def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkShrinkFilter(), 'Processing.', ('vtkDataSet',), ('vtkUnstructuredGrid',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def shrink(self, fraction=0.8): """Shrink the individual tetrahedra to improve visibility.""" sf = vtk.vtkShrinkFilter() sf.SetInputData(self._ugrid) sf.SetShrinkFactor(fraction) sf.Update() return self._update(sf.GetOutput())
def toMesh(self, fill=True, shrink=1.0): """ Build a polygonal Mesh from the current TetMesh. If fill=True, the interior traingular faces of all the tets are created. In this case setting a `shrink` value slightly smaller than 1.0 can avoid flickering due to adjacent faces. If fill=False, only the boundary triangles are generated. """ gf = vtk.vtkGeometryFilter() if fill: sf = vtk.vtkShrinkFilter() sf.SetInputData(self._ugrid) sf.SetShrinkFactor(shrink) sf.Update() gf.SetInputData(sf.GetOutput()) gf.Update() else: gf.SetInputData(self._ugrid) gf.Update() poly = gf.GetOutput() msh = Mesh(poly).flat() msh.scalarbar = self.scalarbar lut = utils.ctf2lut(self) msh._mapper.SetLookupTable(lut) if self.useCells: msh._mapper.SetScalarModeToUseCellData() else: msh._mapper.SetScalarModeToUsePointData() # msh._mapper.SetScalarRange(msh._mapper.GetScalarRange()) # print(msh._mapper.GetScalarRange(), lut.GetRange()) # msh._mapper.SetScalarRange() # msh.selectCellArray('chem_0') return msh
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkShrinkFilter(), 'Processing.', ('vtkDataSet', ), ('vtkUnstructuredGrid', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def main(): colors = vtk.vtkNamedColors() # Create a grid grid = vtk.vtkRectilinearGrid() grid.SetDimensions(2, 3, 2) xArray = vtk.vtkDoubleArray() xArray.InsertNextValue(0.0) xArray.InsertNextValue(2.0) yArray = vtk.vtkDoubleArray() yArray.InsertNextValue(0.0) yArray.InsertNextValue(1.0) yArray.InsertNextValue(2.0) zArray = vtk.vtkDoubleArray() zArray.InsertNextValue(0.0) zArray.InsertNextValue(5.0) grid.SetXCoordinates(xArray) grid.SetYCoordinates(yArray) grid.SetZCoordinates(zArray) shrinkFilter = vtk.vtkShrinkFilter() shrinkFilter.SetInputData(grid) shrinkFilter.SetShrinkFactor(.8) # Create a mapper and actor mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(shrinkFilter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d('PeachPuff')) # Visualize renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetWindowName('VisualizeRectilinearGrid') renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('SlateGray')) renderer.GetActiveCamera().Roll(10.0) renderer.GetActiveCamera().Elevation(60.0) renderer.GetActiveCamera().Azimuth(30.0) renderer.ResetCamera() renderWindow.Render() renderWindowInteractor.Start()
def shrink_elements(self, ob, factor=0.9): ''' class method to shrink the elements slightly to enhance visualization esthetics ob=vtk 3d tetrahedralization factor=float 0 to 1 indicating element scaling returns:vtk filtered vtk tetrahedralization ''' shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(ob.GetOutputPort()) shrink.SetShrinkFactor(0.9) return (shrink)
def addGrid(self, grid): nx, ny, nz = grid.shape[1:] self.display.append(True) self.grids.append(vtk.vtkStructuredGrid()) self.grids[-1].SetExtent(0, nz-1, 0, ny-1, 0, nx-1) p = vtk.vtkPoints() shp = grid.shape grid.shape = (3, nx*ny*nz) p.SetData(vtknp.numpy_to_vtk(np.ascontiguousarray(grid.T), deep=True, array_type=vtknp.get_vtk_array_type(grid.dtype))) grid.shape = shp self.grids[-1].SetPoints(p) #Couleur color = np.random.rand(3) #Create a vtkOutlineFilter to draw the bounding box of the data set. ol = vtk.vtkOutlineFilter() if (vtk.vtkVersion().GetVTKMajorVersion()>=6): ol.SetInputData(self.grids[-1]) else: ol.SetInput(self.grids[-1]) olm = vtk.vtkPolyDataMapper() olm.SetInputConnection(ol.GetOutputPort()) ola = vtk.vtkActor() ola.SetMapper(olm) ola.GetProperty().SetColor(color) s=vtk.vtkShrinkFilter() if (vtk.vtkVersion().GetVTKMajorVersion()>=6): s.SetInputData(self.grids[-1]) else: s.SetInput(self.grids[-1]) s.SetShrinkFactor(0.8) # mapper = vtk.vtkDataSetMapper() #map.SetInputData(data) mapper.SetInputConnection(s.GetOutputPort()) act = vtk.vtkLODActor() act.SetMapper(mapper) #act.GetProperty().SetRepresentationToWireframe() #act.GetProperty().SetRepresentationToPoints() act.GetProperty().SetColor(color) act.GetProperty().SetEdgeColor(color) act.GetProperty().EdgeVisibilityOff() self.actors.append(act) self.setBounds() self.ren.SetActiveCamera(self.cam)
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 test(self): sphere = vtk.vtkSphereSource() sphere.ReleaseDataFlagOn() shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(sphere.GetOutputPort()) shrink.ReleaseDataFlagOn() shrink.Update() # We expect sphere's output to be wiped by shrink after # this update self.assertEqual(sphere.GetOutput().GetNumberOfCells(), 0) # We update sphere separately. Its output should not be # empty sphere.Update() self.assertTrue(sphere.GetOutput().GetNumberOfCells() > 0)
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 main(): colors = vtk.vtkNamedColors() # Create hyper tree grid source source = vtk.vtkHyperTreeGridSource() source.SetMaximumLevel(6) source.SetGridSize(3, 3, 2) source.SetGridScale(1.5, 1., .7) source.SetDimension(3) source.SetBranchFactor(4) source.SetDescriptor( "RRR .R. .RR ..R ..R .R.|R.......................... ........................... ........................... .............R............. ....RR.RR........R......... .....RRRR.....R.RR......... ........................... ........................... ...........................|........................... ........................... ........................... ...RR.RR.......RR.......... ........................... RR......................... ........................... ........................... ........................... ........................... ........................... ........................... ........................... ............RRR............|........................... ........................... .......RR.................. ........................... ........................... ........................... ........................... ........................... ........................... ........................... ...........................|........................... ..........................." ) source.Update() shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(source.GetOutputPort()) shrink.SetShrinkFactor(.8) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(shrink.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Burlywood")) #Create the RenderWindow, Renderer and both Actors renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderer.SetBackground(colors.GetColor3d("SlateGray")) renderer.AddActor(actor) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(150) renderer.GetActiveCamera().Elevation(30) renderer.ResetCameraClippingRange() renderWindow.SetSize(640, 480) interactor.Start()
def main(): colors = vtk.vtkNamedColors() renderer = vtk.vtkRenderer() renderer.GetCullers().RemoveAllItems() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(12) sphere.SetPhiResolution(12) shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(sphere.GetOutputPort()) shrink.SetShrinkFactor(0.9) colorIt = vtk.vtkElevationFilter() colorIt.SetInputConnection(shrink.GetOutputPort()) colorIt.SetLowPoint(0, 0, -.5) colorIt.SetHighPoint(0, 0, .5) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(colorIt.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('LavenderBlush')) renWin.SetSize(600, 600) renWin.SetWindowName('LoopShrink') renWin.Render() renderer.GetActiveCamera().Zoom(1.5) # Interact with the data. iren.Start()
def contourCase(poly, mode): """ Create a renderer, actor, mapper to contour the polydata poly : polydata to contour mode : scalar-mode for BPDCF """ # Prepare an array of point-data scalars # Perform the contouring. Note that we need to set scalar # mode to index because line cells do not get contour values # even if scalar mode is set to value. valueRange = poly.GetPointData().GetScalars().GetRange() num = 5 bpdcf = vtk.vtkBandedPolyDataContourFilter() bpdcf.SetInputData(poly) bpdcf.GenerateValues(num, valueRange[0], valueRange[1]) bpdcf.GenerateContourEdgesOff() if mode == 'index': bpdcf.SetScalarModeToIndex() elif mode == 'value': bpdcf.SetScalarModeToValue() bpdcf.Update() # Shrink all cells somewhat so the contouring of edges can # be seen better sf = vtk.vtkShrinkFilter() sf.SetShrinkFactor(0.90) sf.SetInputConnection(bpdcf.GetOutputPort()) # Mapper shows contour index values m = vtk.vtkDataSetMapper() m.SetInputConnection(sf.GetOutputPort()) m.SetScalarModeToUseCellData() m.SetScalarRange( bpdcf.GetOutput().GetCellData().GetArray('Scalars').GetRange()) a = vtk.vtkActor() a.SetMapper(m) return a
def contourCase(poly,mode): """ Create a renderer, actor, mapper to contour the polydata poly : polydata to contour mode : scalar-mode for BPDCF """ # Prepare an array of point-data scalars # Perform the contouring. Note that we need to set scalar # mode to index because line cells do not get contour values # even if scalar mode is set to value. valueRange=poly.GetPointData().GetScalars().GetRange() num=5 bpdcf = vtk.vtkBandedPolyDataContourFilter() bpdcf.SetInputData(poly) bpdcf.GenerateValues( num, valueRange[0],valueRange[1] ) bpdcf.GenerateContourEdgesOff() if mode == 'index': bpdcf.SetScalarModeToIndex() elif mode == 'value': bpdcf.SetScalarModeToValue() bpdcf.Update() # Shrink all cells somewhat so the contouring of edges can # be seen better sf = vtk.vtkShrinkFilter() sf.SetShrinkFactor(0.90) sf.SetInputConnection( bpdcf.GetOutputPort()) # Mapper shows contour index values m = vtk.vtkDataSetMapper() m.SetInputConnection(sf.GetOutputPort()) m.SetScalarModeToUseCellData() m.SetScalarRange(bpdcf.GetOutput().GetCellData().GetArray('Scalars').GetRange()) a = vtk.vtkActor() a.SetMapper(m) return a
tetEdgeTubes = vtk.vtkTubeFilter() tetEdgeTubes.SetInputConnection(tetEdges.GetOutputPort()) tetEdgeTubes.SetRadius(.005) tetEdgeTubes.SetNumberOfSides(6) tetEdgeTubes.UseDefaultNormalOn() tetEdgeTubes.SetDefaultNormal(.577, .577, .577) tetEdgeMapper = vtk.vtkPolyDataMapper() tetEdgeMapper.SetInputConnection(tetEdgeTubes.GetOutputPort()) tetEdgeMapper.ScalarVisibilityOff() tetEdgeActor = vtk.vtkActor() tetEdgeActor.SetMapper(tetEdgeMapper) tetEdgeActor.GetProperty().SetDiffuseColor(lamp_black) tetEdgeActor.GetProperty().SetSpecular(.4) tetEdgeActor.GetProperty().SetSpecularPower(10) #shrink the triangles so we can see each one aShrinker = vtk.vtkShrinkFilter() aShrinker.SetShrinkFactor(1) aShrinker.SetInputConnection(clipper.GetOutputPort()) aMapper = vtk.vtkDataSetMapper() aMapper.ScalarVisibilityOff() aMapper.SetInputConnection(aShrinker.GetOutputPort()) Tets = vtk.vtkActor() Tets.SetMapper(aMapper) Tets.GetProperty().SetDiffuseColor(banana) #build a model of the cube CubeModel = vtk.vtkCubeSource() CubeModel.SetCenter(.5, .5, .5) Edges = vtk.vtkExtractEdges() Edges.SetInputConnection(CubeModel.GetOutputPort()) Tubes = vtk.vtkTubeFilter() Tubes.SetInputConnection(Edges.GetOutputPort())
print('No AxisReflection Filter (HTG)') reflection = htg # Geometries geometry = vtk.vtkHyperTreeGridGeometry() if isFilter: geometry.SetInputConnection(reflection.GetOutputPort()) else: geometry.SetInputData(reflection) print('With Geometry Filter (HTG to NS)') # Shrink Filter if True: print('With Shrink Filter (NS)') # En 3D, le shrink ne doit pas se faire sur la geometrie car elle ne represente que la peau shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(geometry.GetOutputPort()) shrink.SetShrinkFactor(.8) else: print('No Shrink Filter (NS)') shrink = geometry # LookupTable lut = vtk.vtkLookupTable() lut.SetHueRange(0.66, 0) lut.UsingLogScale() lut.Build() # Mappers mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(geometry.GetOutputPort())
def delaunay3DArea(system, radius=None, render=False): """ Estimates system's area by summing all the triangles from Delaunay's triangulation """ if radius is None: delaunayAlpha = 2.0 else: delaunayAlpha = radius delaunayTolerance = 1.0 clusterPoints = vtk.vtkPoints() for i in range(system.NAtoms): clusterPoints.InsertPoint(i, system.pos[i*3 + 0], system.pos[i*3 + 1], system.pos[i*3 + 2]) polyCluster = vtk.vtkPolyData() polyCluster.SetPoints(clusterPoints) delaunayCluster = vtk.vtkDelaunay3D() delaunayCluster.SetInputData(polyCluster) # delaunayCluster.SetTolerance(delaunayTolerance) delaunayCluster.SetAlpha(delaunayAlpha) delaunayCluster.BoundingTriangulationOff() delaunayCluster.Update() clusterSurfaceFilter = vtk.vtkGeometryFilter() clusterSurfaceFilter.SetInputConnection(delaunayCluster.GetOutputPort()) clusterSurfaceFilter.Update() mapClipper = vtk.vtkDataSetMapper() mapClipper.SetInputConnection(clusterSurfaceFilter.GetOutputPort()) surfaceArea = 0.0 clipperPointInput = mapClipper.GetInput() for i in range(clipperPointInput.GetNumberOfCells()): p1 = clipperPointInput.GetCell(i).GetPoints().GetPoint(0) p2 = clipperPointInput.GetCell(i).GetPoints().GetPoint(1) p3 = clipperPointInput.GetCell(i).GetPoints().GetPoint(2) triangleArea = vtk.vtkTriangle.TriangleArea(p1, p2, p3) surfaceArea += triangleArea if render: # Shrink the result to help see it better. shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(delaunayCluster.GetOutputPort()) shrink.SetShrinkFactor(0.9) map = vtk.vtkDataSetMapper() map.SetInputConnection(shrink.GetOutputPort()) triangulation = vtk.vtkActor() triangulation.SetMapper(map) triangulation.GetProperty().SetColor(1, 0, 0) 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(triangulation) ren.SetBackground(1, 1, 1) renWin.SetSize(250, 250) renWin.Render() cam1 = ren.GetActiveCamera() cam1.Zoom(1.5) iren.Initialize() renWin.Render() iren.Start() return surfaceArea
wedgeEdges.SetInputConnection(clipper.GetOutputPort()) wedgeEdgeTubes = vtk.vtkTubeFilter() wedgeEdgeTubes.SetInputConnection(wedgeEdges.GetOutputPort()) wedgeEdgeTubes.SetRadius(.005) wedgeEdgeTubes.SetNumberOfSides(6) wedgeEdgeMapper = vtk.vtkPolyDataMapper() wedgeEdgeMapper.SetInputConnection(wedgeEdgeTubes.GetOutputPort()) wedgeEdgeMapper.ScalarVisibilityOff() wedgeEdgeActor = vtk.vtkActor() wedgeEdgeActor.SetMapper(wedgeEdgeMapper) wedgeEdgeActor.GetProperty().SetDiffuseColor(GetRGBColor('lamp_black')) wedgeEdgeActor.GetProperty().SetSpecular(.4) wedgeEdgeActor.GetProperty().SetSpecularPower(10) # shrink the triangles so we can see each one aShrinker = vtk.vtkShrinkFilter() aShrinker.SetShrinkFactor(1) aShrinker.SetInputConnection(clipper.GetOutputPort()) aMapper = vtk.vtkDataSetMapper() aMapper.ScalarVisibilityOff() aMapper.SetInputConnection(aShrinker.GetOutputPort()) Wedges = vtk.vtkActor() Wedges.SetMapper(aMapper) Wedges.GetProperty().SetDiffuseColor(GetRGBColor('banana')) # build a model of the cube Edges = vtk.vtkExtractEdges() Edges.SetInputData(grid) Tubes = vtk.vtkTubeFilter() Tubes.SetInputConnection(Edges.GetOutputPort()) Tubes.SetRadius(.01)
clean1.SetInputConnection(convert0.GetOutputPort()) clean1.ToleranceIsAbsoluteOff() clean1.SetTolerance(0.00001) clean1.RemoveUnusedPointsOn() # Time execution timer.StartTimer() clean1.Update() timer.StopTimer() time = timer.GetElapsedTime() print("Time to clean grid (non-zero tolerance): {0}".format(time)) print("\tRemaining points: {0}".format(clean1.GetOutput().GetNumberOfPoints())) print("\tRemaining cells: {0}".format(clean1.GetOutput().GetNumberOfCells())) # Now shrink the data and clean with zero and non-zero tolerance shrink0 = vtk.vtkShrinkFilter() shrink0.SetInputData(sample) shrink0.SetShrinkFactor(1.0) shrink0.Update() # Convert mesh to polyhedra convert0.SetInputConnection(shrink0.GetOutputPort()) # This is with a zero tolerance clean0.SetInputConnection(convert0.GetOutputPort()) clean0.AveragePointDataOn() timer.StartTimer() clean0.Update() timer.StopTimer() time = timer.GetElapsedTime()
def __init__( self, inputobj=None, ): vtk.vtkActor.__init__(self) BaseGrid.__init__(self) inputtype = str(type(inputobj)) self._data = None self._polydata = None ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() # elif utils.isSequence(inputobj):pass # TODO elif "UnstructuredGrid" in inputtype: self._data = inputobj elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj) self._data = loadUnStructuredGrid(inputobj) else: colors.printc("UGrid(): cannot understand input type:\n", inputtype, c=1) return self._mapper = vtk.vtkPolyDataMapper() self._mapper.SetInterpolateScalarsBeforeMapping( settings.interpolateScalarsBeforeMapping) if settings.usePolygonOffset: self._mapper.SetResolveCoincidentTopologyToPolygonOffset() pof, pou = settings.polygonOffsetFactor, settings.polygonOffsetUnits self._mapper.SetResolveCoincidentTopologyPolygonOffsetParameters( pof, pou) self.GetProperty().SetInterpolationToFlat() if not self._data: return sf = vtk.vtkShrinkFilter() sf.SetInputData(self._data) sf.SetShrinkFactor(1.0) sf.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(sf.GetOutput()) gf.Update() self._polydata = gf.GetOutput() self._mapper.SetInputData(self._polydata) sc = None if self.useCells: sc = self._polydata.GetCellData().GetScalars() else: sc = self._polydata.GetPointData().GetScalars() if sc: self._mapper.SetScalarRange(sc.GetRange()) self.SetMapper(self._mapper)
def main(): cellName = get_program_parameters() # Store the cell class names in a dictionary. cellMap = dict() cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_LINE)] = vtk.VTK_LINE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_EDGE)] = vtk.VTK_QUADRATIC_EDGE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_CUBIC_LINE)] = vtk.VTK_CUBIC_LINE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_TRIANGLE)] = vtk.VTK_TRIANGLE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_TRIANGLE)] = vtk.VTK_QUADRATIC_TRIANGLE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUAD)] = vtk.VTK_QUAD cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_QUAD)] = vtk.VTK_QUADRATIC_QUAD cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_TETRA)] = vtk.VTK_TETRA cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_HEXAHEDRON)] = vtk.VTK_HEXAHEDRON cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_WEDGE)] = vtk.VTK_WEDGE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_PYRAMID)] = vtk.VTK_PYRAMID cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_WEDGE)] = vtk.VTK_QUADRATIC_WEDGE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_PYRAMID)] = vtk.VTK_QUADRATIC_PYRAMID cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_HEXAHEDRON)] = vtk.VTK_QUADRATIC_HEXAHEDRON cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId( vtk.VTK_QUADRATIC_TETRA)] = vtk.VTK_QUADRATIC_TETRA if cellName not in cellMap: print('Cell type ', cellName, ' is not supported.') return source = vtk.vtkCellTypeSource() source.SetCellType(cellMap[cellName]) source.Update() print('Cell: ', cellName) originalPoints = source.GetOutput().GetPoints() points = vtk.vtkPoints() points.SetNumberOfPoints(source.GetOutput().GetNumberOfPoints()) rng = vtk.vtkMinimalStandardRandomSequence() rng.SetSeed(5070) # for testing for i in range(0, points.GetNumberOfPoints()): perturbation = [0.0] * 3 for j in range(0, 3): rng.Next() perturbation[j] = rng.GetRangeValue(-0.1, 0.1) currentPoint = [0.0] * 3 originalPoints.GetPoint(i, currentPoint) points.SetPoint(i, currentPoint[0] + perturbation[0], currentPoint[1] + perturbation[1], currentPoint[2] + perturbation[2]) source.GetOutput().SetPoints(points) numCells = source.GetOutput().GetNumberOfCells() print('Number of cells: ', numCells) idArray = vtk.vtkIntArray() idArray.SetNumberOfTuples(numCells) for i in range(0, numCells): idArray.InsertTuple1(i, i + 1) idArray.SetName('Ids') source.GetOutput().GetCellData().AddArray(idArray) source.GetOutput().GetCellData().SetActiveScalars('Ids') shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(source.GetOutputPort()) shrink.SetShrinkFactor(.8) tessellate = vtk.vtkTessellatorFilter() tessellate.SetInputConnection(shrink.GetOutputPort()) tessellate.SetMaximumNumberOfSubdivisions(3) # Create a lookup table to map cell data to colors. lut = vtk.vtkLookupTable() colorSeries = vtk.vtkColorSeries() seriesEnum = colorSeries.BREWER_QUALITATIVE_SET3 colorSeries.SetColorScheme(seriesEnum) colorSeries.BuildLookupTable(lut, colorSeries.ORDINAL) # Fill in a few known colors, the rest will be generated if needed. colors = vtk.vtkNamedColors() # Create a mapper and actor. mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(source.GetOutputPort()) mapper.SetInputConnection(shrink.GetOutputPort()) mapper.SetScalarRange(0, numCells + 1) mapper.SetLookupTable(lut) mapper.SetScalarModeToUseCellData() mapper.SetResolveCoincidentTopologyToPolygonOffset() if (source.GetCellType() == vtk.VTK_QUADRATIC_PYRAMID or source.GetCellType() == vtk.VTK_QUADRATIC_WEDGE): mapper.SetInputConnection(shrink.GetOutputPort()) else: mapper.SetInputConnection(tessellate.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() # actor.GetProperty().SetLineWidth(3) textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(20) textProperty.SetJustificationToCentered() textProperty.SetColor(colors.GetColor3d('Lamp_Black')) textMapper = vtk.vtkTextMapper() textMapper.SetInput(cellName) textMapper.SetTextProperty(textProperty) textActor = vtk.vtkActor2D() textActor.SetMapper(textMapper) textActor.SetPosition(320, 20) # Create a renderer, render window, and interactor. renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName('CellTypeSource') renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene. renderer.AddViewProp(textActor) 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.Render() renderWindowInteractor.Start()
def makeModels(self): """ make vtk model """ # Here we create two ellipsoidal implicit functions and boolean them # together to form a "cross" shaped implicit function. quadric = vtk.vtkQuadric() quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0) sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(quadric) sample.ComputeNormalsOff() trans = vtk.vtkTransform() trans.Scale(1, .5, .333) sphere = vtk.vtkSphere() sphere.SetRadius(self.radius) sphere.SetTransform(trans) trans2 = vtk.vtkTransform() trans2.Scale(.25, .5, 1.0) sphere2 = vtk.vtkSphere() sphere2.SetRadius(self.radius) sphere2.SetTransform(trans2) self.sphere_geom_1 = sphere self.sphere_geom_2 = sphere2 union = vtk.vtkImplicitBoolean() union.AddFunction(sphere) union.AddFunction(sphere2) union.SetOperationType(0) # Here is where it gets interesting. The implicit function is used to # extract those cells completely inside the function. They are then # shrunk to helpr show what was extracted. extract = vtk.vtkExtractGeometry() extract.SetInputConnection(sample.GetOutputPort()) extract.SetImplicitFunction(union) shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(extract.GetOutputPort()) shrink.SetShrinkFactor(self.shrink_factor) dataMapper = vtk.vtkDataSetMapper() dataMapper.SetInputConnection(shrink.GetOutputPort()) self.shrink_geom = shrink # data actor self.data_actor = vtk.vtkActor() self.data_actor.SetMapper(dataMapper) # The outline gives context to the original data. outline = vtk.vtkOutlineFilter() outline.SetInputConnection(sample.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) # outline actor self.outline_actor = vtk.vtkActor() self.outline_actor.SetMapper(outlineMapper) outlineProp = self.outline_actor.GetProperty() outlineProp.SetColor(0, 0, 0)
def __init__(self, inputobj=None): vtk.vtkActor.__init__(self) BaseGrid.__init__(self) inputtype = str(type(inputobj)) self._data = None self._polydata = None self.name = "UGrid" ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() elif utils.isSequence(inputobj): pts, cells, celltypes = inputobj self._data = vtk.vtkUnstructuredGrid() if not utils.isSequence(cells[0]): tets = [] nf = cells[0] + 1 for i, cl in enumerate(cells): if i == nf or i == 0: k = i + 1 nf = cl + k cell = [cells[j + k] for j in range(cl)] tets.append(cell) cells = tets # This would fill the points and use those to define orientation vpts = utils.numpy2vtk(pts, dtype=float) points = vtk.vtkPoints() points.SetData(vpts) self._data.SetPoints(points) # This fill the points and use cells to define orientation # points = vtk.vtkPoints() # for c in cells: # for pid in c: # points.InsertNextPoint(pts[pid]) # self._data.SetPoints(points) # Fill cells # https://vtk.org/doc/nightly/html/vtkCellType_8h_source.html for i, ct in enumerate(celltypes): cell_conn = cells[i] if ct == vtk.VTK_HEXAHEDRON: cell = vtk.vtkHexahedron() elif ct == vtk.VTK_TETRA: cell = vtk.vtkTetra() elif ct == vtk.VTK_VOXEL: cell = vtk.vtkVoxel() elif ct == vtk.VTK_WEDGE: cell = vtk.vtkWedge() elif ct == vtk.VTK_PYRAMID: cell = vtk.vtkPyramid() elif ct == vtk.VTK_HEXAGONAL_PRISM: cell = vtk.vtkHexagonalPrism() elif ct == vtk.VTK_PENTAGONAL_PRISM: cell = vtk.vtkPentagonalPrism() else: print("UGrid: cell type", ct, "not implemented. Skip.") continue cpids = cell.GetPointIds() for j, pid in enumerate(cell_conn): cpids.SetId(j, pid) self._data.InsertNextCell(ct, cpids) elif "UnstructuredGrid" in inputtype: self._data = inputobj elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj, verbose=False) self._data = loadUnStructuredGrid(inputobj) self.filename = inputobj else: colors.printc("UGrid(): cannot understand input type:\n", inputtype, c='r') return # self._mapper = vtk.vtkDataSetMapper() self._mapper = vtk.vtkPolyDataMapper() self._mapper.SetInterpolateScalarsBeforeMapping( settings.interpolateScalarsBeforeMapping) if settings.usePolygonOffset: self._mapper.SetResolveCoincidentTopologyToPolygonOffset() pof, pou = settings.polygonOffsetFactor, settings.polygonOffsetUnits self._mapper.SetResolveCoincidentTopologyPolygonOffsetParameters( pof, pou) self.GetProperty().SetInterpolationToFlat() if not self._data: return # now fill the representation of the vtk unstr grid sf = vtk.vtkShrinkFilter() sf.SetInputData(self._data) sf.SetShrinkFactor(1.0) sf.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(sf.GetOutput()) gf.Update() self._polydata = gf.GetOutput() self._mapper.SetInputData(self._polydata) sc = None if self.useCells: sc = self._polydata.GetCellData().GetScalars() else: sc = self._polydata.GetPointData().GetScalars() if sc: self._mapper.SetScalarRange(sc.GetRange()) self.SetMapper(self._mapper) self.property = self.GetProperty()
def main(): colors = vtk.vtkNamedColors() ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) quadric = vtk.vtkQuadric() quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0) sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(quadric) sample.ComputeNormalsOff() trans = vtk.vtkTransform() trans.Scale(1, 0.5, 0.333) sphere = vtk.vtkSphere() sphere.SetRadius(0.25) sphere.SetTransform(trans) trans2 = vtk.vtkTransform() trans2.Scale(0.25, 0.5, 1.0) sphere2 = vtk.vtkSphere() sphere2.SetRadius(0.25) sphere2.SetTransform(trans2) booleanUnion = vtk.vtkImplicitBoolean() booleanUnion.AddFunction(sphere) booleanUnion.AddFunction(sphere2) booleanUnion.SetOperationType(0) # boolean Union extract = vtk.vtkExtractGeometry() extract.SetInputConnection(sample.GetOutputPort()) extract.SetImplicitFunction(booleanUnion) shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(extract.GetOutputPort()) shrink.SetShrinkFactor(0.5) dataMapper = vtk.vtkDataSetMapper() dataMapper.SetInputConnection(shrink.GetOutputPort()) dataActor = vtk.vtkActor() dataActor.SetMapper(dataMapper) # outline outline = vtk.vtkOutlineFilter() outline.SetInputConnection(sample.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(0, 0, 0) # Add the actors to the renderer, set the background and size # ren1.AddActor(outlineActor) ren1.AddActor(dataActor) ren1.SetBackground(colors.GetColor3d("SlateGray")) renWin.SetSize(640, 480) renWin.SetWindowName('ExtractData') renWin.Render() ren1.GetActiveCamera().Azimuth(30) ren1.GetActiveCamera().Elevation(30) renWin.Render() iren.Start()
return ts, fs ### helpers end ########################################## def get_y_top(t): return 1.0 - 0.005 * t ts, fns = read_pvd_file(pvd_file) reader = vtk.vtkXMLUnstructuredGridReader() destroyTopology = vtk.vtkShrinkFilter() destroyTopology.SetShrinkFactor(1.0) # destroyTopology.SetInputConnection(strainFilter.GetOutputPort()) # destroyTopology.SetInputConnection(reader.GetOutputPort()) # strainFilter = vtk.vtkCellDerivatives() # strainFilter.SetVectorModeToPassVectors() # strainFilter.SetTensorModeToComputeStrain() # strainFilter.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) warpVector = vtk.vtkWarpVector() # warpVector.SetInputConnection(strainFilter.GetOutputPort()) # cell2point = vtk.vtkCellDataToPointData() # cell2point.SetInputConnection(destroyTopology.GetOutputPort()) # cell2point.PassCellDataOff()
def main(): colors = vtk.vtkNamedColors() # Create hyper tree grid source descriptor = 'RRR .R. .RR ..R ..R .R.|R.......................... ' \ '........................... ........................... ' \ '.............R............. ....RR.RR........R......... ' \ '.....RRRR.....R.RR......... ........................... ' \ '........................... ' \ '...........................|........................... ' \ '........................... ........................... ' \ '...RR.RR.......RR.......... ........................... ' \ 'RR......................... ........................... ' \ '........................... ........................... ' \ '........................... ........................... ' \ '........................... ........................... ' \ '............RRR............|........................... ' \ '........................... .......RR.................. ' \ '........................... ........................... ' \ '........................... ........................... ' \ '........................... ........................... ' \ '........................... ' \ '...........................|........................... ' \ '...........................' source = vtk.vtkHyperTreeGridSource() source.SetMaximumLevel(6) source.SetDimensions(4, 4, 3) # GridCell 3, 3, 2 source.SetGridScale(1.5, 1.0, 0.7) source.SetBranchFactor(4) source.SetDescriptor(descriptor) source.Update() # Hyper tree grid to unstructured grid filter htg2ug = vtk.vtkHyperTreeGridToUnstructuredGrid() htg2ug.SetInputConnection(source.GetOutputPort()) htg2ug.Update() shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(htg2ug.GetOutputPort()) shrink.SetShrinkFactor(.8) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(shrink.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(colors.GetColor3d('Burlywood')) # Create the RenderWindow, Renderer and Interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderer.SetBackground(colors.GetColor3d('SlateGray')) renderer.AddActor(actor) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(150) renderer.GetActiveCamera().Elevation(30) renderer.ResetCameraClippingRange() renderWindow.SetSize(640, 480) renderWindow.Render() renderWindow.SetWindowName('HyperTreeGridSource') interactor.Start()
def main(): colors = vtk.vtkNamedColors() filename = get_program_parameters() # Create the reader for the data. print('Loading ', filename) reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.Update() extractEdges = vtk.vtkExtractEdges() extractEdges.SetInputConnection(reader.GetOutputPort()) legendValues = vtk.vtkVariantArray() it = reader.GetOutput().NewCellIterator() it.InitTraversal() while not it.IsDoneWithTraversal(): cell = vtk.vtkGenericCell() it.GetCell(cell) cellName = vtk.vtkCellTypes.GetClassNameFromTypeId(cell.GetCellType()) print(cellName, 'NumberOfPoints:', cell.GetNumberOfPoints(), 'CellDimension:', cell.GetCellDimension()) legendValues.InsertNextValue(cellName) it.GoToNextCell() # Tube the edges tubes = vtk.vtkTubeFilter() tubes.SetInputConnection(extractEdges.GetOutputPort()) tubes.SetRadius(.05) tubes.SetNumberOfSides(21) edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(tubes.GetOutputPort()) edgeMapper.SetScalarRange(0, 26) edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetSpecular(0.6) edgeActor.GetProperty().SetSpecularPower(30) # Glyph the points sphere = vtk.vtkSphereSource() sphere.SetPhiResolution(21) sphere.SetThetaResolution(21) sphere.SetRadius(0.08) pointMapper = vtk.vtkGlyph3DMapper() pointMapper.SetInputConnection(reader.GetOutputPort()) pointMapper.SetSourceConnection(sphere.GetOutputPort()) pointMapper.ScalingOff() pointMapper.ScalarVisibilityOff() pointActor = vtk.vtkActor() pointActor.SetMapper(pointMapper) pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana')) pointActor.GetProperty().SetSpecular(0.6) pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0) pointActor.GetProperty().SetSpecularPower(100) # Label the points labelMapper = vtk.vtkLabeledDataMapper() labelMapper.SetInputConnection(reader.GetOutputPort()) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # The geometry geometryShrink = vtk.vtkShrinkFilter() geometryShrink.SetInputConnection(reader.GetOutputPort()) geometryShrink.SetShrinkFactor(0.8) # NOTE: We must copy the originalLut because the CategoricalLegend # needs an indexed lookup table, but the geometryMapper uses a # non-index lookup table categoricalLut = vtk.vtkLookupTable() originalLut = reader.GetOutput().GetCellData().GetScalars().GetLookupTable( ) categoricalLut.DeepCopy(originalLut) categoricalLut.IndexedLookupOn() geometryMapper = vtk.vtkDataSetMapper() geometryMapper.SetInputConnection(geometryShrink.GetOutputPort()) geometryMapper.SetScalarModeToUseCellData() geometryMapper.SetScalarRange(0, 11) geometryActor = vtk.vtkActor() geometryActor.SetMapper(geometryMapper) geometryActor.GetProperty().SetLineWidth(3) geometryActor.GetProperty().EdgeVisibilityOn() geometryActor.GetProperty().SetEdgeColor(0, 0, 0) # Legend for v in range(0, legendValues.GetNumberOfTuples()): categoricalLut.SetAnnotation(legendValues.GetValue(v), legendValues.GetValue(v).ToString()) legend = vtk.vtkCategoryLegend() legend.SetScalarsToColors(categoricalLut) legend.SetValues(legendValues) legend.SetTitle('Cell Type') legend.GetBrush().SetColor(colors.GetColor4ub('Silver')) placeLegend = vtk.vtkContextTransform() placeLegend.AddItem(legend) placeLegend.Translate(640 - 20, 480 - 12 * 16) contextView = vtk.vtkContextView() contextView.GetScene().AddItem(placeLegend) renderer = contextView.GetRenderer() renderWindow = contextView.GetRenderWindow() renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(geometryActor) renderer.AddActor(labelActor) renderer.AddActor(edgeActor) renderer.AddActor(pointActor) renderer.SetBackground(colors.GetColor3d('SlateGray')) aCamera = vtk.vtkCamera() aCamera.Azimuth(-40.0) aCamera.Elevation(50.0) renderer.SetActiveCamera(aCamera) renderer.ResetCamera() renderWindow.SetSize(640, 480) renderWindow.SetWindowName('ReadLegacyUnstructuredGrid') renderWindow.Render() renderWindowInteractor.Start()