def CreateCircle(radius):
	circleSource = vtkRegularPolygonSource()
	circleSource.SetNumberOfSides(32)
	circleSource.SetRadius(radius)
	circleSource.SetGeneratePolygon(False)

	circleMapper = vtkPolyDataMapper()
	circleMapper.SetInputConnection(circleSource.GetOutputPort())

	circle = vtkActor()
	circle.PickableOff()
	circle.SetMapper(circleMapper)
	circle.GetProperty().SetColor(1.0, 0.5, 0.5)

	return circle
	def __init__(self):
		self.poly_list = []
		self.actor_list = []
		
		# Create shapes and actors
		boxUp = vtk.vtkRegularPolygonSource()
		boxUp.GeneratePolygonOn()
		boxUp.GeneratePolylineOff()
		boxUp.SetNumberOfSides(3)
		boxUp.SetCenter(0,14,0)
		boxUp.SetRadius(11)
		self.poly_list.append(boxUp)
		
		boxL = vtk.vtkRegularPolygonSource()
		boxL.GeneratePolygonOn()
		boxL.GeneratePolylineOff()
		boxL.SetNumberOfSides(4)
		boxL.SetCenter(-15,-2,0)
		boxL.SetRadius(9)
		self.poly_list.append(boxL)
		
		boxR = vtk.vtkRegularPolygonSource()
		boxR.GeneratePolygonOn()
		boxR.GeneratePolylineOff()
		boxR.SetNumberOfSides(4)
		boxR.SetCenter(15,-2,0)
		boxR.SetRadius(9)
		self.poly_list.append(boxR)
		
		boxLDown = vtk.vtkRegularPolygonSource()
		boxLDown.GeneratePolygonOn()
		boxLDown.GeneratePolylineOff()
		boxLDown.SetNumberOfSides(6)
		boxLDown.SetCenter(-12,-22,0)
		boxLDown.SetRadius(9)
		self.poly_list.append(boxLDown)
		
		boxRDown = vtk.vtkRegularPolygonSource()
		boxRDown.GeneratePolygonOn()
		boxRDown.GeneratePolylineOff()
		boxRDown.SetNumberOfSides(6)
		boxRDown.SetCenter(12,-22,0)
		boxRDown.SetRadius(9)
		self.poly_list.append(boxRDown)
		
		for ii, poly in enumerate(self.poly_list):
			map = vtk.vtkPolyDataMapper2D()
			map.SetInputConnection(poly.GetOutputPort(0))
			act = vtk.vtkActor2D()
			act.SetMapper(map)
			act.SetPickable(True)
			# act.GetProperty().SetColor(0.5, 0.45, 0.35)
			act.GetProperty().SetColor(0.4, 0.4, 0.4)
			act.GetProperty().SetLineWidth(0.0)
			act.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
			act.GetPositionCoordinate().SetValue(0.075 ,0.15)
			act.GetPosition2Coordinate().SetCoordinateSystemToNormalizedDisplay()
			act.GetPosition2Coordinate().SetValue(0.5, 0.5)
			self.actor_list.append(act)
Exemplo n.º 3
0
def main():
    colors = vtk.vtkNamedColors()

    # Create a circle
    polygonSource = vtk.vtkRegularPolygonSource()
    # Comment this line to generate a disk instead of a circle.
    polygonSource.GeneratePolygonOff()
    polygonSource.SetNumberOfSides(50)
    polygonSource.SetRadius(5.0)
    polygonSource.SetCenter(0.0, 0.0, 0.0)

    #  Visualize
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(polygonSource.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Cornsilk'))

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Circle")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('DarkGreen'))

    renderWindow.Render()
    renderWindowInteractor.Start()
Exemplo n.º 4
0
    def draw_circle(self):
        """ Draw a circle at random coordinates in the window. """
        #pylint:disable=attribute-defined-outside-init
        # Generate random position and size
        self.circle_radius = random.random() * 500 + 25
        self.target_x = -400 + self.circle_radius \
            + (800 - 2*self.circle_radius) * random.random()
        self.target_y = -260 + self.circle_radius\
             + (520 - 2*self.circle_radius) * random.random()

        # Create a circle
        polygon_source = vtk.vtkRegularPolygonSource()
        # Comment this line to generate a disk instead of a circle.
        polygon_source.GeneratePolygonOff()
        polygon_source.SetNumberOfSides(50)
        polygon_source.SetRadius(self.circle_radius)
        polygon_source.SetCenter(self.target_x, self.target_y, 0.0)

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(polygon_source.GetOutputPort())

        # actor
        self.target_actor = vtk.vtkActor()
        self.target_actor.SetMapper(mapper)
Exemplo n.º 5
0
    def createActorTubes(self, elements):
        source = vtk.vtkAppendPolyData()
        mapper = vtk.vtkPolyDataMapper()
        actor = vtk.vtkActor()

        for element in elements:
            cross_section = element.cross_section
            if cross_section and self.plotRadius:
                polygon = self.createSectionPolygon(element)
            else:
                if self.defaultRadius is None:
                    base_length = self.project.preprocessor.structure_principal_diagonal
                    if element.length / 10 > base_length / 1000:
                        self.defaultRadius = element.length / 10
                    else:
                        self.defaultRadius = base_length / 1000
                polygon = vtk.vtkRegularPolygonSource()
                polygon.SetRadius(self.defaultRadius)
                polygon.SetNumberOfSides(20)

            tube = self.generalSectionTube(element, polygon.GetOutputPort())
            source.AddInputData(tube.GetOutput())

        mapper.SetInputConnection(source.GetOutputPort())
        actor.SetMapper(mapper)
        return actor
Exemplo n.º 6
0
def Polygon(center=(0., 0., 0.), radius=1, normal=(0, 0, 1), n_sides=6):
    """Create a polygonal disk with a hole in the center.

    The disk has zero height. The user can specify the inner and outer radius
    of the disk, and the radial and circumferential resolution of the polygonal
    representation.

    Parameters
    ----------
    center : np.ndarray or list
        Center in [x, y, z]. middle of the axis of the polygon.

    radius : float
        The radius of the polygon

    normal : np.ndarray or list
        direction vector in [x, y, z]. orientation vector of the cone.

    n_sides : int
        Number of sides of the polygon

    """
    src = vtk.vtkRegularPolygonSource()
    src.SetCenter(center)
    src.SetNumberOfSides(n_sides)
    src.SetRadius(radius)
    src.SetNormal(normal)
    src.Update()
    return pyvista.wrap(src.GetOutput())
Exemplo n.º 7
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkRegularPolygonSource(), 'Processing.',
         (), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 8
0
def main():
    colors = vtk.vtkNamedColors()

    # Sphere
    sphereSource = vtk.vtkSphereSource()
    sphereSource.SetCenter(-4.0, 0.0, 0.0)
    sphereSource.SetRadius(4.0)

    sphereMapper = vtk.vtkPolyDataMapper()
    sphereMapper.SetInputConnection(sphereSource.GetOutputPort())

    sphereActor = vtk.vtkActor()
    sphereActor.SetMapper(sphereMapper)
    sphereActor.GetProperty().SetColor(colors.GetColor3d('MistyRose'))

    # Regular Polygon
    regularPolygonSource = vtk.vtkRegularPolygonSource()
    regularPolygonSource.SetCenter(4.0, 0.0, 0.0)
    regularPolygonSource.SetRadius(4.0)

    regularPolygonMapper = vtk.vtkPolyDataMapper()
    regularPolygonMapper.SetInputConnection(regularPolygonSource.GetOutputPort())

    regularPolygonActor = vtk.vtkActor()
    regularPolygonActor.SetMapper(regularPolygonMapper)
    regularPolygonActor.GetProperty().SetColor(colors.GetColor3d('Cornsilk'))

    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName('BalloonWidget')

    # An interactor
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Create the widget
    balloonRep = vtk.vtkBalloonRepresentation()
    balloonRep.SetBalloonLayoutToImageRight()

    balloonWidget = vtk.vtkBalloonWidget()
    balloonWidget.SetInteractor(renderWindowInteractor)
    balloonWidget.SetRepresentation(balloonRep)
    balloonWidget.AddBalloon(sphereActor, 'This is a sphere')
    balloonWidget.AddBalloon(regularPolygonActor, 'This is a regular polygon')

    # Add the actors to the scene
    renderer.AddActor(sphereActor)
    renderer.AddActor(regularPolygonActor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    # Render an image (lights and cameras are created automatically)
    renderWindow.Render()
    balloonWidget.EnabledOn()

    # Begin mouse interaction
    renderWindowInteractor.Start()
    renderWindowInteractor.Initialize()
Exemplo n.º 9
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkRegularPolygonSource(),
                                       'Processing.', (), ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemplo n.º 10
0
def polygon(pos=[0, 0, 0],
            normal=[0, 0, 1],
            nsides=6,
            r=1,
            c='coral',
            bc='darkgreen',
            lw=1,
            alpha=1,
            legend=None,
            texture=None,
            followcam=False,
            camera=None):
    '''
    Build a 2D polygon of `nsides` of radius `r` oriented as `normal`.

    If ``followcam=True`` the polygon will always reorient itself to current camera.
    '''
    ps = vtk.vtkRegularPolygonSource()
    ps.SetNumberOfSides(nsides)
    ps.SetRadius(r)
    ps.SetNormal(-np.array(normal))
    ps.Update()

    tf = vtk.vtkTriangleFilter()
    tf.SetInputConnection(ps.GetOutputPort())
    tf.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(tf.GetOutputPort())
    if followcam:  # follow cam
        actor = vtk.vtkFollower()
        actor.SetCamera(camera)
        if not camera:
            colors.printc('Warning: vtkCamera does not yet exist for polygon',
                          c=5)
    else:
        actor = Actor()  # vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.getColor(c))
    # check if color string contains a float, in this case ignore alpha
    al = colors._getAlpha(c)
    if al:
        alpha = al
    actor.GetProperty().SetOpacity(alpha)
    actor.GetProperty().SetLineWidth(lw)
    actor.GetProperty().SetInterpolationToFlat()
    if bc:  # defines a specific color for the backface
        backProp = vtk.vtkProperty()
        backProp.SetDiffuseColor(colors.getColor(bc))
        backProp.SetOpacity(alpha)
        actor.SetBackfaceProperty(backProp)
    if texture:
        actor.texture(texture)
    actor.SetPosition(pos)
    return actor
Exemplo n.º 11
0
 def __create_vtk_loop_rep(self, p):
   n = (0, -1/math.sqrt(2), 1/math.sqrt(2))
   r = Settings.loop_radius
   vtk_circle_src = vtk.vtkRegularPolygonSource()
   vtk_circle_src.SetCenter(p[0] + r*n[0], p[1] - r*n[1], p[2] + r*n[2])
   vtk_circle_src.SetNormal(n)
   vtk_circle_src.SetRadius(r)
   vtk_circle_src.GeneratePolygonOff()
   vtk_circle_src.SetNumberOfSides(40)
   vtk_circle_src.Update()
   return vtk_circle_src.GetOutput()
Exemplo n.º 12
0
 def showGrid(self):
     self.grid = []
     # latitude
     tmp = self.addPart(ObjectBase(vtk.vtkRegularPolygonSource()))
     tmp._source.SetGeneratePolyline(True)
     tmp._source.SetGeneratePolygon(False)
     tmp._source.SetNumberOfSides(self.res)
     tmp._source.SetRadius(0.5 + self.height)
     tmp._actor.GetProperty().SetColor(0.3, 0.3, 0.3)
     self.grid.append(tmp)
     for i in range(10, 90, 10):
         u = i * math.pi / 180.0
         h = (0.5 + self.height) * math.cos(u)
         r = (0.5 + self.height) * math.cos(0.5*math.pi-u)
         a = self.addPart(ObjectBase(vtk.vtkRegularPolygonSource()))
         a._source.SetGeneratePolyline(True)
         a._source.SetGeneratePolygon(False)
         a._source.SetNumberOfSides(self.res)
         a._source.SetRadius(r)
         a._source.SetCenter(0.0, 0.0, h)
         a._actor.GetProperty().SetColor(0.3, 0.3, 0.3)
         self.grid.append(a)
         b = self.addPart(ObjectBase(vtk.vtkRegularPolygonSource()))
         b._source.SetGeneratePolyline(True)
         b._source.SetGeneratePolygon(False)
         b._source.SetNumberOfSides(self.res)
         b._source.SetRadius(r)
         b._source.SetCenter(0.0, 0.0, -h)
         b._actor.GetProperty().SetColor(0.3, 0.3, 0.3)
         self.grid.append(b)
     # longitude
     for i in range(0, 180, 10):
         u = i * math.pi / 180.0
         a = self.addPart(ObjectBase(vtk.vtkRegularPolygonSource()))
         a._source.SetGeneratePolyline(True)
         a._source.SetGeneratePolygon(False)
         a._source.SetNumberOfSides(2*self.res)
         a._source.SetNormal(math.sin(u), math.cos(u), 0.0)
         a._source.SetRadius(0.5 + self.height)
         a._actor.GetProperty().SetColor(0.3, 0.3, 0.3)
         self.grid.append(a)
Exemplo n.º 13
0
def Polygon(pos=(0, 0, 0),
            normal=(0, 0, 1),
            nsides=6,
            r=1,
            c="coral",
            bc="darkgreen",
            lw=1,
            alpha=1,
            followcam=False):
    """
    Build a 2D polygon of `nsides` of radius `r` oriented as `normal`.

    :param followcam: if `True` the text will auto-orient itself to the active camera.
        A ``vtkCamera`` object can also be passed.
    :type followcam: bool, vtkCamera  
    
    |Polygon|
    """
    ps = vtk.vtkRegularPolygonSource()
    ps.SetNumberOfSides(nsides)
    ps.SetRadius(r)
    ps.SetNormal(-np.array(normal))
    ps.Update()

    tf = vtk.vtkTriangleFilter()
    tf.SetInputConnection(ps.GetOutputPort())
    tf.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(tf.GetOutputPort())
    if followcam:
        import vtkplotter.plotter as plt

        actor = vtk.vtkFollower()
        if isinstance(followcam, vtk.vtkCamera):
            actor.SetCamera(followcam)
        else:
            actor.SetCamera(plt._plotter_instance.camera)
    else:
        actor = Actor()

    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.getColor(c))
    actor.GetProperty().SetOpacity(alpha)
    actor.GetProperty().SetLineWidth(lw)
    actor.GetProperty().SetInterpolationToFlat()
    if bc:  # defines a specific color for the backface
        backProp = vtk.vtkProperty()
        backProp.SetDiffuseColor(colors.getColor(bc))
        backProp.SetOpacity(alpha)
        actor.SetBackfaceProperty(backProp)
    actor.SetPosition(pos)
    return actor
 def draw_circles(self):
     circles = []
     for center, normal in zip(self.all_centers_disc, self.all_normals):
         for radii in self.all_radii:
             for radius in radii:
                 circle = vtk.vtkRegularPolygonSource()
                 circle.SetNormal(normal)
                 circle.SetNumberOfSides(500)
                 circle.SetRadius(radius)
                 circle.SetCenter(center)
                 circle.Update()
                 circles.append(circle.GetOutput())
     return circles
Exemplo n.º 15
0
def Polygon(pos=(0, 0, 0), nsides=6, r=1, c="coral", alpha=1):
    """
    Build a 2D polygon of `nsides` of radius `r` oriented as `normal`.

    |Polygon|
    """
    ps = vtk.vtkRegularPolygonSource()
    ps.SetNumberOfSides(nsides)
    ps.SetRadius(r)
    ps.Update()
    actor = Actor(ps.GetOutput(), c, alpha)
    actor.SetPosition(pos)
    settings.collectable_actors.append(actor)
    return actor
Exemplo n.º 16
0
def CreateCircle(radius):
    circleSource = vtkRegularPolygonSource()
    circleSource.SetNumberOfSides(32)
    circleSource.SetRadius(radius)
    circleSource.SetGeneratePolygon(False)

    circleMapper = vtkPolyDataMapper()
    circleMapper.SetInputConnection(circleSource.GetOutputPort())

    circle = vtkActor()
    circle.PickableOff()
    circle.SetMapper(circleMapper)
    circle.GetProperty().SetColor(1.0, 0.5, 0.5)

    return circle
Exemplo n.º 17
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        polygonSource = vtk.vtkRegularPolygonSource()
        polygonSource.Update()

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputConnection(polygonSource.GetOutputPort())
        triangleFilter.Update()

        inputMapper = vtk.vtkPolyDataMapper()
        inputMapper.SetInputConnection(polygonSource.GetOutputPort())
        inputActor = vtk.vtkActor()
        inputActor.SetMapper(inputMapper)
        inputActor.GetProperty().SetRepresentationToWireframe()

        triangleMapper = vtk.vtkPolyDataMapper()
        triangleMapper.SetInputConnection(triangleFilter.GetOutputPort())
        triangleActor = vtk.vtkActor()
        triangleActor.SetMapper(triangleMapper)
        triangleActor.GetProperty().SetRepresentationToWireframe()

        # Setup renderers
        leftRenderer = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(leftRenderer)
        leftRenderer.SetViewport(0, 0, 0.5, 1)
        leftRenderer.SetBackground(0.6, 0.5, 0.4)
        leftRenderer.AddActor(inputActor)

        rightRenderer = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(rightRenderer)
        rightRenderer.SetViewport(0.5, 0, 1, 1)
        rightRenderer.SetBackground(0.4, 0.5, 0.6)
        rightRenderer.AddActor(triangleActor)

        leftRenderer.ResetCamera()
        rightRenderer.ResetCamera()

        self._initialized = False
Exemplo n.º 18
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create source
        polygonSource = vtk.vtkRegularPolygonSource()
        polygonSource.Update()

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputConnection(polygonSource.GetOutputPort())
        triangleFilter.Update()

        inputMapper = vtk.vtkPolyDataMapper()
        inputMapper.SetInputConnection(polygonSource.GetOutputPort())
        inputActor = vtk.vtkActor()
        inputActor.SetMapper(inputMapper)
        inputActor.GetProperty().SetRepresentationToWireframe()

        triangleMapper = vtk.vtkPolyDataMapper()
        triangleMapper.SetInputConnection(triangleFilter.GetOutputPort())
        triangleActor = vtk.vtkActor()
        triangleActor.SetMapper(triangleMapper)
        triangleActor.GetProperty().SetRepresentationToWireframe()
 
        # Setup renderers
        leftRenderer = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(leftRenderer)
        leftRenderer.SetViewport(0, 0, 0.5, 1)
        leftRenderer.SetBackground(0.6, 0.5, 0.4)
        leftRenderer.AddActor(inputActor)

        rightRenderer = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(rightRenderer)
        rightRenderer.SetViewport(0.5, 0, 1, 1)
        rightRenderer.SetBackground(0.4, 0.5, 0.6)
        rightRenderer.AddActor(triangleActor)

        leftRenderer.ResetCamera()
        rightRenderer.ResetCamera()

        self._initialized = False
Exemplo n.º 19
0
def make_polydata_actor(centers, normals, return_pdm=False, type='circle'):
    """ Create the actor and set colors

    :param return_pdm: if True give back the polydatamapper
    :param centers: list of centers as tuples 
    :param normals: list of list of normals as tuples
    """

    # In order to build the bounding box it is convenient to combine
    # All sources using a vtkAppenPolyData
    apd = vtk.vtkAppendPolyData()

    mappers = []
    # create source
    for i in range(len(centers)):
        normal = normals[i]
        if normal is None:
            source = vtk.vtkSphereSource()
            source.SetRadius(80)
        else:
            if type == 'torus':
                source = vtk.vtkSuperquadricSource()
                source.SetScale(1.0, 1.0, 1.0)
                source.SetPhiResolution(16)
                source.SetThetaResolution(16)
                source.SetThetaRoundness(1)
                source.SetThickness(0.1)
                source.SetSize(100.5)
                source.SetToroidal(1)
                source.SetNormal(normal)
            elif type == 'circle':
                source = vtk.vtkRegularPolygonSource()
                source.SetNumberOfSides(16)
                source.SetRadius(100)
                source.SetNormal(normal)
        source.SetCenter(*centers[i])
        apd.AddInput(source.GetOutput())
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(apd.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    if return_pdm:
        return actor, apd
    else:
        return actor
Exemplo n.º 20
0
    def __init__(self, position=None, color=None, size=None, filled=None):
        """ Size is the radius of the disk
        """
        Shape.__init__(self, position, color, size, filled)

        source = vtkRegularPolygonSource()
        source.SetNumberOfSides(30)
        source.SetCenter(0, 0, 0)

        mapper = vtkPolyDataMapper()
        mapper.SetInput(source.GetOutput())
        self._actor.SetMapper(mapper)
        # Use flat lightning
        self._actor.GetProperty().SetAmbient(1)

        if size is not None:
            self._set_size(size)
def make_polydata_actor(centers, normals, return_pdm=False, type='circle'):
    """ Create the actor and set colors

    :param return_pdm: if True give back the polydatamapper
    :param centers: list of centers as tuples 
    :param normals: list of list of normals as tuples
    """

    # In order to build the bounding box it is convenient to combine
    # All sources using a vtkAppenPolyData
    apd = vtk.vtkAppendPolyData()

    mappers = []
    # create source
    for i in range(len(centers)):
        normal = normals[i]
        if normal is None:
            source = vtk.vtkSphereSource()
            source.SetRadius(80)
        else:
            if type=='torus':
                source = vtk.vtkSuperquadricSource();
                source.SetScale(1.0, 1.0, 1.0)
                source.SetPhiResolution (16)
                source.SetThetaResolution(16)
                source.SetThetaRoundness (1)
                source.SetThickness (0.1)
                source.SetSize(100.5)
                source.SetToroidal(1)
                source.SetNormal(normal)
            elif type=='circle':
                source = vtk.vtkRegularPolygonSource()
                source.SetNumberOfSides(16)
                source.SetRadius(100)
                source.SetNormal(normal)
        source.SetCenter(*centers[i])
        apd.AddInput(source.GetOutput())
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(apd.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    if return_pdm:
        return actor, apd
    else:
        return actor
Exemplo n.º 22
0
  def get_actor(self, zplane = 0.0):

    polygonSource = vtk.vtkRegularPolygonSource()

    polygonSource.SetNumberOfSides(50)
    polygonSource.SetRadius(self.radius)
    polygonSource.SetCenter(self.cx, self.cy, zplane)
    polygonSource.Update()
           
    mapper = vtk.vtkPolyDataMapper()

    mapper.SetInputConnection(polygonSource.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(1.0, 0.0, 0.0)

    return actor
Exemplo n.º 23
0
def main():
    colors = vtk.vtkNamedColors()

    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 1, 0)
    points.InsertNextPoint(2, 2, 0)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    # Create anything you want here, we will use a polygon for the demo.
    polygonSource = vtk.vtkRegularPolygonSource()  # default is 6 sides

    glyph2D = vtk.vtkGlyph2D()
    glyph2D.SetSourceConnection(polygonSource.GetOutputPort())
    glyph2D.SetInputData(polydata)
    glyph2D.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph2D.GetOutputPort())
    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Salmon'))

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    style = vtk.vtkInteractorStyleImage()
    renderWindowInteractor.SetInteractorStyle(style)

    renderWindow.SetWindowName('Glyph2D')
    renderWindow.Render()
    renderWindowInteractor.Start()
Exemplo n.º 24
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        points = vtk.vtkPoints()
        points.InsertNextPoint(0, 0, 0)
        points.InsertNextPoint(1, 1, 0)
        points.InsertNextPoint(2, 2, 0)

        polyData = vtk.vtkPolyData()
        polyData.SetPoints(points)

        # Create anything you want here, we will use a polygon for the demo.
        polygonSource = vtk.vtkRegularPolygonSource() #default is 6 sides
        glyph2D = vtk.vtkGlyph2D()
        glyph2D.SetSourceConnection(polygonSource.GetOutputPort())
        glyph2D.SetInput(polyData)
        glyph2D.Update()
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph2D.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Exemplo n.º 25
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        points = vtk.vtkPoints()
        points.InsertNextPoint(0, 0, 0)
        points.InsertNextPoint(1, 1, 0)
        points.InsertNextPoint(2, 2, 0)

        polyData = vtk.vtkPolyData()
        polyData.SetPoints(points)

        # Create anything you want here, we will use a polygon for the demo.
        polygonSource = vtk.vtkRegularPolygonSource()  #default is 6 sides
        glyph2D = vtk.vtkGlyph2D()
        glyph2D.SetSourceConnection(polygonSource.GetOutputPort())
        glyph2D.SetInput(polyData)
        glyph2D.Update()

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph2D.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Exemplo n.º 26
0
    def __init__(self,
                 raio,
                 centro,
                 material,
                 grupo="disco",
                 cor=(255, 255, 255)):
        """
        Construtor da classe Disco.

        Args:
            raio (float): raio do disco.
            centro (float[2]): tupla da posição (x,y) do centro do disco.
            material (Material): Material do disco.
            grupo (string): Grupo desse elemento. Padrão "disco".
            cor (int[3]): tupla as 3 componentes RBG 0-255 para cor do elemento.

        """
        Elemento.__init__(self, grupo)
        self._tipo = "Disco"
        self.raio = raio
        self.centro = np.array(centro)
        self.mat = material
        self.area = math.pi * raio**2
        self.massa = self.mat.den * self.area

        # lista de todas as variaveis do elemento ao decorrer da simulação, pos, vel...
        # vel inicial duplicada para calcular corretamente a velocidade média no 1o passo
        self.movimento = {
            'pos': [centro],
            'vel': [self.v0, self.v0],
            'F': [self.F0]
        }

        # config para VTK
        self.disk = vtk.vtkRegularPolygonSource()
        self.disk.SetNumberOfSides(50)
        self.disk.SetRadius(raio)
        #self.disk.SetCenter(centro[0], centro[1], 0)
        self._set_vtk(self.disk, cor)
        self.actor.SetPosition(centro[0], centro[1], 0)
Exemplo n.º 27
0
def main():
    colors = vtk.vtkNamedColors()

    # Create a pentagon
    polygonSource = vtk.vtkRegularPolygonSource()
    polygonSource.SetNumberOfSides(5)
    polygonSource.SetRadius(5)
    polygonSource.SetCenter(0, 0, 0)

    shrink = vtk.vtkShrinkPolyData()
    shrink.SetInputConnection(polygonSource.GetOutputPort())
    shrink.SetShrinkFactor(.9)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(shrink.GetOutputPort())

    back = vtk.vtkProperty()
    back.SetColor(colors.GetColor3d("Tomato"))

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().EdgeVisibilityOn()
    actor.GetProperty().SetLineWidth(5)
    actor.GetProperty().SetColor(colors.GetColor3d("Banana"))
    actor.SetBackfaceProperty(back)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Regular Polygon Source")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Silver"))

    renderWindow.Render()
    renderWindowInteractor.Start()
def make_polydata_actor(centers, normals, colors, return_pdm=False):
    """ Create the actor and set colors

    :param return_pdm: if True give back the polydatamapper
    :param centers: list of centers as tuples 
    :param normals: list of normals as tuples
    :param colors: list of rgb tuples
    """
     
    # In order to build the bounding box it is convenient to combine
    # All sources using a vtkAppenPolyData
    apd = vtk.vtkAppendPolyData()

    mappers = []
    # create source
    for i in range(len(centers)):

        normal = normals[i]
        if normal is None:
            continue
        source = vtk.vtkRegularPolygonSource()
        source.SetNormal(normal)
        source.SetCenter(*centers[i])
        source.SetNumberOfSides(16)
        source.SetRadius(100)
        apd.AddInput(source.GetOutput())
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(apd.GetOutputPort())
    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    
    # set colors:
    actor.GetProperty().SetColor(*colors[i])
    if return_pdm:
        return actor, apd
    else:
        return actor
Exemplo n.º 29
0
    def createActorTubes(self, elements):
        source = vtk.vtkAppendPolyData()
        mapper = vtk.vtkPolyDataMapper()
        actor = vtk.vtkActor()
        # _first = True

        for element in elements:
            cross_section = element.cross_section
            if cross_section:
                polygon = self.createSectionPolygon(element)
            else:  # not cross section
                if self.defaultRadius is None:
                    self.defaultRadius = element.length / 20
                polygon = vtk.vtkRegularPolygonSource()
                polygon.SetRadius(self.defaultRadius)
                polygon.SetNumberOfSides(20)

            tube = self.generalSectionTube(element, polygon.GetOutputPort())
            source.AddInputData(tube.GetOutput())

        mapper.SetInputConnection(source.GetOutputPort())
        actor.SetMapper(mapper)
        return actor
Exemplo n.º 30
0
    def add_case_actors(self, data, actors, color, opacity):
        for i in range(len(data)):

            x = (self.sat_x / 360.0) * (180 + float(data[i][1]))
            y = (self.sat_y / 180.0) * (90 + float(data[i][0]))
            cases = int(data[i][self.date+2])

            if(cases > 0 and (float(data[i][1]) != 0 or float(data[i][0]) != 0)):
                radius = (math.log2(cases)/math.log2(self.max_cases)) * self.max_radius 
                polygon_source = vtk.vtkRegularPolygonSource()
                polygon_source.SetNumberOfSides(50)
                polygon_source.SetRadius(radius)
                polygon_source.SetCenter(x, y, 0)

                cases_mapper = vtk.vtkPolyDataMapper()
                cases_mapper.SetInputConnection(polygon_source.GetOutputPort())

                cases_actor = vtk.vtkActor()
                cases_actor.SetMapper(cases_mapper)
                cases_actor.GetProperty().SetColor(color[0], color[1], color[2])
                cases_actor.GetProperty().SetOpacity(opacity)

                self.ren.AddActor(cases_actor)
                actors.append(cases_actor)
Exemplo n.º 31
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the background color.
    colors.SetColor("BkgColor", [51, 77, 102, 255])

    # Create container to hold the 3D object generators (sources)
    geometricObjectSources = list()

    # Populate the container with the various object sources to be demonstrated
    geometricObjectSources.append(vtk.vtkArrowSource())
    geometricObjectSources.append(vtk.vtkConeSource())
    geometricObjectSources.append(vtk.vtkCubeSource())
    geometricObjectSources.append(vtk.vtkCylinderSource())
    geometricObjectSources.append(vtk.vtkDiskSource())
    geometricObjectSources.append(vtk.vtkLineSource())
    geometricObjectSources.append(vtk.vtkRegularPolygonSource())
    geometricObjectSources.append(vtk.vtkSphereSource())

    # Create containers for the remaining nodes of each pipeline
    mappers = list()
    actors = list()
    textmappers = list()
    textactors = list()

    # Create a common text property.
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(16)
    textProperty.SetJustificationToCentered()

    # Create a mapper and actor for each object and the corresponding text label
    for i in range(0, len(geometricObjectSources)):
        geometricObjectSources[i].Update()

        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(geometricObjectSources[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(
            colors.GetColor3d("Seashell"))

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(
            geometricObjectSources[i].GetClassName())  # set text label to the name of the object source
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(120, 16)  # Note: the position of an Actor2D is specified in display coordinates

    # Define size of the grid that will hold the objects
    gridCols = 3
    gridRows = 3
    # Define side length (in pixels) of each renderer square
    rendererSize = 300

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Geometric Objects Demo")
    renderWindow.SetSize(rendererSize * gridCols, rendererSize * gridRows)

    # Set up a grid of viewports for each renderer
    for row in range(0, gridRows):
        for col in range(0, gridCols):
            index = row * gridCols + col

            # Create a renderer for this grid cell
            renderer = vtk.vtkRenderer()
            renderer.SetBackground(colors.GetColor3d("BkgColor"))

            # Set the renderer's viewport dimensions (xmin, ymin, xmax, ymax) within the render window.
            # Note that for the Y values, we need to subtract the row index from gridRows
            # because the viewport Y axis points upwards, but we want to draw the grid from top to down
            viewport = [
                float(col) / gridCols,
                float(gridRows - row - 1) / gridRows,
                float(col + 1) / gridCols,
                float(gridRows - row) / gridRows
            ]
            renderer.SetViewport(viewport)

            # Add the corresponding actor and label for this grid cell, if they exist
            if index < len(geometricObjectSources):
                renderer.AddActor(actors[index])
                renderer.AddActor(textactors[index])
                renderer.ResetCameraClippingRange()

            renderWindow.AddRenderer(renderer)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    renderWindow.Render()
    interactor.Start()
Exemplo n.º 32
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        # Create source
        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
        
        # Setup the RenderWindow
        self.vtkWidget.GetRenderWindow().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)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])
        
                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4,0.3,0.2)
        
        self._initialized = False
Exemplo n.º 33
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create two polygon sources, one a closed polyline, one a polygon
#
polyline = vtk.vtkRegularPolygonSource()
polyline.SetCenter(1,1,1)
polyline.SetRadius(1)
polyline.SetNumberOfSides(12)
polyline.SetNormal(1,2,3)
polyline.GeneratePolylineOn()
polyline.GeneratePolygonOff()
polylineMapper = vtk.vtkPolyDataMapper()
polylineMapper.SetInputConnection(polyline.GetOutputPort())
polylineActor = vtk.vtkActor()
polylineActor.SetMapper(polylineMapper)
polylineActor.GetProperty().SetColor(0,1,0)
polylineActor.GetProperty().SetAmbient(1)
polygon = vtk.vtkRegularPolygonSource()
polygon.SetCenter(3,1,1)
polygon.SetRadius(1)
polygon.SetNumberOfSides(12)
polygon.SetNormal(1,2,3)
polygon.GeneratePolylineOff()
polygon.GeneratePolygonOn()
polygonMapper = vtk.vtkPolyDataMapper()
polygonMapper.SetInputConnection(polygon.GetOutputPort())
polygonActor = vtk.vtkActor()
Exemplo n.º 34
0
#!/usr/bin/env python

import vtk

# Create a pentagon
polygonSource = vtk.vtkRegularPolygonSource()

#polygonSource.GeneratePolygonOff()
polygonSource.SetNumberOfSides(5)
polygonSource.SetRadius(5)
polygonSource.SetCenter(0,0,0)
polygonSource.Update()

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(polygonSource.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)

renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

renderer.AddActor(actor)
renderer.SetBackground(.3,.3,.5) # Background color purple

renderWindow.Render()
renderWindowInteractor.Start()
Exemplo n.º 35
0
    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()
Exemplo n.º 36
0
#!/usr/bin/env python

import vtk

# Create a pentagon
polygonSource = vtk.vtkRegularPolygonSource()

#polygonSource.GeneratePolygonOff()
polygonSource.SetNumberOfSides(5)
polygonSource.SetRadius(5)
polygonSource.SetCenter(0, 0, 0)
polygonSource.Update()

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(polygonSource.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)

renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

renderer.AddActor(actor)
renderer.SetBackground(.3, .3, .5)  # Background color purple

renderWindow.Render()
renderWindowInteractor.Start()
Exemplo n.º 37
0
    def __init__(self,
                 parent=None,
                 width=400,
                 height=400,
                 showWidget=False,
                 scale=False):
        super(ROIManager, self).__init__()
        self.width = width
        self.height = height
        self.showWidget = showWidget
        self.scale = scale
        self.renderer = None
        self.ROIRadius = 20.0
        self.minValueBG = 0
        self.maxValueBG = 0
        self.minValueFG = 0
        self.maxValueFG = 0
        self.probeWidget = None
        self.drawOverlay = 0

        # utility Qt instances for use in methods
        self.gray = qt.QColor()
        self.gray.setRedF(0.5)
        self.gray.setGreenF(0.5)
        self.gray.setBlueF(0.5)
        # a painter to use for various jobs
        self.painter = qt.QPainter()

        # make a qwidget display
        if self.showWidget:
            self.frame = qt.QFrame(parent)
            mw = slicer.util.mainWindow()
            self.frame.setGeometry(mw.x, mw.y, self.width, self.height)
            self.frameLayout = qt.QVBoxLayout(self.frame)
            self.label = qt.QLabel()
            self.frameLayout.addWidget(self.label)
            self.frame.show()

        # make an image actor in the slice view
        self.vtkImage = vtk.vtkImageData()

        self.mrmlUtils = slicer.qMRMLUtils()
        self.imageMapper = vtk.vtkImageMapper()
        self.imageMapper.SetColorLevel(128)
        self.imageMapper.SetColorWindow(255)
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.imageMapper.SetInput(self.vtkImage)
        else:
            self.imageMapper.SetInputData(self.vtkImage)
        self.actor2D = vtk.vtkActor2D()
        self.actor2D.SetMapper(self.imageMapper)

        # make a circle actor
        self.circle = vtk.vtkRegularPolygonSource()
        self.circle.SetNumberOfSides(50)
        self.circle.SetRadius(5)
        self.circle.SetCenter(0, 0, 0)
        self.circle.GeneratePolylineOn()
        self.circle.GeneratePolygonOff()
        self.circle.Update()
        self.mapper = vtk.vtkPolyDataMapper2D()
        self.actor = vtk.vtkActor2D()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.mapper.SetInput(self.circle.GetOutput())
        else:
            self.mapper.SetInputConnection(self.circle.GetOutputPort())
        self.actor.SetMapper(self.mapper)
        property_ = self.actor.GetProperty()
        property_.SetColor(1, 1, 0)
        property_.SetLineWidth(1)
Exemplo n.º 38
0
def test_custom_interactor_style_events(recording=False):
    print("Using VTK {}".format(vtk.vtkVersion.GetVTKVersion()))
    filename = "test_custom_interactor_style_events.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)
    scene = window.Scene()

    # the show manager allows to break the rendering process
    # in steps so that the widgets can be added properly
    interactor_style = interactor.CustomInteractorStyle()
    show_manager = window.ShowManager(scene,
                                      size=(800, 800),
                                      reset_camera=False,
                                      interactor_style=interactor_style)

    # Create a cursor, a circle that will follow the mouse.
    polygon_source = vtk.vtkRegularPolygonSource()
    polygon_source.GeneratePolygonOff()  # Only the outline of the circle.
    polygon_source.SetNumberOfSides(50)
    polygon_source.SetRadius(10)
    # polygon_source.SetRadius
    polygon_source.SetCenter(0, 0, 0)

    mapper = vtk.vtkPolyDataMapper2D()
    vtk_utils.set_input(mapper, polygon_source.GetOutputPort())

    cursor = vtk.vtkActor2D()
    cursor.SetMapper(mapper)
    cursor.GetProperty().SetColor(1, 0.5, 0)
    scene.add(cursor)

    def follow_mouse(iren, obj):
        obj.SetPosition(*iren.event.position)
        iren.force_render()

    interactor_style.add_active_prop(cursor)
    interactor_style.add_callback(cursor, "MouseMoveEvent", follow_mouse)

    # create some minimalistic streamlines
    lines = [
        np.array([[-1, 0, 0.], [1, 0, 0.]]),
        np.array([[-1, 1, 0.], [1, 1, 0.]])
    ]
    colors = np.array([[1., 0., 0.], [0.3, 0.7, 0.]])
    tube1 = actor.streamtube([lines[0]], colors[0])
    tube2 = actor.streamtube([lines[1]], colors[1])
    scene.add(tube1)
    scene.add(tube2)

    # Define some counter callback.
    states = defaultdict(lambda: 0)

    def counter(iren, _obj):
        states[iren.event.name] += 1

    # Assign the counter callback to every possible event.
    for event in [
            "CharEvent", "MouseMoveEvent", "KeyPressEvent", "KeyReleaseEvent",
            "LeftButtonPressEvent", "LeftButtonReleaseEvent",
            "RightButtonPressEvent", "RightButtonReleaseEvent",
            "MiddleButtonPressEvent", "MiddleButtonReleaseEvent"
    ]:
        interactor_style.add_callback(tube1, event, counter)

    # Add callback to scale up/down tube1.
    def scale_up_obj(iren, obj):
        counter(iren, obj)
        scale = np.asarray(obj.GetScale()) + 0.1
        obj.SetScale(*scale)
        iren.force_render()
        iren.event.abort()  # Stop propagating the event.

    def scale_down_obj(iren, obj):
        counter(iren, obj)
        scale = np.array(obj.GetScale()) - 0.1
        obj.SetScale(*scale)
        iren.force_render()
        iren.event.abort()  # Stop propagating the event.

    interactor_style.add_callback(tube2, "MouseWheelForwardEvent",
                                  scale_up_obj)
    interactor_style.add_callback(tube2, "MouseWheelBackwardEvent",
                                  scale_down_obj)

    # Add callback to hide/show tube1.
    def toggle_visibility(iren, obj):
        key = iren.event.key
        if key.lower() == "v":
            obj.SetVisibility(not obj.GetVisibility())
            iren.force_render()

    interactor_style.add_active_prop(tube1)
    interactor_style.add_active_prop(tube2)
    interactor_style.remove_active_prop(tube2)
    interactor_style.add_callback(tube1, "CharEvent", toggle_visibility)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(states.items()))
    else:
        show_manager.play_events_from_file(recording_filename)
        msg = ("Wrong count for '{}'.")
        expected = [('CharEvent', 6), ('KeyPressEvent', 6),
                    ('KeyReleaseEvent', 6), ('MouseMoveEvent', 1652),
                    ('LeftButtonPressEvent', 1), ('RightButtonPressEvent', 1),
                    ('MiddleButtonPressEvent', 2),
                    ('LeftButtonReleaseEvent', 1),
                    ('MouseWheelForwardEvent', 3),
                    ('MouseWheelBackwardEvent', 1),
                    ('MiddleButtonReleaseEvent', 2),
                    ('RightButtonReleaseEvent', 1)]

        # Useful loop for debugging.
        for event, count in expected:
            if states[event] != count:
                print("{}: {} vs. {} (expected)".format(
                    event, states[event], count))

        for event, count in expected:
            npt.assert_equal(states[event], count, err_msg=msg.format(event))
Exemplo n.º 39
0
    def createSectionPolygon(self, element):

        if None in [element.cross_section, element.cross_section_points]:
            poly = vtk.vtkRegularPolygonSource()
            poly.SetNumberOfSides(3)
            poly.SetNormal(1, 0, 0)
            poly.SetRadius(1e-6)
            return poly

        if self.pressure_plot:
            if element.element_type in ['beam_1']:
                poly = vtk.vtkRegularPolygonSource()
                poly.SetNumberOfSides(3)
                poly.SetNormal(1, 0, 0)
                poly.SetRadius(1e-6)
                return poly
            elif element.valve_parameters:
                r = (element.valve_diameters[element.index][1] / 2) * self.bff
            elif element.perforated_plate:
                r = (element.perforated_plate.hole_diameter / 2) * self.bff
            else:
                r = (element.cross_section.inner_diameter / 2) * self.bff

            poly = vtk.vtkRegularPolygonSource()
            poly.SetNumberOfSides(36)
            poly.SetNormal(1, 0, 0)
            poly.SetRadius(r)
            return poly

        outer_points, inner_points, _ = element.cross_section_points
        number_inner_points = len(inner_points)
        number_outer_points = len(outer_points)

        # definitions
        points = vtk.vtkPoints()
        outerData = vtk.vtkPolyData()
        innerPolygon = vtk.vtkPolygon()
        innerCell = vtk.vtkCellArray()
        innerData = vtk.vtkPolyData()
        delaunay = vtk.vtkDelaunay2D()

        outerPolygon = vtk.vtkPolygon()
        edges = vtk.vtkCellArray()
        source = vtk.vtkTriangleFilter()

        # create points
        for y, z in inner_points:
            y *= self.bff
            z *= self.bff
            points.InsertNextPoint(0, y, z)

        for y, z in outer_points:
            y *= self.bff
            z *= self.bff
            points.InsertNextPoint(0, y, z)

        # create external polygon
        outerData.SetPoints(points)

        #TODO: clean-up the structure below
        if number_inner_points >= 3:

            delaunay.SetProjectionPlaneMode(2)
            delaunay.SetInputData(outerData)

            # remove inner area for holed sections
            for i in range(number_inner_points):
                innerPolygon.GetPointIds().InsertNextId(i)

            innerCell.InsertNextCell(innerPolygon)
            innerData.SetPoints(points)
            innerData.SetPolys(innerCell)
            delaunay.SetSourceData(innerData)
            delaunay.Update()

            return delaunay

        else:

            # prevents bugs on the outer section
            for i in range(number_outer_points):
                outerPolygon.GetPointIds().InsertNextId(i)
            edges.InsertNextCell(outerPolygon)

            outerData.SetPolys(edges)
            source.AddInputData(outerData)
            return source
Exemplo n.º 40
0
    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()
Exemplo n.º 41
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        # Create source
        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

        # Setup the RenderWindow
        self.vtkWidget.GetRenderWindow().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)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4, 0.3, 0.2)

        self._initialized = False