def __draw_sample_as_cylinder(self,sample,color,warning_color): a = self.__cylinder_actors.get(sample) if a is not None: a.SetVisibility(1) return p1 = sample.coil_center p2 = sample.sphere_intersection p3 = p1+(p2-p1)*1.2 # an extra 20% to guarantee it goes into the sphere #height = self.COIL_HEIGHT*1.2 height = self.COIL_HEIGHT*500 source = vtk.vtkCylinderSource() source.SetCenter(0,0,0) #source.SetRadius(self.SAMPLE_RADIUS) source.SetRadius(2) source.SetHeight(height) source.SetResolution(8) trans = vtk.vtkTransform() trans.Identity() v1 = p1-p2 v1 /= np.linalg.norm(v1) v2 = (0,1,0) vp = np.cross(v2,v1) angle = np.arcsin(np.linalg.norm(vp)) angle_deg = 180*angle/np.pi trans.Translate(p3) trans.RotateWXYZ(angle_deg,vp) trans.Translate((0,height/2,0)) trans_filter = vtk.vtkTransformPolyDataFilter() trans_filter.SetInputConnection(source.GetOutputPort()) trans_filter.SetTransform(trans) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(trans_filter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.__cylinder_actors[sample]=actor prop = actor.GetProperty() if sample.timing_error > 1: if warning_color is None: warning_color = self.SAMPLE_CYLINDER_WARNING_COLOR prop.SetColor(warning_color) else: if color is None: color = self.SAMPLE_CYLINDER_COLOR prop.SetColor(color) info = vtk.vtkInformation() info.Set(vtk.vtkShadowMapBakerPass.RECEIVER(),0) info.Set(vtk.vtkShadowMapBakerPass.OCCLUDER(),0) #prop.SetAmbient(0.8) actor.SetPropertyKeys(info)
def makeCylinderPtsVTP(locXYZ,radius=50,height=50,res=10): # Load the file if type(locXYZ) == np.ndarray: loc = locXYZ elif type(locXYZ) == str: loc = np.genfromtxt(locXYZ) # Make append poly filter appPoly = vtk.vtkAppendPolyData() # Loop through all the locations for pt in loc[:,0:3]: # Make the cylinters cyl = vtk.vtkCylinderSource() cyl.SetCenter(pt) cyl.SetRadius(radius) cyl.SetHeight(height) cyl.SetResolution(res) # Rotate to be vertical rot = vtk.vtkTransform() rot.Translate(-pt) rot.PostMultiply() rot.RotateX(90) rot.Translate(pt) tranFor = vtk.vtkTransformPolyDataFilter() tranFor.SetInputConnection(cyl.GetOutputPort()) tranFor.SetTransform(rot) tranFor.Update() # Append appPoly.AddInputConnection(tranFor.GetOutputPort()) # Update and return. appPoly.Update() return appPoly.GetOutput()
def Cylinder(self, x, y, z): ''' create a cylinder and return the actor ''' obj = vtk.vtkCylinderSource() actor = self.MapObject(obj) actor.GetProperty().SetColor(0.8, 0.5, 0.3) actor.GetProperty().SetSpecular(0.3) actor.SetPosition(x, y, z)
def create_glyphs (self, poly): if self.glyph_type == 'sphere': glyph = vtk.vtkSphereSource() glyph.SetRadius(1) glyph.SetPhiResolution(8) glyph.SetThetaResolution(8) elif self.glyph_type == 'cylinder': glyph = vtk.vtkCylinderSource() glyph.SetHeight(self.height) glyph.SetRadius(self.radius) glyph.SetCenter(0,0,0) glyph.SetResolution(10) glyph.CappingOn() tt = vtk.vtkTransform() tt.RotateZ(90) tf = vtk.vtkTransformPolyDataFilter() tf.SetInput(glyph.GetOutput()) tf.SetTransform(tt) tf.Update() glypher = vtk.vtkGlyph3D() glypher.SetInput(poly) glypher.SetSource(tf.GetOutput()) glypher.SetVectorModeToUseNormal() glypher.SetScaleModeToScaleByScalar() glypher.SetScaleFactor(self.glyph_scale_factor) glypher.Update() return glypher
def main(): colors = vtk.vtkNamedColors() # Create a sphere cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetCenter(0.0, 0.0, 0.0) cylinderSource.SetRadius(5.0) cylinderSource.SetHeight(7.0) cylinderSource.SetResolution(100) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cylinderSource.GetOutputPort()) actor = vtk.vtkActor() actor.GetProperty().SetColor(colors.GetColor3d("Cornsilk")) actor.SetMapper(mapper) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Cylinder") renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actor to the scene renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d("DarkGreen")) # Render and interact renderWindow.Render() renderWindowInteractor.Start()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkCylinderSource(), 'Processing.', (), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def get_sources(): sources = list() # Create a sphere sphere = vtk.vtkSphereSource() sphere.SetCenter(0.0, 0.0, 0.0) sphere.Update() sources.append(sphere) # Create a cone cone = vtk.vtkConeSource() cone.SetCenter(0.0, 0.0, 0.0) cone.SetDirection(0, 1, 0) cone.Update() sources.append(cone) # Create a cube cube = vtk.vtkCubeSource() cube.SetCenter(0.0, 0.0, 0.0) cube.Update() sources.append(cube) # Create a cylinder cylinder = vtk.vtkCylinderSource() cylinder.SetCenter(0.0, 0.0, 0.0) cylinder.Update() sources.append(cylinder) return sources
def createPlaneActorCircleByCenterAndRot(center, x_rot, z_rot): # TODO: rename me cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(50) cylinder.SetRadius(params.PlaneDiameter / 3) # TODO: remove hardcode cylinder.SetHeight(0.1) # cylinder.SetCenter(center[0], center[2] - 0.1, center[1]) # WHAT? vtk :( mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cylinder.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(params.PlaneColor) actor.GetProperty().SetOpacity(0.3) actor.RotateX(90) # actor.RotateX(x_rot) # actor.SetPosition(center[0], center[1],center[2] - 0.1) # actor.RotateY(x_rot) # actor.GetUserTransform() transform = vtk.vtkTransform() transform.PostMultiply() transform.RotateX(x_rot) transform.PostMultiply() transform.RotateZ(z_rot) transform.Translate(center[0], center[1], center[2] - 0.1) actor.SetUserTransform(transform) return actor
def __init__(self, renderers, radius = 2.0, height = 8.0, rotationXYZ = [0, 0, 0], offsetXYZ = [0, 0, 0]): ''' Initialize the cylinder. ''' # Call the parent constructor super(Cylinder,self).__init__(renderers) cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetCenter(0.0, 0.0, 0.0) cylinderSource.SetRadius(radius) cylinderSource.SetHeight(height) # Make it a little more defined cylinderSource.SetResolution(24) # Transform scale it to the right size trans = vtk.vtkTransform() trans.Scale(1, 1, 1) trans.Translate(offsetXYZ[0], offsetXYZ[1], offsetXYZ[2]) trans.RotateZ(rotationXYZ[2]) trans.RotateX(rotationXYZ[0]) trans.RotateY(rotationXYZ[1]) transF = vtk.vtkTransformPolyDataFilter() transF.SetInputConnection(cylinderSource.GetOutputPort()) transF.SetTransform(trans) cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(transF.GetOutputPort()) self.vtkActor.SetMapper(cylinderMapper) # Change it to a red sphere self.vtkActor.GetProperty().SetColor(0.8, 0.8, 0.3)
def createCylinderActor(color=None, radius=0.25, height=0.3, center=None, ): cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(128) cylinder.SetRadius(radius) cylinder.SetHeight(height) cylinderMapper = vtk.vtkPolyDataMapper() polyDataFilter = vtk.vtkTransformPolyDataFilter() polyDataFilter.SetInputConnection(cylinder.GetOutputPort()) transform = vtk.vtkTransform() if center is not None: transform.Translate(*center) else: transform.Translate(0,0,height/2) transform.RotateWXYZ(90, 1,0,0) polyDataFilter.SetTransform(transform) cylinderMapper.SetInputConnection(polyDataFilter.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) if color is not None: cylinderActor.GetProperty().SetColor(color) return cylinderActor
def __init__(self,center=(0,-2,0) , radius=0.5, height=2, color=(0,1,1), rotXYZ=(0,0,0), resolution=50 ): """ cylinder """ self.src = vtk.vtkCylinderSource() self.src.SetCenter(0,0,0) self.src.SetHeight(height) self.src.SetRadius(radius) self.src.SetResolution(resolution) # SetResolution # SetCapping(int) # CappingOn() CappingOff() # this transform rotates the cylinder so it is vertical # and then translates the lower tip to the center point transform = vtk.vtkTransform() transform.Translate(center[0], center[1], center[2]+height/2) transform.RotateX(rotXYZ[0]) transformFilter=vtk.vtkTransformPolyDataFilter() transformFilter.SetTransform(transform) transformFilter.SetInputConnection(self.src.GetOutputPort()) transformFilter.Update() self.mapper = vtk.vtkPolyDataMapper() #self.mapper.SetInput(self.src.GetOutput()) self.mapper.SetInput( transformFilter.GetOutput() ) self.SetMapper(self.mapper) self.SetColor(color)
def createCylinderMesh(self, center, direction, radius=1.0, height=1.0): startPoint = [ center[i] - direction[i] * height / 2.0 for i in range(3) ] cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetResolution(8) cylinderSource.SetRadius(radius) cylinderSource.Update() normalizedX = direction normalizedY = [0, 0, 0] normalizedZ = [0, 0, 0] vtk.vtkMath.Normalize(normalizedX) arbitrary = [1, 1, 1] vtk.vtkMath.Cross(normalizedX, arbitrary, normalizedZ) vtk.vtkMath.Normalize(normalizedZ) vtk.vtkMath.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) transform = vtk.vtkTransform() transform.Translate(startPoint) transform.Concatenate(matrix) transform.RotateZ(-90.0) transform.Scale(1.0, height, 1.0) transform.Translate(0, .5, 0) transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetTransform(transform) transformPD.SetInputConnection(cylinderSource.GetOutputPort()) transformPD.Update() return transformPD.GetOutputDataObject(0)
def recomputePath(self): cylinderCenter = ((self.cylinderTop + self.cylinderBottom) / 2) cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetCenter(cylinderCenter) cylinderAxis = (self.cylinderTop - self.cylinderBottom) normalizedCylinderAxis = cylinderAxis / np.sqrt( sum(cylinderAxis * cylinderAxis)) cylinderEnd = cylinderCenter + (self.cylinderHeight / 2) * normalizedCylinderAxis plane = vtk.vtkPlane() plane.SetNormal(normalizedCylinderAxis) plane.SetOrigin(cylinderEnd) upAxis = np.array([0, 1, 0]) sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(self.sphereOrigin) cylinderSource.SetRadius(self.cylinderRadius) cylinderSource.SetHeight(self.cylinderHeight) sphereSource.SetRadius(self.sphereRadius) cylinderTransform = vtk.vtkTransform() cylinderTransform.PostMultiply() cylinderTransform.Translate(-cylinderCenter[0], -cylinderCenter[1], -cylinderCenter[2]) cylinderTransform.RotateWXYZ( -1 * np.degrees(self.py_ang(cylinderAxis, upAxis)), np.cross(cylinderAxis, upAxis)) cylinderTransform.Translate(cylinderCenter[0], cylinderCenter[1], cylinderCenter[2]) self.cylinderPolyDataFilter.SetInputConnection( cylinderSource.GetOutputPort()) self.cylinderPolyDataFilter.SetTransform(cylinderTransform) self.cylinderPolyDataFilter.Update()
def __init__(self, center=(0, -2, 0), radius=0.5, height=2, color=(0, 1, 1), rotXYZ=(0, 0, 0), resolution=50): """ cylinder """ self.src = vtk.vtkCylinderSource() self.src.SetCenter(0, 0, 0) self.src.SetHeight(height) self.src.SetRadius(radius) self.src.SetResolution(resolution) # SetResolution # SetCapping(int) # CappingOn() CappingOff() # this transform rotates the cylinder so it is vertical # and then translates the lower tip to the center point transform = vtk.vtkTransform() transform.Translate(center[0], center[1], center[2] + height / 2) transform.RotateX(rotXYZ[0]) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetTransform(transform) transformFilter.SetInputConnection(self.src.GetOutputPort()) transformFilter.Update() self.mapper = vtk.vtkPolyDataMapper() #self.mapper.SetInput(self.src.GetOutput()) self.mapper.SetInput(transformFilter.GetOutput()) self.SetMapper(self.mapper) self.SetColor(color)
def CylinderSource(self, currentElement): source = vtk.vtkCylinderSource() try: source.SetRadius( float(currentElement.get('SetRadius')) ) except: self.logger.error(' .. <CylinderSource> failed to SetRadius') if 'SetHeight' in currentElement.keys(): try: source.SetHeight( float(currentElement.get('SetHeight')) ) except: self.logger.error(' .. <CylinderSource> failed to SetHeight') if 'boneLength' in currentElement.keys(): try: source.SetHeight( self.bonelengths[currentElement.get('boneLength')] ) except: self.logger.error(' .. <CylinderSource> failed to SetHeight from boneLength') if 'SetResolution' in currentElement.keys(): try: source.SetResolution( int(currentElement.get('SetResolution')) ) except: self.logger.error(' .. <CylinderSource> failed to SetResolution') if 'SetCapping' in currentElement.keys(): try: source.SetCapping( int(currentElement.get('SetCapping')) ) except: self.logger.error(' .. <CylinderSource> failed to SetCapping') return source
def testEncodings(self): # Render something cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(8) cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.RotateX(30.0) cylinderActor.RotateY(-45.0) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) ren.AddActor(cylinderActor) renWin.SetSize(200, 200) ren.ResetCamera() ren.GetActiveCamera().Zoom(1.5) renWin.Render() # Get a vtkImageData with the rendered output w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(renWin) w2if.SetShouldRerender(1) w2if.SetReadFrontBuffer(0) w2if.Update() imgData = w2if.GetOutput() # Use vtkDataEncoder to convert the image to PNG format and Base64 encode it encoder = vtk.vtkDataEncoder() base64String = encoder.EncodeAsBase64Png(imgData).encode('ascii') # Now Base64 decode the string back to PNG image data bytes inputArray = array.array('B', base64String) outputBuffer = bytearray(len(inputArray)) utils = vtk.vtkIOCore.vtkBase64Utilities() actualLength = utils.DecodeSafely(inputArray, len(inputArray), outputBuffer, len(outputBuffer)) outputArray = bytearray(actualLength) outputArray[:] = outputBuffer[0:actualLength] # And write those bytes to the disk as an actual PNG image file with open('TestDataEncoder.png', 'wb') as fd: fd.write(outputArray) # Create a vtkTesting object and specify a baseline image rtTester = vtk.vtkTesting() for arg in sys.argv[1:]: rtTester.AddArgument(arg) rtTester.AddArgument("-V") rtTester.AddArgument("TestDataEncoder.png") # Perform the image comparison test and print out the result. result = rtTester.RegressionTest("TestDataEncoder.png", 0.0) if result == 0: raise Exception("TestDataEncoder failed.")
def __init__(self): self.cylinder = vtk.vtkCylinderSource() self.cylinder.SetRadius(2.5) self.cylinder.SetHeight(50) self.cylinder.SetCenter(0, 0, 0) self.cylinder.SetResolution(100) self.vtkActor = None
def vtkdisk(c=(0, 0, 1)): # create a rendering window and renderer # ren = vtk.vtkRenderer() # renWin = vtk.vtkRenderWindow() # renWin.AddRenderer(ren) # create a renderwindowinteractor # iren = vtk.vtkRenderWindowInteractor() # iren.SetRenderWindow(renWin) # create source source = vtk.vtkDiskSource() source = vtk.vtkCylinderSource() source.SetCenter(c) source.SetRadius(0.01) # source.SetOuterRadius(.2) source.SetResolution(10) source.SetHeight(0.001) # source.SetCircumferentialResolution(100) source.Update() # source2.SetCenter(.3,0,0) # source2.Update() # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) # actor diskactor = vtk.vtkActor() diskactor.SetMapper(mapper) return diskactor
def drawVtkSymb(symbType,renderer, RGBcolor, vPos, vDir, scale): '''Adds to the renderer a symbol of type 'arrow', 'doubleArrow', 'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' , 'doubleCube', 'cylinder', 'doubleCylinder' :param symbType: type of symbol (available types: 'arrow', 'doubleArrow', 'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' , 'doubleCube', 'cylinder', 'doubleCylinder') :param renderer: vtk renderer :param RGBcolor: list [R,G,B] with the 3 components of color :param vPos: list [x,y,z] with the 3 coordinates of the point where to place the symbol. :param vDir: director vector to orient the symbol :param scale: scale to be applied to the symbol representation ''' symTpLow=symbType.lower() if 'arrow' in symTpLow: symbSource=vtk.vtkArrowSource() elif 'cone' in symTpLow: symbSource=vtk.vtkConeSource() elif 'sphere' in symTpLow: symbSource=vtk.vtkSphereSource() elif 'cube' in symTpLow: symbSource=vtk.vtkCubeSource() elif 'cylinder' in symTpLow: symbSource=vtk.vtkCylinderSource() vPosVx=[vPos[i]-scale/2.0*vDir[i] for i in range(3)] #vertex position addSymb(symbSource,renderer, RGBcolor, vPosVx, vDir, scale) if 'double' in symTpLow: vPosVx=[vPosVx[i]-scale*vDir[i] for i in range(3)] #vertex position addSymb(symbSource,renderer, RGBcolor, vPosVx, vDir, scale)
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.frame = QtGui.QFrame() layout = QtGui.QVBoxLayout() self.vtkWidget = \ QVTKRenderWindowInteractor(self.frame) layout.addWidget(self.vtkWidget) self.renderer = vtk.vtkRenderer() rw = self.vtkWidget.GetRenderWindow() rw.AddRenderer(self.renderer) self.interactor = rw.GetInteractor() cylinder = vtk.vtkCylinderSource() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection( \ cylinder.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) self.renderer.AddActor(actor) self.renderer.ResetCamera() self.frame.setLayout(layout) self.setCentralWidget(self.frame) self.show() self.interactor.Initialize()
def testEncodings(self): # Render something cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(8) cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.RotateX(30.0) cylinderActor.RotateY(-45.0) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) ren.AddActor(cylinderActor) renWin.SetSize(200, 200) ren.ResetCamera() ren.GetActiveCamera().Zoom(1.5) renWin.Render() # Get a vtkImageData with the rendered output w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(renWin) w2if.SetShouldRerender(1) w2if.SetReadFrontBuffer(0) w2if.Update() imgData = w2if.GetOutput() # Use vtkDataEncoder to convert the image to PNG format and Base64 encode it encoder = vtk.vtkDataEncoder() base64String = encoder.EncodeAsBase64Png(imgData).encode('ascii') # Now Base64 decode the string back to PNG image data bytes outputBuffer = bytearray(120000) inputArray = array.array('B', base64String) utils = vtk.vtkIOCore.vtkBase64Utilities() actualLength = utils.Decode(inputArray, 120000, outputBuffer) outputArray = bytearray(actualLength) outputArray[:] = outputBuffer[0:actualLength] # And write those bytes to the disk as an actual PNG image file with open('TestDataEncoder.png', 'wb') as fd: fd.write(outputArray) # Create a vtkTesting object and specify a baseline image rtTester = vtk.vtkTesting() for arg in sys.argv[1:]: rtTester.AddArgument(arg) rtTester.AddArgument("-V") rtTester.AddArgument("TestDataEncoder.png") # Perform the image comparison test and print out the result. result = rtTester.RegressionTest("TestDataEncoder.png", 0.0) if result == 0: raise Exception("TestDataEncoder failed.")
def __init__(self, models_json_file, background_image_file, camera_intrinsics_file, liver2camera_reference_file, probe2camera_reference_file, camera_to_world=None, left_to_right=None, offscreen=False, zbuffer=False, clipping_range=(1, 1000)): super().__init__(models_json_file, background_image_file, camera_intrinsics_file, camera_to_world=camera_to_world, left_to_right=left_to_right, offscreen=offscreen, zbuffer=zbuffer, gaussian_sigma=0, gaussian_window_size=11, clipping_range=clipping_range) self.reference_l2c = np.loadtxt(liver2camera_reference_file) self.reference_p2c = np.loadtxt(probe2camera_reference_file) self.cyl = vtk.vtkCylinderSource() self.cyl.SetResolution(88) self.cyl.SetRadius(5) self.cyl.SetHeight(1000) self.cyl.SetCenter((0, self.cyl.GetHeight() / 2.0, 0)) self.cyl.Update() self.cyl_matrix = vtk.vtkMatrix4x4() self.cyl_matrix.Identity() self.cyl_trans = vtk.vtkTransform() self.cyl_trans.SetMatrix(self.cyl_matrix) self.cyl_transform_filter = vtk.vtkTransformPolyDataFilter() self.cyl_transform_filter.SetInputData(self.cyl.GetOutput()) self.cyl_transform_filter.SetTransform(self.cyl_trans) self.cyl_mapper = vtk.vtkPolyDataMapper() self.cyl_mapper.SetInputConnection( self.cyl_transform_filter.GetOutputPort()) self.cyl_mapper.Update() self.cyl_actor = vtk.vtkActor() self.cyl_actor.SetMapper(self.cyl_mapper) probe_model = self.model_loader.get_surface_model('probe') probe_colour = probe_model.get_colour() self.cyl_actor.GetProperty().SetColor(probe_colour) if probe_model.get_no_shading(): self.cyl_actor.GetProperty().SetAmbient(1) self.cyl_actor.GetProperty().SetDiffuse(0) self.cyl_actor.GetProperty().SetSpecular(0) self.overlay.add_vtk_actor(self.cyl_actor) self.set_clipping_range(clipping_range[0], clipping_range[1]) self.setup_camera_extrinsics(camera_to_world, left_to_right)
def cylinderFactory(height, radius, resolution): cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(resolution) cylinder.SetRadius(radius) cylinder.SetHeight(height) return cylinder
def getVtkSource(self): cylinder = kwvtk.vtkCylinderSource() cylinder.SetRadius(self.getRadius()) cylinder.SetCenter(self.getCenter()) cylinder.SetHeight(self.getHeight()) cylinder.SetResolution(10) return cylinder
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkCylinderSource(), 'Processing.', (), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def work(numbers): Raw_data = gzip.open('VTK_Data.pickle.gz', 'rb') Subjects_data, Label, ID, Age, Weight = Pickle.load(Raw_data) subjectNo1 = int(numbers[0]) subjectNo2 = int(numbers[1]) data1 = Subjects_data[subjectNo1 * 130:(subjectNo1 + 1) * 130, :] data2 = Subjects_data[subjectNo2 * 130:(subjectNo2 + 1) * 130, :] print("First subject is", Label[subjectNo1]) print('Second subject is', Label[subjectNo2]) #Create a sphere cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetResolution(8) cylinderSource.SetRadius(6.0) cylinderSource.SetHeight(0.8 * augment_ratio) #Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cylinderSource.GetOutputPort()) actor1 = vtk.vtkActor() actor2 = vtk.vtkActor() actor1.SetMapper(mapper) actor2.SetMapper(mapper) # prop = actor.GetProperty() # Setup a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() camera = vtk.vtkCamera() camera.SetPosition(0, (bottomLine1 + bottomLine2) / 2, -550) renderer.SetActiveCamera(camera) renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) #Add the actor to the scene renderer.AddActor(actor1) renderer.AddActor(actor2) renderer.SetBackground(1, 1, 1) # Background color white renderWindow.SetSize(700, 400) #Render and interact renderWindow.Render() # Initialize must be called prior to creating timer events. renderWindowInteractor.Initialize() # Sign up to receive TimerEvent cb = vtkTimerCallback(data1, data2) cb.actor1 = actor1 cb.actor2 = actor2 renderWindowInteractor.AddObserver('TimerEvent', cb.execute) timerId = renderWindowInteractor.CreateRepeatingTimer(1000) #start the interaction and timer renderWindowInteractor.Start()
def add_cyl(self, pt1, pt2): cyl = vtk.vtkCylinderSource() r = 0.1 cyl.SetRadius(r) cyl.SetResolution(15) x = [0,0,0] y = [0,0,0] z = [0,0,0] vtk.vtkMath.Subtract(pt2, pt1, x) length = vtk.vtkMath.Norm(x) vtk.vtkMath.Normalize(x) #print("length: " + str(length)) arbitrary = [0,0,0] arbitrary[0] = vtk.vtkMath.Random(-10,10) arbitrary[1] = vtk.vtkMath.Random(-10,10) arbitrary[2] = vtk.vtkMath.Random(-10,10) vtk.vtkMath.Cross(x, arbitrary, z) vtk.vtkMath.Normalize(z) vtk.vtkMath.Cross(z, x, y) matrix = vtk.vtkMatrix4x4() matrix.Identity() for i in range(3): matrix.SetElement(i, 0, x[i]) matrix.SetElement(i, 1, y[i]) matrix.SetElement(i, 2, z[i]) #print("x: " + str(x)) #print("y: " + str(y)) #print("z: " + str(z)) transform = vtk.vtkTransform() transform.Translate(pt1) transform.Concatenate(matrix); transform.RotateZ(-90.0) transform.Scale(1.0, length, 1.0) transform.Translate(0, 0.5, 0) transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetTransform(transform) transformPD.SetInputConnection(cyl.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() actor = vtk.vtkActor() #mapper.SetInputConnection(transformPD.GetOutputPort()) mapper.SetInputConnection(cyl.GetOutputPort()) actor.SetUserMatrix(transform.GetMatrix()) actor.GetProperty().SetColor(1.0, 0.0, 0.0) actor.SetMapper(mapper) self.renderer.AddActor(actor) """
def cylinder(radius, height, resolution): cylinder_shape = vtk.vtkCylinderSource() cylinder_shape.SetRadius(radius) cylinder_shape.SetHeight(height) cylinder_shape.SetResolution(resolution) cylinder_shape.Update() mapp_object = vtk.vtkPolyDataMapper() mapp_object.SetInputData(cylinder_shape.GetOutput()) return mapp_object
def CreateLine(): cylinder = vtk.vtkCylinderSource() cylinder.SetCenter(0,0,0) cylinder.SetRadius(1.0) cylinder.SetHeight(200) cylinder.SetResolution(100) cylinder.Update() source = cylinder.GetOutput() return source
def cylinder(pos=[0, 0, 0], r=1, height=1, axis=[0, 0, 1], c='teal', wire=0, alpha=1, legend=None, texture=None, res=24): ''' Build a cylinder of specified height and radius r, centered at pos. If pos is a list of 2 points, e.g. pos=[v1,v2], build a cylinder with base centered at v1 and top at v2. [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/gyroscope1.py) [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/turing.py) ''' if utils.isSequence(pos[0]): # assume user is passing pos=[base, top] base = np.array(pos[0]) top = np.array(pos[1]) pos = (base + top) / 2 height = np.linalg.norm(top - base) axis = top - base axis = utils.norm(axis) else: axis = utils.norm(axis) base = pos - axis * height / 2 top = pos + axis * height / 2 cyl = vtk.vtkCylinderSource() cyl.SetResolution(res) cyl.SetRadius(r) cyl.SetHeight(height) cyl.Update() theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateX(90) # put it along Z t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(cyl.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha, wire, legend=legend, texture=texture) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) actor.base = base actor.top = top return actor
def create_vtk_example_mesh_actor(opacity=1.0): cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(8) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cylinder.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) return actor
def visualize(): A = initPoints(particleA) B = initPoints(particleB) C = initPoints(particleC) displayDict = {} # Set up the renderer and redering window renderer = vtk.vtkRenderer() renwin = vtk.vtkRenderWindow() renwin.SetSize(1600, 1400) renwin.StereoCapableWindowOn() renwin.StereoRenderOn() renwin.SetStereoTypeToCrystalEyes() renwin.AddRenderer(renderer) ptsComp = vtk.vtkPoints() posComp = vnp.numpy_to_vtk(np.array([[0, 0, 0]], order='C'), deep=True) ptsComp.SetData(posComp) polyDataComp = vtk.vtkPolyData() polyDataComp.SetPoints(ptsComp) sourceComp = vtk.vtkCylinderSource() sourceComp.SetResolution(20) sourceComp.SetRadius(compartment['radius'] + particleScale) sourceComp.SetHeight(compartment['length'] + 2 * particleScale) sourceComp.SetCenter(0, -compartment['length']/2, 0) glyphComp = vtk.vtkGlyph3D() glyphComp.SetSource(sourceComp.GetOutput()) glyphComp.SetInput(polyDataComp) glyphComp.ScalingOff() # glyphComp.SetScaleModeToDefault() # glyphComp.SetScaleFactor(particleScale) mapperComp = vtk.vtkPolyDataMapper() mapperComp.SetInput(glyphComp.GetOutput()) mapperComp.ImmediateModeRenderingOn() actorComp = vtk.vtkActor() actorComp.SetMapper(mapperComp) actorComp.GetProperty().SetOpacity(0.2) actorComp.GetProperty().SetColor(1, 1, 1) actorComp.SetOrientation(0, 90, 90) renderer.AddActor(actorComp) renderer.AddActor(A['actor']) renderer.AddActor(B['actor']) renderer.AddActor(C['actor']) print 'Create camera' camera = vtk.vtkCamera() camera.SetPosition(300e-6, 200.0e-6, -300.0e-6) camera.SetFocalPoint(0, 0, 0) camera.ComputeViewPlaneNormal() renderer.SetActiveCamera(camera) renderer.ResetCamera() interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) callback = TimerCallback(A, B, C) interactor.Initialize() interactor.AddObserver('TimerEvent', callback.execute) timerId = interactor.CreateRepeatingTimer(1) print 'Here' # renwin.FullScreenOn() interactor.Start()
def __init__(self, render, parent=None): self.colorTable = vtk.vtkNamedColors() super(createCylinder, self).__init__(parent) self.render = render self.cylinder = vtk.vtkCylinderSource() self.setupUi(self) self.validInput() self.monitor() self.drawCylinder()
def create_cylinder(self, ii, t, offset): # pas = 3*self.L pas = 0 cylinder = vtk.vtkCylinderSource() cylinder.SetCenter(pas * t, self.L * (ii + offset), 0) cylinder.SetRadius(self.L) cylinder.SetHeight(self.L) cylinder.SetResolution(100) return cylinder
def create_oriented_cylinder_actor(self, x1=None, x2=None, lux=0.0, luy=0.0, colour=None, opacity=0.0): # Create a cylinder. # Cylinder height vector is (0,1,0). # Cylinder center is in the middle of the cylinder cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetResolution(15) cylinderSource.CappingOff() # Compute a basis normalizedX = [0] * 3 normalizedY = [0] * 3 normalizedZ = [0] * 3 # The X axis is a vector from start to end vtk.vtkMath.Subtract(x2, x1, normalizedX) length = vtk.vtkMath.Norm(normalizedX) vtk.vtkMath.Normalize(normalizedX) # The Z axis is an Y vector cross X arbitrary = [0.0, 1.0, 0.0] vtk.vtkMath.Cross(normalizedX, arbitrary, normalizedZ) vtk.vtkMath.Normalize(normalizedZ) # The Y axis is Z cross X vtk.vtkMath.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(0, 3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) # Apply the transforms transform = vtk.vtkTransform() transform.Translate(x1) # translate to starting point transform.Concatenate(matrix) # apply direction cosines transform.RotateZ(-90.0) # align cylinder to x axis transform.Scale(luy, length, lux) # scale along the height vector transform.Translate(0, .5, 0) # translate to start of cylinder # Transform the polydata transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetTransform(transform) transformPD.SetInputConnection(cylinderSource.GetOutputPort()) # Create a mapper and actor for the arrow mapper = vtk.vtkPolyDataMapper() actor = vtk.vtkActor() mapper.SetInputConnection(transformPD.GetOutputPort()) actor.SetMapper(mapper) if len(colour): actor.GetProperty().SetColor(colour[0], colour[1], colour[2]) actor.GetProperty().SetOpacity(opacity) return actor
def get_cylinder(upper, height, radius, direction, resolution=10): import vtk src = vtk.vtkCylinderSource() src.SetCenter((0, height / 2, 0)) # src.SetHeight(height + radius/2.0) src.SetHeight(height) src.SetRadius(radius) src.SetResolution(resolution) return move_to_position(src, upper, direction).GetOutput()
def __init__(self): self.source = vtk.vtkCylinderSource() self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.source.GetOutputPort()) self.mapper.Update() self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper)
def basic_cyclinder(): """ Basic attributes of a cylinder used by segment """ cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(15) cylinder.SetHeight(1) cylinder.SetRadius(0.03) return cylinder
def Cylinder(center=(0., 0., 0.), direction=(1., 0., 0.), radius=0.5, height=1.0, resolution=100, capping=True, **kwargs): """Create the surface of a cylinder. See also :func:`pyvista.CylinderStructured`. Parameters ---------- center : list or np.ndarray Location of the centroid in [x, y, z] direction : list or np.ndarray Direction cylinder points to in [x, y, z] radius : float Radius of the cylinder. height : float Height of the cylinder. resolution : int Number of points on the circular face of the cylinder. capping : bool, optional Cap cylinder ends with polygons. Default True Return ------ cylinder : pyvista.PolyData Cylinder surface. Examples -------- >>> import pyvista >>> import numpy as np >>> cylinder = pyvista.Cylinder(np.array([1, 2, 3]), np.array([1, 1, 1]), 1, 1) >>> cylinder.plot() # doctest:+SKIP """ capping = kwargs.pop('cap_ends', capping) assert_empty_kwargs(**kwargs) cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetRadius(radius) cylinderSource.SetHeight(height) cylinderSource.SetCapping(capping) cylinderSource.SetResolution(resolution) cylinderSource.Update() surf = pyvista.PolyData(cylinderSource.GetOutput()) surf.rotate_z(-90) translate(surf, center, direction) return surf
def cylinderMapper(): colors = vtk.vtkNamedColors() # Set the background color. bkg = map(lambda x: x / 255.0, [26, 51, 102, 255]) colors.SetColor("BkgColor", *bkg) # This creates a polygonal cylinder model with eight circumferential # facets. cylinder = vtk.vtkCylinderSource() cylinder.SetResolution(100) # The mapper is responsible for pushing the geometry into the graphics # library. It may also do color mapping, if scalars or other # attributes are defined. cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) # The actor is a grouping mechanism: besides the geometry (mapper), it # also has a property, transformation matrix, and/or texture map. # Here we set its color and rotate it -22.5 degrees. cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.GetProperty().SetColor(colors.GetColor3d("Tomato")) cylinderActor.RotateX(30.0) cylinderActor.RotateY(-45.0) # Create the graphics structure. The renderer renders into the render # window. The render window interactor captures mouse events and will # perform appropriate camera or actor manipulation depending on the # nature of the events. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size ren.AddActor(cylinderActor) ren.SetBackground(colors.GetColor3d("BkgColor")) renWin.SetSize(300, 300) renWin.SetWindowName('Cylinder') # This allows the interactor to initalize itself. It has to be # called before an event loop. iren.Initialize() # We'll zoom in a little by accessing the camera and invoking a "Zoom" # method on it. ren.ResetCamera() ren.GetActiveCamera().Zoom(1.5) renWin.Render() # Start the event loop. iren.Start()
def SetTrunk(self, radio, height, resolution): self.cylinder = vtk.vtkCylinderSource() self.cylinder.SetRadius(radio) self.cylinder.SetHeight(height) self.cylinder.SetResolution(resolution) self.cylinder.Update() #mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(self.cylinder.GetOutput()) return mapper
def display_cylinder(self, actorName, vec3_origin, vec3_direction, height, radius, vec3_color): cyl = vtk.vtkCylinderSource() cyl.SetRadius(radius) cyl.SetHeight(height) cyl.SetCapping(1) cyl.Update() # transform to center with orientation according to normal axis1 = [vec3_direction[0], vec3_direction[1], vec3_direction[2]] axis2 = np.cross(axis1, [1, 1, 1]) axis2 = axis2 / np.linalg.norm(axis2) axis3 = np.cross(axis2, axis1) # print axis1 # print axis2 # print axis3 trans = np.eye(4) trans[0, 0] = axis2[0] trans[0, 1] = axis1[0] trans[0, 2] = axis3[0] trans[0, 3] = vec3_origin[0] trans[1, 0] = axis2[1] trans[1, 1] = axis1[1] trans[1, 2] = axis3[1] trans[1, 3] = vec3_origin[1] trans[2, 0] = axis2[2] trans[2, 1] = axis1[2] trans[2, 2] = axis3[2] trans[2, 3] = vec3_origin[2] trans[3, 0] = 0 trans[3, 1] = 0 trans[3, 2] = 0 trans[3, 3] = 1 vtk_trans = vtk.vtkMatrix4x4() for i in range(0, 4): for j in range(0, 4): vtk_trans.SetElement(i, j, trans[i, j]) ar_trans = vtk.vtkTransform() ar_trans.SetMatrix(vtk_trans) ar_trans_filter = vtk.vtkTransformPolyDataFilter() ar_trans_filter.SetTransform(ar_trans) ar_trans_filter.SetInputConnection(cyl.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(ar_trans_filter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(vec3_color[0], vec3_color[1], vec3_color[2]) self.ren.AddActor(actor) self.name2actor[actorName] = actor return
def __init__(self, geom, ident=None): self.src = vtkCylinderSource() ODE_Object.__init__(self, geom, ident) (radius, height) = self.geom.getParams() self.src.SetRadius(radius) self.src.SetHeight(height) self.src.SetResolution(20)
def draw_block_error(self,block): #universal if self.__error_triple is None: big_r = self.experiment.sphere_radius height = big_r*0.05 source = vtk.vtkCylinderSource() source.SetCenter(0,0,0) source.SetResolution(20) source.CappingOff() source.SetHeight(height) trans = vtk.vtkTransform() trans_filter = vtk.vtkTransformPolyDataFilter() trans_filter.SetInputConnection(source.GetOutputPort()) trans_filter.SetTransform(trans) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(trans_filter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.__error_actor = actor prop = actor.GetProperty() prop.SetColor(self.ERROR_COLOR) prop.SetOpacity(0.8) self.__error_triple = (source,trans,actor) else: source,trans,actor = self.__error_triple actor.SetVisibility(1) #specific big_r = self.experiment.sphere_radius height = big_r*0.05 radius = block.circle_radius rel_center = block.circle_relative_center sphere_center = self.experiment.sphere_center circle_center = sphere_center+rel_center source.SetRadius(radius) trans.Identity() v1 = rel_center / np.linalg.norm(rel_center) v2 = (0,1,0) vp = np.cross(v2,v1) angle = np.arcsin(np.linalg.norm(vp)) angle_deg = 180*angle/np.pi trans.Translate(circle_center) trans.RotateWXYZ(angle_deg,vp) trans.Translate((0,height/2,0))
def get_cylinder(upper, height, radius, direction, resolution=10): src = vtk.vtkCylinderSource() src.SetCenter((0, height/2, 0)) src.SetHeight(height + radius/2.0) src.SetRadius(radius) src.SetResolution(resolution) rot1 = vtk.vtkTransform() fi = nm.arccos(direction[1]) rot1.RotateWXYZ(-nm.rad2deg(fi), 0.0, 0.0, 1.0) u = nm.abs(nm.sin(fi)) rot2 = vtk.vtkTransform() if u > 1.0e-6: # sometimes d[0]/u little bit is over 1 d0_over_u = direction[0] / u if d0_over_u > 1: psi = 0 elif d0_over_u < -1: psi = 2 * nm.pi else: psi = nm.arccos(direction[0] / u) logger.debug('d0 '+str(direction[0])+' u '+str(u)+' psi '+str(psi)) if direction[2] < 0: psi = 2 * nm.pi - psi rot2.RotateWXYZ(-nm.rad2deg(psi), 0.0, 1.0, 0.0) tl = vtk.vtkTransform() tl.Translate(upper) tr1a = vtk.vtkTransformFilter() tr1a.SetInput(src.GetOutput()) tr1a.SetTransform(rot1) tr1b = vtk.vtkTransformFilter() tr1b.SetInput(tr1a.GetOutput()) tr1b.SetTransform(rot2) tr2 = vtk.vtkTransformFilter() tr2.SetInput(tr1b.GetOutput()) tr2.SetTransform(tl) tr2.Update() return tr2.GetOutput()
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 setup(self): self.head = ObjectBase(vtk.vtkConeSource()) self.head._source.SetRadius(0.2) self.head._source.SetHeight(0.25) self.head._source.SetResolution(18) self.head._actor.SetPosition(0.625, 0.0, 0.0) self.head._actor.GetProperty().SetAmbient(0.4) self.addPart(self.head) self.body = ObjectBase(vtk.vtkCylinderSource()) self.body._source.SetHeight(1.0) self.body._source.SetRadius(0.1) self.body._source.SetResolution(18) self.body._actor.RotateZ(90) self.body._actor.GetProperty().SetAmbient(0.4) self.addPart(self.body) self.rgbCalc = Helpers.RgbCalculator(-1.0, 1.0)
def create_cylinder(self): # create source source = vtk.vtkCylinderSource() source.SetCenter(0,0,0) source.SetRadius(5.0) source.SetHeight(7.0) source.SetResolution(100.0) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) # assign actor to the renderer self.render.AddActor(actor)
def __init__(self, renderer): ''' Initialize the cylinder. ''' # Call the parent constructor super(Cylinder,self).__init__(renderer) cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetCenter(0.0, 0.0, 0.0) cylinderSource.SetRadius(2.0) cylinderSource.SetHeight(8.0) # Make it a little more defined cylinderSource.SetResolution(24) cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinderSource.GetOutputPort()) self.vtkActor.SetMapper(cylinderMapper) # Change it to a red sphere self.vtkActor.GetProperty().SetColor(0.8, 0.8, 0.3)
def create_glyphs (self, poly): if self.glyph_type == 'sphere': glyph = vtk.vtkSphereSource() glyph.SetRadius(1) glyph.SetPhiResolution(8) glyph.SetThetaResolution(8) elif self.glyph_type == 'cylinder': glyph = vtk.vtkCylinderSource() glyph.SetHeight(self.height) glyph.SetRadius(self.radius) glyph.SetCenter(0,0,0) glyph.SetResolution(10) glyph.CappingOn() tt = vtk.vtkTransform() tt.RotateZ(90) tf = vtk.vtkTransformPolyDataFilter() tf.SetInput(glyph.GetOutput()) tf.SetTransform(tt) tf.Update() glypher = vtk.vtkGlyph3D() glypher.SetInput(poly) glypher.SetSource(tf.GetOutput()) glypher.SetVectorModeToUseNormal() glypher.SetScaleModeToScaleByScalar() glypher.SetScaleFactor(self.glyph_scale_factor) print "Scale factor %f" % self.glyph_scale_factor glypher.Update() # Color the glyph according to whatever other value is in the vtk file glypher.GetOutput().GetPointData().SetScalars(glypher.GetOutput().GetPointData().GetArray("h2")) # print(glypher.GetOutput()) return glypher
def set_glyph_mode (self, event=None): debug ("In Glyph::set_glyph_mode ()") Common.state.busy () val = self.glyph_var.get () if val == 0: # 2d glyph self.glyph_src = vtk.vtkGlyphSource2D () self.glyph_src.SetGlyphTypeToArrow () elif val == 1: # Cone self.glyph_src = vtk.vtkConeSource() elif val == 2: # Sphere self.glyph_src = vtk.vtkSphereSource() self.glyph_src.SetPhiResolution(4) self.glyph_src.SetThetaResolution(4) elif val == 3: # Cube self.glyph_src = vtk.vtkCubeSource() elif val == 4: # Cylinder self.glyph_src = vtk.vtkCylinderSource() elif val == 5: # 3D arrow self.glyph_src = vtk.vtkArrowSource() self.glyph.SetSource (self.glyph_src.GetOutput ()) self.renwin.Render () Common.state.idle ()
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # This example demonstrates how to set up flexible joints using # the transformation pipeline and vtkTransformPolyDataFilter. # create a rendering window and renderer ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) # set up first set of polydata c1 = vtk.vtkCylinderSource() c1.SetHeight(1.6) c1.SetRadius(0.2) c1.SetCenter(0,0.8,0) t1 = vtk.vtkTransform() f1 = vtk.vtkTransformPolyDataFilter() f1.SetInputConnection(c1.GetOutputPort()) f1.SetTransform(t1) m1 = vtk.vtkDataSetMapper() m1.SetInputConnection(f1.GetOutputPort()) a1 = vtk.vtkActor() a1.SetMapper(m1) a1.GetProperty().SetColor(1,0,0) # set up second set, at a relative transform to the first c2 = vtk.vtkCylinderSource() c2.SetHeight(1.6) c2.SetRadius(0.15) c2.SetCenter(0,0.8,0)
cubeMapper = vtk.vtkPolyDataMapper() cubeMapper.SetInputConnection(cube.GetOutputPort()) cubeActor = vtk.vtkActor() cubeActor.SetMapper(cubeMapper) cubeActor.SetPosition(0.0, 0.25, 0) cubeActor.GetProperty().SetColor(0, 0, 1) cone = vtk.vtkConeSource() coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.SetPosition(0, 0, 0.25) coneActor.GetProperty().SetColor(0, 1, 0) cylinder = vtk.vtkCylinderSource() cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.GetProperty().SetColor(1, 0, 0) assembly = vtk.vtkAssembly() assembly.AddPart(cylinderActor) assembly.AddPart(sphereActor) assembly.AddPart(cubeActor) assembly.AddPart(coneActor) assembly.SetOrigin(5, 10, 15) assembly.AddPosition(5, 0, 0) assembly.RotateX(15)
def GeometricObjects(self): GeometricObjects = list() GeometricObjects.append(vtk.vtkArrowSource()) GeometricObjects.append(vtk.vtkConeSource()) GeometricObjects.append(vtk.vtkCubeSource()) GeometricObjects.append(vtk.vtkCylinderSource()) GeometricObjects.append(vtk.vtkDiskSource()) GeometricObjects.append(vtk.vtkLineSource()) GeometricObjects.append(vtk.vtkRegularPolygonSource()) GeometricObjects.append(vtk.vtkSphereSource()) renderers = list() mappers = list() actors = list() textmappers = list() textactors = list() # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(10) textProperty.SetJustificationToCentered() # Create a parametric function source, renderer, mapper # and actor for each object. for idx, item in enumerate(GeometricObjects): GeometricObjects[idx].Update() mappers.append(vtk.vtkPolyDataMapper()) mappers[idx].SetInputConnection(GeometricObjects[idx].GetOutputPort()) actors.append(vtk.vtkActor()) actors[idx].SetMapper(mappers[idx]) textmappers.append(vtk.vtkTextMapper()) textmappers[idx].SetInput(item.GetClassName()) textmappers[idx].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[idx].SetMapper(textmappers[idx]) textactors[idx].SetPosition(150, 16) renderers.append(vtk.vtkRenderer()) gridDimensions = 3 for idx in range(len(GeometricObjects)): if idx < gridDimensions * gridDimensions: renderers.append(vtk.vtkRenderer) rendererSize = 300 # Create the RenderWindow # renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions) # Add and position the renders to the render window. viewport = list() for row in range(gridDimensions): for col in range(gridDimensions): idx = row * gridDimensions + col viewport[:] = [] viewport.append(float(col) * rendererSize / (gridDimensions * rendererSize)) viewport.append(float(gridDimensions - (row+1)) * rendererSize / (gridDimensions * rendererSize)) viewport.append(float(col+1)*rendererSize / (gridDimensions * rendererSize)) viewport.append(float(gridDimensions - row) * rendererSize / (gridDimensions * rendererSize)) if idx > (len(GeometricObjects) - 1): continue renderers[idx].SetViewport(viewport) renderWindow.AddRenderer(renderers[idx]) renderers[idx].AddActor(actors[idx]) renderers[idx].AddActor(textactors[idx]) renderers[idx].SetBackground(0.4,0.3,0.2) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
def cylinder(): source = vtk.vtkCylinderSource() source.SetResolution(32) source_fixture(source, 'cylinder')
cone_glyph[mu].OrientOn() cmapper[mu] = vtk.vtkPolyDataMapper() cmapper[mu].SetInputConnection(cone_glyph[mu].GetOutputPort()) cactor[mu] = vtk.vtkActor() cactor[mu].GetProperty().SetOpacity(0.4) cactor[mu].GetProperty().SetColor(0, 0, 1) cactor[mu].SetMapper(cmapper[mu]) arrow[mu] = vtk.vtkArrowSource() arrow[mu].SetTipResolution(40) arrow[mu].SetShaftResolution(40) cylinder[mu] = vtk.vtkCylinderSource() cylinder[mu].SetRadius(.01) cylinder[mu].SetHeight(1) sphere[mu] = vtk.vtkSphereSource() # 1. scale = (scalar value of that particular data index); # 2. denominator = Range[1] - Range[0]; # 3. scale = (scale < Range[0] ? Range[0] : (scale > Range[1] ? Range[1] : scale)); # 4. scale = (scale - Range[0]) / denominator; # 5. scale *= scaleFactor; arrow_glyph[mu] = vtk.vtkGlyph3D() arrow_glyph[mu].SetInputConnection(contact_pos_force[mu].GetOutputPort()) arrow_glyph[mu].SetSourceConnection(arrow[mu].GetOutputPort()) arrow_glyph[mu].ScalingOn()
import vtk # create a rendering window and render ren = vtk.vtkRenderer() # create a renderer renWin = vtk.vtkRenderWindow() # create a rendering window renWin.AddRenderer(ren) # add the renderer to the rendering window renWin.SetWindowName(" Cylinder ") # set he name of the window renWin.SetSize(800,800) #create a rendering window interacter iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create source source = vtk.vtkCylinderSource() source.SetCenter(0,0,0) source.SetRadius(5.0) source.SetHeight(7.0) source.SetResolution(100.0) #mapper mapper = vtk.vtkPolyDataMapper() #mapper.SetInput(source.GetOutput()) mapper.SetInputConnection(source.GetOutputPort()) #actor actor = vtk.vtkActor() actor.SetMapper(mapper)
def RequestData(self, request, inInfo, outInfo): logging.info('') start = timer() append = vtk.vtkAppendPolyData() # floor if self._floor: self._floor_polydata = vtk.vtkCubeSource() self._floor_polydata.SetCenter(0, .05, 0) self._floor_polydata.SetXLength(10.0) self._floor_polydata.SetYLength(0.1) self._floor_polydata.SetZLength(10.0) append.AddInputConnection(self._floor_polydata.GetOutputPort()) # table if self._objects['table']: table_leg_1 = vtk.vtkCubeSource() table_leg_1.SetCenter((1.0 / 2) - (.1 / 2), .75 / 2, (-.75 / 2) + (.1 / 2)) table_leg_1.SetXLength(0.1) table_leg_1.SetYLength(0.75) table_leg_1.SetZLength(0.1) table_leg_2 = vtk.vtkCubeSource() table_leg_2.SetCenter((-1.0 / 2) + (.1 / 2), .75 / 2, (-.75 / 2) + (.1 / 2)) table_leg_2.SetXLength(0.1) table_leg_2.SetYLength(0.75) table_leg_2.SetZLength(0.1) table_leg_3 = vtk.vtkCubeSource() table_leg_3.SetCenter((-1.0 / 2) + (.1 / 2), .75 / 2, (.75 / 2) - (.1 / 2)) table_leg_3.SetXLength(0.1) table_leg_3.SetYLength(0.75) table_leg_3.SetZLength(0.1) table_leg_4 = vtk.vtkCubeSource() table_leg_4.SetCenter((1.0 / 2) - (.1 / 2), .75 / 2, (.75 / 2) - (.1 / 2)) table_leg_4.SetXLength(0.1) table_leg_4.SetYLength(0.75) table_leg_4.SetZLength(0.1) table_top = vtk.vtkCubeSource() table_top.SetCenter(0.0, .75 - (.1 / 2), 0.0) table_top.SetXLength(1.0) table_top.SetYLength(0.1) table_top.SetZLength(0.75) self._polydata['table'] = vtk.vtkAppendPolyData() self._polydata['table'].AddInputConnection(table_leg_1.GetOutputPort()) self._polydata['table'].AddInputConnection(table_leg_2.GetOutputPort()) self._polydata['table'].AddInputConnection(table_leg_3.GetOutputPort()) self._polydata['table'].AddInputConnection(table_leg_4.GetOutputPort()) self._polydata['table'].AddInputConnection(table_top.GetOutputPort()) append.AddInputConnection(self._polydata['table'].GetOutputPort()) # left cup if self._objects['left_cup']: self._polydata['left_cup'] = vtk.vtkCylinderSource() self._polydata['left_cup'].SetCenter(-.75 / 4, .75 + (.12 / 2), 0.0) self._polydata['left_cup'].SetHeight(.12) self._polydata['left_cup'].SetRadius(.06 / 2) append.AddInputConnection(self._polydata['left_cup'].GetOutputPort()) # right cup if self._objects['right_cup']: self._polydata['right_cup'] = vtk.vtkCylinderSource() self._polydata['right_cup'].SetCenter(.75 / 4, .75 + (.12 / 2), 0.0) self._polydata['right_cup'].SetHeight(.12) self._polydata['right_cup'].SetRadius(.06 / 2) append.AddInputConnection(self._polydata['right_cup'].GetOutputPort()) append.Update() # output info = outInfo.GetInformationObject(0) output = vtk.vtkPolyData.GetData(info) output.ShallowCopy(append.GetOutput()) end = timer() logging.info('Execution time {:.4f} seconds'.format(end - start)) return 1
def setvtkWidget(self): self.ren = vtk.vtkRenderer() self.m_widget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.m_widget.GetRenderWindow().GetInteractor() # The car model (includes a plate, two poles and four wheel) # Plate of the car # Create source plate = vtk.vtkCubeSource() plate.SetXLength(100) plate.SetYLength(60) plate.SetZLength(6) plate.SetCenter(50, 0, -3) # Create a mapper plateMapper = vtk.vtkPolyDataMapper() plateMapper.SetInputConnection(plate.GetOutputPort()) # Create a transform plateTransform = vtk.vtkTransform() # Create an actor self.plateActor = vtk.vtkActor() self.plateActor.SetMapper(plateMapper) self.plateActor.SetUserTransform(plateTransform) self.plateActor.GetProperty().SetColor(0.69, 0.77, 0.87) self.ren.AddActor(self.plateActor) # Two poles # Left pole # Create source poleL = vtk.vtkCylinderSource() poleL.SetRadius(1.0) poleL.SetHeight(50.0) poleL.SetCenter(10, 0, 0) poleL.SetResolution(100.0) # Create a mapper poleLMapper = vtk.vtkPolyDataMapper() poleLMapper.SetInputConnection(poleL.GetOutputPort()) # Create a transform poleLTransform = vtk.vtkTransform() poleLTransform.SetInput(plateTransform) # Create an actor poleLActor = vtk.vtkActor() poleLActor.SetMapper(poleLMapper) poleLActor.SetUserTransform(poleLTransform) poleLTransform.RotateX(90.0) poleLTransform.Translate(0.0, 25.0, 0.0) self.ren.AddActor(poleLActor) # Right pole # Create source poleR = vtk.vtkCylinderSource() poleR.SetRadius(1.0) poleR.SetHeight(50.0) poleR.SetCenter(90, 0, 0) poleR.SetResolution(100.0) # Create a mapper poleRMapper = vtk.vtkPolyDataMapper() poleRMapper.SetInputConnection(poleR.GetOutputPort()) # Create a transform poleRTransform = vtk.vtkTransform() poleRTransform.SetInput(plateTransform) # Create an actor poleRActor = vtk.vtkActor() poleRActor.SetMapper(poleRMapper) poleRActor.SetUserTransform(poleRTransform) poleRTransform.RotateX(90.0) poleRTransform.Translate(0.0, 25.0, 0.0) self.ren.AddActor(poleRActor) # 4 car's wheels wheel = [] wheelMapper = [] wheelTransform = [] wheelActor = [] for i in range(4): # Create source wheel.append(vtk.vtkCylinderSource()) wheel[i].SetRadius(6.0) wheel[i].SetHeight(3.0) wheel[i].SetResolution(100.0) # Create a mapper wheelMapper.append(vtk.vtkPolyDataMapper()) wheelMapper[i].SetInputConnection(wheel[i].GetOutputPort()) # Create a transform wheelTransform.append(vtk.vtkTransform()) wheelTransform[i].SetInput(plateTransform) # Create an actor wheelActor.append(vtk.vtkActor()) wheelActor[i].SetMapper(wheelMapper[i]) wheelActor[i].SetUserTransform(wheelTransform[i]) wheelActor[i].GetProperty().SetColor(1.0, 1.0, 0.6) self.ren.AddActor(wheelActor[i]) wheel[0].SetCenter(10, 25, -9.0) wheel[1].SetCenter(90, 25, -9.0) wheel[2].SetCenter(10, -25, -9.0) wheel[3].SetCenter(90, -25, -9.0) # Two spheres' model # Left sphere # Create source sphereL = vtk.vtkSphereSource() sphereL.SetRadius(5) sphereL.SetCenter(0, 0, 30) # Create a mapper sphereLMapper = vtk.vtkPolyDataMapper() sphereLMapper.SetInputConnection(sphereL.GetOutputPort()) # Create an actor sphereLActor = vtk.vtkActor() sphereLActor.SetMapper(sphereLMapper) sphereLActor.GetProperty().SetColor(1.0, 0.2, 0.2) self.ren.AddActor(sphereLActor) # Right sphere # Create source sphereR = vtk.vtkSphereSource() sphereR.SetRadius(5) sphereR.SetCenter(100, 0, 30) # Create a mapper sphereRMapper = vtk.vtkPolyDataMapper() sphereRMapper.SetInputConnection(sphereR.GetOutputPort()) # Create an actor sphereRActor = vtk.vtkActor() sphereRActor.SetMapper(sphereRMapper) sphereRActor.GetProperty().SetColor(0.0, 0.5, 1.0) self.ren.AddActor(sphereRActor) # Create a camera #self.ren.ResetCamera() camera = vtk.vtkCamera() self.ren.SetActiveCamera(camera) self.ren.GetActiveCamera().SetPosition(50, -300, 100) self.ren.GetActiveCamera().SetFocalPoint(50, 0, 0) self.ren.GetActiveCamera().SetViewUp(0, 0, 1) self.ren.GetActiveCamera().UpdateViewport(self.ren)