Exemplo n.º 1
0
class RotationViewer(module_template.Viewer):
    """Uses mayavi to plot a sphere made up of small spheres as pixels. The
    colors indicate the responsability density."""
    def __init__(self, parent=None):
        super(RotationViewer, self).__init__()
        #self._widget = QtGui.QWidget(parent)
        self._vtk_widget = QVTKRenderWindowInteractor(self._widget) # _vtk_widget is actually the RenderWindowInteractor
        self._vtk_widget.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick())

        #self._vtk_widget.Initialize()
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self._vtk_widget)
        self._widget.setLayout(layout)

        self._renderer = vtk.vtkRenderer()
        self._vtk_widget.GetRenderWindow().AddRenderer(self._renderer)

        #self._mlab_widget = embedded_mayavi.MlabWidget()
        self._setup_done = False
        self._points = None
        self._default_sphere_n = 10
        self._sphere = vtk_tools.SphereMap(self._default_sphere_n)
        self._renderer.AddViewProp(self._sphere.get_actor())
        self._renderer.SetBackground(1., 1., 1.)
        #self._renderer.Render()

    def initialize(self):
        self._vtk_widget.Initialize()

    # def get_widget(self):
    #     """Return the widget containing the view."""
    #     return self._vtk_widget

    def set_sampling_n(self, sampling_n):
        """Rerun when the array size changes."""
        self._sphere.set_n(sampling_n)

    def get_coordinates(self):
        return self._sphere.get_coordinates()

    def get_number_of_points():
        pass

    def plot_rotations(self, values):
        """Update the viewer to show the new values."""
        if len(values) != self._sphere.get_number_of_points():
            #raise ValueError("values must be array of length {0}. Length {1} array received.".format(self._sphere.get_number_of_points(), len(values)))
            sampling_n = icosahedral_sphere.points_to_n(len(values))
            self.set_sampling_n(sampling_n)
        self._sphere.set_lookup_table(vtk_tools.get_lookup_table(0., values.max(), log=False, colorscale="jet", number_of_colors=1000))
        self._sphere.set_values(values)
        #self._sphere
        #self._renderer.Render()
        self._vtk_widget.Render()
Exemplo n.º 2
0
class Main(QtGui.QMainWindow):
    def resizeEvent(self, Event):
        pass
        #self.ModelView.resize(self.ui.ModelFrame.geometry().width()-15,self.ui.ModelFrame.geometry().height()-39)

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle(
            QtGui.QApplication.translate("MainWindow", "3DLP Slicer", None,
                                         QtGui.QApplication.UnicodeUTF8))

        #load previous settings from config file here:
        self.parser = SafeConfigParser()
        filename = 'sliceconfig.ini'
        if hasattr(sys, '_MEIPASS'):
            # PyInstaller >= 1.6
            os.chdir(sys._MEIPASS)
            filename = os.path.join(sys._MEIPASS, filename)
            APPNAME = '3DLP'
            APPDATA = os.path.join(os.environ['APPDATA'], APPNAME)
            if not os.path.isdir(os.path.join(APPDATA)):
                os.mkdir(os.path.join(APPDATA))
                shutil.copy(filename, os.path.join(APPDATA, ''))
                self.parser.read(os.path.join(APPDATA, 'sliceconfig.ini'))
                self.LoadSettingsFromConfigFile()
            else:
                if not os.path.isfile(os.path.join(APPDATA,
                                                   'sliceconfig.ini')):
                    shutil.copy(filename, os.path.join(APPDATA))
                else:
                    self.parser.read(os.path.join(APPDATA, 'sliceconfig.ini'))
                    self.LoadSettingsFromConfigFile()
        else:  #otherwise it's running in pydev environment: use the dev config file
            os.chdir(os.path.dirname(sys.argv[0]))
            filename = os.path.join(os.path.dirname(sys.argv[0]), filename)
            self.parser.read('sliceconfig.ini')
            self.LoadSettingsFromConfigFile()

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(.4, .4, .4)

        # create the modelview widget
        self.ModelView = QVTKRenderWindowInteractor(self.ui.ModelFrame)
        self.ModelView.SetInteractorStyle(MyInteractorStyle())
        self.ModelView.Initialize()
        self.ModelView.Start()

        self.renWin = self.ModelView.GetRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.ModelView.show()

        self.ModelView.resize(1006 - 17, 716 - 39)
        #self.ModelView.resize(self.ui.ModelFrame.geometry().width()-1,self.ui.ModelFrame.geometry().height()-1)

        self.modelList = []

    def AddModel(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Open 3D Model',
                                                     '.', '*.stl')
        if filename == '':  #user hit cancel
            return
        modelObject = model(self, filename)
        self.modelList.append(modelObject)
        self.ui.modelList.addItem(os.path.basename(str(filename)))
        if len(self.modelList) == 1:
            self.FirstOpen()

        self.ren.ResetCamera()
        self.ModelView.Render()  #update model view

    def FirstOpen(self):
        #create annotated cube anchor actor
        self.axesActor = vtk.vtkAnnotatedCubeActor()
        self.axesActor.SetXPlusFaceText('Right')
        self.axesActor.SetXMinusFaceText('Left')
        self.axesActor.SetYMinusFaceText('Front')
        self.axesActor.SetYPlusFaceText('Back')
        self.axesActor.SetZMinusFaceText('Bot')
        self.axesActor.SetZPlusFaceText('Top')
        self.axesActor.GetTextEdgesProperty().SetColor(.8, .8, .8)
        self.axesActor.GetZPlusFaceProperty().SetColor(.8, .8, .8)
        self.axesActor.GetZMinusFaceProperty().SetColor(.8, .8, .8)
        self.axesActor.GetXPlusFaceProperty().SetColor(.8, .8, .8)
        self.axesActor.GetXMinusFaceProperty().SetColor(.8, .8, .8)
        self.axesActor.GetYPlusFaceProperty().SetColor(.8, .8, .8)
        self.axesActor.GetYMinusFaceProperty().SetColor(.8, .8, .8)
        self.axesActor.GetTextEdgesProperty().SetLineWidth(2)
        self.axesActor.GetCubeProperty().SetColor(.2, .2, .2)
        self.axesActor.SetFaceTextScale(0.25)
        self.axesActor.SetZFaceTextRotation(90)

        #create orientation markers
        self.axes = vtk.vtkOrientationMarkerWidget()
        self.axes.SetOrientationMarker(self.axesActor)
        self.axes.SetInteractor(self.ModelView)
        self.axes.EnabledOn()
        self.axes.InteractiveOff()

        self.ui.Transform_groupbox.setEnabled(True)

    def SliceModel(self):
        try:
            if self.modelActor:  #check to see if a model is loaded, if not it will throw an exception
                pass
        except:  #self.modelActor doesn't exist (hasn't been instantiated with a model yet)
            QtGui.QMessageBox.critical(
                self, 'Error slicing model',
                "You must first load a model to slice it!",
                QtGui.QMessageBox.Ok)
            return
        self.outputFile = str(
            QFileDialog.getSaveFileName(self, "Save file", "", ".3dlp"))
        self.slicer = slicer.slicer(self)
        self.slicer.imageheight = int(self.imageHeight)
        self.slicer.imagewidth = int(self.imageWidth)
        # check to see if starting depth is less than ending depth!! this assumption is crucial
        self.slicer.startingdepth = float(self.startingDepth)
        self.slicer.endingdepth = float(self.endingDepth)
        self.slicer.layerincrement = float(self.slicingIncrement)
        self.slicer.OpenModel(self.filename)
        self.slicer.slice()

    def UpdateModelOpacity(self):
        try:
            if self.modelActor:  #check to see if a model is loaded, if not it will throw an exception
                opacity, ok = QtGui.QInputDialog.getText(
                    self, 'Model Opacity',
                    'Enter the desired opacity (0-100):')
                if not ok:  #the user hit the "cancel" button
                    return
                self.modelActor.GetProperty().SetOpacity(float(opacity) / 100)
                self.ren.Render()
                self.ModelView.Render()
        except:  #self.modelActor doesn't exist (hasn't been instantiated with a model yet)
            QtGui.QMessageBox.critical(
                self, 'Error setting opacity',
                "You must first load a model to change its opacity!",
                QtGui.QMessageBox.Ok)

    def ModelIndexChanged(self, new, previous):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        self.ui.positionX.setValue(modelObject.CurrentXPosition)
        self.ui.positionY.setValue(modelObject.CurrentYPosition)
        self.ui.positionZ.setValue(modelObject.CurrentZPosition)
        self.ui.rotationX.setValue(modelObject.CurrentXRotation)
        self.ui.rotationY.setValue(modelObject.CurrentYRotation)
        self.ui.rotationZ.setValue(modelObject.CurrentZRotation)
        self.ui.scale.setValue(modelObject.CurrentScale)

    def Update_Position_X(self, position):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        transform = modelObject.transform
        transform.Translate((float(position) - modelObject.CurrentXPosition),
                            0.0, 0.0)
        modelObject.CurrentXPosition = modelObject.CurrentXPosition + (
            float(position) - modelObject.CurrentXPosition)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(transform)
        transformFilter.SetInputConnection(modelObject.reader.GetOutputPort())
        transformFilter.Update()
        modelObject.mapper.SetInputConnection(transformFilter.GetOutputPort())
        modelObject.mapper.Update()
        self.ren.Render()
        self.ModelView.Render()

    def Update_Position_Y(self, position):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        transform = modelObject.transform
        transform.Translate(0.0,
                            (float(position) - modelObject.CurrentYPosition),
                            0.0)
        modelObject.CurrentYPosition = modelObject.CurrentYPosition + (
            float(position) - modelObject.CurrentYPosition)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(transform)
        transformFilter.SetInputConnection(modelObject.reader.GetOutputPort())
        transformFilter.Update()
        modelObject.mapper.SetInputConnection(transformFilter.GetOutputPort())
        modelObject.mapper.Update()
        self.ren.Render()
        self.ModelView.Render()

    def Update_Position_Z(self, position):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        transform = modelObject.transform
        transform.Translate(0.0, 0.0,
                            (float(position) - modelObject.CurrentZPosition))
        modelObject.CurrentZPosition = modelObject.CurrentZPosition + (
            float(position) - modelObject.CurrentZPosition)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(transform)
        transformFilter.SetInputConnection(modelObject.reader.GetOutputPort())
        transformFilter.Update()
        modelObject.mapper.SetInputConnection(transformFilter.GetOutputPort())
        modelObject.mapper.Update()
        self.ren.Render()
        self.ModelView.Render()

    def Update_Rotation_X(self, rotation):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        transform = modelObject.transform
        transform.RotateX((float(rotation) - modelObject.CurrentXRotation))
        modelObject.CurrentXRotation = modelObject.CurrentXRotation + (
            float(rotation) - modelObject.CurrentXRotation)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(transform)
        transformFilter.SetInputConnection(modelObject.reader.GetOutputPort())
        transformFilter.Update()
        modelObject.mapper.SetInputConnection(transformFilter.GetOutputPort())
        modelObject.mapper.Update()
        self.ren.Render()
        self.ModelView.Render()

    def Update_Rotation_Y(self, rotation):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        transform = modelObject.transform
        transform.RotateY((float(rotation) - modelObject.CurrentYRotation))
        modelObject.CurrentYRotation = modelObject.CurrentYRotation + (
            float(rotation) - modelObject.CurrentYRotation)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(transform)
        transformFilter.SetInputConnection(modelObject.reader.GetOutputPort())
        transformFilter.Update()
        modelObject.mapper.SetInputConnection(transformFilter.GetOutputPort())
        modelObject.mapper.Update()
        self.ren.Render()
        self.ModelView.Render()

    def Update_Rotation_Z(self, rotation):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        transform = modelObject.transform
        transform.RotateZ((float(rotation) - modelObject.CurrentZRotation))
        modelObject.CurrentZRotation = modelObject.CurrentZRotation + (
            float(rotation) - modelObject.CurrentZRotation)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(transform)
        transformFilter.SetInputConnection(modelObject.reader.GetOutputPort())
        transformFilter.Update()
        modelObject.mapper.SetInputConnection(transformFilter.GetOutputPort())
        modelObject.mapper.Update()
        self.ren.Render()
        self.ModelView.Render()

    def Update_Scale(self, scale):
        modelObject = self.modelList[self.ui.modelList.currentRow()]
        transform = modelObject.transform

        self.reader = vtk.vtkSTLReader()
        self.reader.SetFileName(str(self.filename))

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.reader.GetOutputPort())

        #create model actor
        self.actor = vtk.vtkActor()
        self.actor.GetProperty().SetColor(1, 1, 1)
        self.actor.GetProperty().SetOpacity(1)
        self.actor.SetMapper(self.mapper)

        #create outline mapper
        self.outline = vtk.vtkOutlineFilter()
        self.outline.SetInputConnection(self.reader.GetOutputPort())
        self.outlineMapper = vtk.vtkPolyDataMapper()
        self.outlineMapper.SetInputConnection(self.outline.GetOutputPort())

        #create outline actor
        self.outlineActor = vtk.vtkActor()
        self.outlineActor.SetMapper(self.outlineMapper)

        #add actors to parent render window
        self.parent.ren.AddActor(self.actor)
        self.parent.ren.AddActor(self.outlineActor)

        delta = modelObject.PreviousScale - modelObject.CurrentScale
        modelObject.transform
        #transform.Scale((float(scale)-modelObject.CurrentScale)/100.0, (float(scale)-modelObject.CurrentScale)/100.0, (float(scale)-modelObject.CurrentScale)/100.0)
        transform.Scale
        modelObject.CurrentScale = modelObject.CurrentScale + (
            float(scale) - modelObject.CurrentScale)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(modelObject.transform)
        transformFilter.SetInputConnection(modelObject.reader.GetOutputPort())
        transformFilter.Update()
        modelObject.mapper.SetInputConnection(transformFilter.GetOutputPort())
        modelObject.mapper.Update()
        self.ren.Render()
        self.ModelView.Render()

    def LoadSettingsFromConfigFile(self):
        self.imageHeight = int(
            self.parser.get('slicing_settings', 'Image_Height'))
        self.imageWidth = int(
            self.parser.get('slicing_settings', 'Image_Width'))
        self.startingDepth = int(
            self.parser.get('slicing_settings', 'Starting_Depth'))
        self.endingDepth = int(
            self.parser.get('slicing_settings', 'Ending_Depth'))
        self.slicingIncrement = int(
            self.parser.get('slicing_settings', 'Slicing_Increment'))
        self.slicingplane = self.parser.get('slicing_settings',
                                            'Slicing_Plane')

    def OpenSettingsDialog(self):
        self.SettingsDialog = StartSettingsDialog(self)
        self.connect(self.SettingsDialog, QtCore.SIGNAL('ApplySettings()'),
                     self.getSettingsDialogValues)
        self.SettingsDialog.imageHeight.setText(str(self.imageHeight))
        self.SettingsDialog.imageWidth.setText(str(self.imageWidth))
        self.SettingsDialog.startingDepth.setText(str(self.startingDepth))
        self.SettingsDialog.endingDepth.setText(str(self.endingDepth))
        self.SettingsDialog.slicingIncrement.setText(str(
            self.slicingIncrement))
        self.slicingplaneDict = {"XZ": 0, "XY": 1, "YZ": 2}
        try:
            self.SettingsDialog.slicingPlane.setCurrentIndex(
                self.slicingplaneDict[self.slicingplane])
        except:  #anything other than a valid entry will default to XZ (index 0)
            self.SettingsDialog.slicingPlane.setCurrentIndex(0)
        self.SettingsDialog.exec_()

    def getSettingsDialogValues(self):
        self.imageHeight = int(self.SettingsDialog.imageHeight.text())
        self.parser.set('slicing_settings', 'Image_Height',
                        "%s" % self.imageHeight)
        self.imageWidth = int(self.SettingsDialog.imageWidth.text())
        self.parser.set('slicing_settings', 'Image_Width',
                        "%s" % self.imageWidth)
        self.startingDepth = int(self.SettingsDialog.startingDepth.text())
        self.parser.set('slicing_settings', 'Starting_Depth',
                        "%s" % self.startingDepth)
        self.endingDepth = int(self.SettingsDialog.endingDepth.text())
        self.parser.set('slicing_settings', 'Ending_Depth',
                        "%s" % self.endingDepth)
        self.slicingIncrement = int(
            self.SettingsDialog.slicingIncrement.text())
        self.parser.set('slicing_settings', 'Slicing_Increment',
                        "%s" % self.slicingIncrement)
        self.slicingplane = self.SettingsDialog.slicingPlane.currentText()
        self.parser.set('slicing_settings', 'Slicing_Plane',
                        "%s" % self.slicingplane)

        filename = 'sliceconfig.ini'
        if hasattr(sys, '_MEIPASS'):
            # PyInstaller >= 1.6
            APPNAME = '3DLP'
            APPDATA = os.path.join(os.environ['APPDATA'], APPNAME)
            filename = os.path.join(APPDATA, filename)
            outputini = open(
                filename, 'w'
            )  #open a file pointer for the config file parser to write changes to
            self.parser.write(outputini)
            outputini.close()  #done writing config file changes
        else:  #otherwise it's running in pydev environment: use the dev config file
            os.chdir(os.path.dirname(sys.argv[0]))
            filename = os.path.join(os.path.dirname(sys.argv[0]), filename)
            outputini = open(
                filename, 'w'
            )  #open a file pointer for the config file parser to write changes to
            self.parser.write(outputini)
            outputini.close()  #done writing config file changes
Exemplo n.º 3
0
class Editor(QtGui.QDialog):

        def __init__(self):
            super(Editor,self).__init__()
            self.loadedImage = 0
            self.loadedSegmentation = 0
            self.images = []
            self.img_data = []
            self.vols = []
            self.ui = uic.loadUi('window.ui',self)
            self.minVal = 10000;
            self.maxVal = -10000;


            self.initRenderWindow()
            self.initFunctionality()
            self.show()
            self.vtkWidget.resize(self.frame.width(),self.frame.height())

        def initFunctionality(self):

            self.quitButton.clicked.connect(QtCore.QCoreApplication.instance().quit)
            self.searchButton.clicked.connect(lambda: self.loadImage())
            self.segmentationButton.clicked.connect(lambda: self.loadSegmentation())
            self.spinBox.valueChanged.connect(lambda: self.horizontalSlider.setValue(self.spinBox.value()))
            self.horizontalSlider.valueChanged.connect(lambda: self.spinBox.setValue(self.horizontalSlider.value()))
            self.horizontalSlider.valueChanged.connect(lambda: self.updateImage())
            self.horizontalSlider.setValue(0)

            self.verticalSlider.valueChanged.connect(lambda: self.updateOpacityTransferFunction())
            self.verticalSlider_2.valueChanged.connect(lambda: self.updateOpacityTransferFunction())
            self.checkBox.stateChanged.connect(lambda: self.segmentationOnOff())

        def initRenderWindow(self):

            pix_diag = 5.0
            self.nVolumes = 0

            self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
            self.ren = vtk.vtkRenderer()
            self.ren.SetBackground(1.0, 1.0, 1.0)
            self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
            self.window = self.vtkWidget.GetRenderWindow()
            self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()



            drange = [0,400]

            self.vtkWidget.opacity_tf = vtk.vtkPiecewiseFunction()
            self.vtkWidget.opacity_tf.AddPoint(drange[0],0.0)
            self.vtkWidget.opacity_tf.AddPoint(drange[1],0.0)
            self.vtkWidget.color_tf = vtk.vtkColorTransferFunction()
            self.vtkWidget.color_tf.AddRGBPoint(drange[0], 0.0, 0.0, 0.0)
            self.vtkWidget.color_tf.AddRGBPoint(drange[1], 1.0, 1.0, 1.0)
            self.vtkWidget.volProperty = vtk.vtkVolumeProperty()
            self.vtkWidget.volProperty.SetColor(self.vtkWidget.color_tf);
            self.vtkWidget.volProperty.SetScalarOpacity(self.vtkWidget.opacity_tf)
            self.vtkWidget.volProperty.ShadeOn()
            self.vtkWidget.volProperty.SetInterpolationTypeToLinear()
            self.vtkWidget.volProperty.SetScalarOpacityUnitDistance(pix_diag)







        def getImage(self,filename):

            if str(filename).endswith('nii') or str(filename).endswith('nii.gz'):
                nim = NiftiImage(str(filename))
                shape = nim.data.shape

                img_data = nim.data

                miny = np.amin(img_data)
                arr = img_data.astype(float)
                arr -= miny
                maxy = np.amax(arr)
                arr = arr / (maxy/2)
                arr -= 1
                arr = sk.img_as_ubyte(arr)

                img_data = arr

            elif str(filename).endswith('hdr'):
                # Use the header to figure out the shape of the data
                # then load the raw data and reshape the array

                img_data = np.frombuffer(open(str(filename).replace('.hdr', '.dat'), 'rb').read(),
                                            np.uint8)\
                            .reshape((shape[2], shape[1], shape[0]))

            return (img_data,shape)

        def addVolumeToRenderer(self,img):

            pix_diag = 5.0

            self.compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
            self.compositeFunction.SetCompositeMethodToInterpolateFirst()

            self.vtkWidget.Render()
            self.volMapper = vtk.vtkVolumeRayCastMapper()
            self.window.Render()
            self.extensions = vtk.vtkOpenGLExtensionManager()
            self.extensions.SetRenderWindow(self.window)
            self.extensions.Update()


            string = self.extensions.GetExtensionsString()

            print(self.extensions.GetExtensionsString())


            self.volMapper.SetVolumeRayCastFunction(self.compositeFunction)
            self.volMapper.SetSampleDistance(pix_diag / 5.0)

            self.volMapper.SetInputConnection(img.GetOutputPort())


            self.updateColourTransferFunction()
            self.updateOpacityTransferFunction()

            self.plane = vtk.vtkPlanes()

            def ClipVolumeRender(obj, event):
                obj.GetPlanes(self.plane)
                self.volMapper.SetClippingPlanes(self.plane)

            self.boxWidget = vtk.vtkBoxWidget()
            self.boxWidget.SetInteractor(self.vtkWidget)
            self.boxWidget.SetPlaceFactor(1.0)

            self.boxWidget.SetInput(img.GetOutput())
            self.boxWidget.PlaceWidget()
            self.boxWidget.InsideOutOn()
            self.boxWidget.AddObserver("InteractionEvent", ClipVolumeRender)

            self.outlineProperty = self.boxWidget.GetOutlineProperty()
            self.outlineProperty.SetRepresentationToWireframe()
            self.outlineProperty.SetAmbient(1.0)
            self.outlineProperty.SetAmbientColor(0, 0, 0)
            self.outlineProperty.SetLineWidth(3)

            self.selectedOutlineProperty = self.boxWidget.GetSelectedOutlineProperty()
            self.selectedOutlineProperty.SetRepresentationToWireframe()
            self.selectedOutlineProperty.SetAmbient(1.0)
            self.selectedOutlineProperty.SetAmbientColor(1, 0, 0)
            self.selectedOutlineProperty.SetLineWidth(3)

            self.outline = vtk.vtkOutlineFilter()
            self.outline.SetInputConnection(img.GetOutputPort())
            self.outlineMapper = vtk.vtkPolyDataMapper()
            self.outlineMapper.SetInputConnection(self.outline.GetOutputPort())
            self.outlineActor = vtk.vtkActor()
            self.outlineActor.SetMapper(self.outlineMapper)

            self.vol = vtk.vtkVolume()
            self.vol.SetMapper(self.volMapper)
            self.vol.SetProperty(self.vtkWidget.volProperty)

            self.ren.AddVolume(self.vol)
            self.ren.AddActor(self.outlineActor)

            self.window.Render()

        def arrayToVTKImage(self, array, shape):

            if len(shape) == 4 and shape[0] == 1:
                shape = (shape[1], shape[2], shape[3])

            image = vtk.vtkImageImport()
            image.CopyImportVoidPointer(array, array.nbytes)
            image.SetDataScalarTypeToUnsignedChar()
            image.SetNumberOfScalarComponents(1)
            image.SetDataExtent(0, shape[2]-1, 0, shape[1]-1, 0, shape[0]-1)
            image.SetWholeExtent(0, shape[2]-1, 0, shape[1]-1, 0, shape[0]-1)

            return image

        def addSegmentationToImage(self):

            dmc = vtk.vtkDiscreteMarchingCubes()
            dmc.SetInputConnection(self.segImage.GetOutputPort())
            dmc.GenerateValues(1, 255, 255)
            dmc.Update()
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(dmc.GetOutputPort())

            self.checkBox.setEnabled(True)
            self.checkBox.setCheckState(2)


            actor = vtk.vtkActor()
            actor.SetMapper(mapper)

            self.ren.AddActor(actor)
            self.window.Render()


        @pyqtSlot()
        def loadImage(self):

            filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '/media/My Passport/CTPaperCTData/Russ/C34R1/VesselSegmentation');

            self.img_data, shape = self.getImage(filename)

            self.image = self.arrayToVTKImage(self.img_data, shape)

            self.maxVal = max(self.maxVal, np.amax(self.img_data))
            self.minVal = min(self.minVal, np.amin(self.img_data))
            self.range = self.maxVal - self.minVal

            self.addVolumeToRenderer(self.image)

            self.ren.ResetCamera()
            self.cam1 = self.ren.GetActiveCamera()

            self.style = vtk.vtkInteractorStyleTrackballCamera()
            self.vtkWidget.SetInteractorStyle(self.style)
            self.vtkWidget.lighting = True

            self.update()

            self.iren.Render()

            self.loadedImage = 1

        def loadSegmentation(self):


            filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '/media/My Passport/CTPaperCTData/Russ/C34R1/VesselSegmentation');

            self.seg_data, self.seg_shape = self.getImage(filename)

            self.segImage = self.arrayToVTKImage(self.seg_data, self.seg_shape)

            self.addSegmentationToImage()





        def updateOpacityTransferFunction(self):


            bottomSliderVal = self.verticalSlider.value()
            topSliderVal = self.verticalSlider_2.value()

            upperVal = min(self.maxVal, bottomSliderVal+topSliderVal/2)
            lowerVal = max(self.minVal, bottomSliderVal-topSliderVal/2)

            self.vtkWidget.opacity_tf.RemoveAllPoints()
            self.vtkWidget.opacity_tf.AddPoint(self.minVal, 0.0)
            self.vtkWidget.opacity_tf.AddPoint(lowerVal, 0.0)
            self.vtkWidget.opacity_tf.AddPoint(upperVal, 1.0)
            self.vtkWidget.opacity_tf.AddPoint(self.maxVal, 1.0)

            self.vtkWidget.color_tf.RemoveAllPoints()
            self.vtkWidget.color_tf.AddRGBPoint(self.minVal, 0, 0, 0)
            self.vtkWidget.color_tf.AddRGBPoint(lowerVal, 0, 0, 0)
            self.vtkWidget.color_tf.AddRGBPoint(upperVal, 1, 1, 1)
            self.vtkWidget.color_tf.AddRGBPoint(self.maxVal, 1, 1, 1)

            self.vtkWidget.Render()

        def updateColourTransferFunction(self):


            self.vtkWidget.color_tf.RemoveAllPoints()
            self.vtkWidget.color_tf.AddRGBPoint(self.minVal, 0, 0, 0)
            self.vtkWidget.color_tf.AddRGBPoint(self.maxVal, 1, 1, 1)

        def resizeEvent(self, QResizeEvent):
            if self.loadedImage == 1:
                    self.vtkWidget.resize(self.frame.width(), self.frame.height())

        def segmentationOnOff(self):
            props = self.ren.GetViewProps()
            props.InitTraversal()
            if self.checkBox.checkState() == 0:
                props.GetNextProp()
                props.GetNextProp()
                props.GetNextProp().VisibilityOff()
                self.vtkWidget.Render()
            elif self.checkBox.checkState() == 2:
                props.GetNextProp()
                props.GetNextProp()
                props.GetNextProp().VisibilityOn()
                self.vtkWidget.Render()
Exemplo n.º 4
0
class ParallelCoordinatesWidget(QCellWidget):
    def __init__(self, parent=None):
        QCellWidget.__init__(self, parent)

        centralLayout = QtGui.QVBoxLayout()
        self.setLayout(centralLayout)
        centralLayout.setMargin(0)
        centralLayout.setSpacing(0)

        self.view = vtk.vtkContextView()
        self.widget = QVTKRenderWindowInteractor(
            self,
            rw=self.view.GetRenderWindow(),
            iren=self.view.GetInteractor())

        self.chart = vtk.vtkChartParallelCoordinates()
        self.view.GetScene().AddItem(self.chart)

        self.layout().addWidget(self.widget)

        # Create a annotation link to access selection in parallel coordinates view
        self.annotationLink = vtk.vtkAnnotationLink()
        # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
        # See vtkSelectionNode doc for field and content type enum values
        self.annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(
            1)  # Point
        self.annotationLink.GetCurrentSelection().GetNode(0).SetContentType(
            4)  # Indices
        # Connect the annotation link to the parallel coordinates representation
        self.chart.SetAnnotationLink(self.annotationLink)
        self.annotationLink.AddObserver("AnnotationChangedEvent",
                                        self.selectionCallback)

    def updateContents(self, inputPorts):
        (self.coord, matrix) = inputPorts
        if self.coord is not None: self.coord.register(self)

        self.createTable(matrix)
        self.widget.Initialize()

        # Capture window into history for playback
        # Call this at the end to capture the image after rendering
        QCellWidget.updateContents(self, inputPorts)

    def updateSelection(self, selectedIds):
        if len(selectedIds) == 0: return

        Ids = VN.numpy_to_vtkIdTypeArray(np.array(selectedIds), deep=True)

        node = vtk.vtkSelectionNode()
        node.SetContentType(vtk.vtkSelectionNode.INDICES)
        node.SetFieldType(vtk.vtkSelectionNode.POINT)
        node.SetSelectionList(Ids)

        selection = vtk.vtkSelection()
        selection.AddNode(node)

        self.annotationLink.SetCurrentSelection(selection)
        self.widget.Render()

    def createTable(self, matrix):
        table = vtk.vtkTable()
        for col, attr in zip(matrix.values.T, matrix.attributes):
            column = VN.numpy_to_vtk(col.copy(), deep=True)
            column.SetName(attr)
            table.AddColumn(column)
        self.chart.GetPlot(0).SetInput(table)

        min_ = matrix.values.min() - 0.01
        max_ = matrix.values.max() + 0.01
        for i in range(self.chart.GetNumberOfAxes()):
            self.chart.GetAxis(i).SetRange(min_, max_)
            self.chart.GetAxis(i).SetBehavior(vtk.vtkAxis.FIXED)


#            self.chart.GetAxis(i).SetPosition(vtk.vtkAxis.LEFT)
#            self.chart.GetAxis(i).GetTitleProperties().SetOrientation(30)

    def selectionCallback(self, caller, event):
        if self.coord is None: return

        annSel = self.annotationLink.GetCurrentSelection()
        if annSel.GetNumberOfNodes() > 0:
            idxArr = annSel.GetNode(0).GetSelectionList()
            if idxArr.GetNumberOfTuples() > 0:
                self.coord.unregister(self)
                self.coord.notifyModules(VN.vtk_to_numpy(idxArr))
                self.coord.register(self)
Exemplo n.º 5
0
class ModelmapViewer(module_template.Viewer):
    """Uses vtk to display the model in 3D as an isosurface or a slice. This is
    not a widget but contains one, accessible with get_widget()"""
    def __init__(self, parent=None):
        super(ModelmapViewer, self).__init__(parent)

        self._surface_algorithm = None
        self._surface_actor = None
        self._volume_scalars = None
        self._volume = None
        self._surface_level = 0.5
        self._color = (0.2, 0.8, 0.2)
        self._planes = []
        self._volume_max = 0.
        self._volume_numpy = None

        self._vtk_widget = QVTKRenderWindowInteractor(
            self._widget)  # _vtk_widget is actually the RenderWindowInteractor
        self._vtk_widget.SetInteractorStyle(
            vtk.vtkInteractorStyleRubberBandPick())
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self._vtk_widget)

        self._widget.setLayout(layout)
        #self._vtk_widget.Initialize()
        #self._vtk_widget.Start()

        self._renderer = vtk.vtkRenderer()
        self._renderer.SetDraw(0)
        self._vtk_render_window = self._vtk_widget.GetRenderWindow()
        self._vtk_render_window.AddRenderer(self._renderer)
        #self._renderer = self._vtk_widget.GetRenderWindow().GetRenderer()
        self._lut = vtk_tools.get_lookup_table(0.,
                                               1.,
                                               log=False,
                                               colorscale="jet")

        self._create_volume_map()
        #self._setup_slices()
        #self._setup_surface()

        white = (1., 1., 1.)
        self._renderer.SetBackground(white)
        #self.set_view_type(VIEW_TYPE.slice)
        #self._vtk_widget.GetRenderWindow().Render()

    def initialize(self):
        super(ModelmapViewer, self).initialize()
        self._vtk_widget.Initialize()
        self._setup_slices()
        self._setup_surface()
        #self.set_view_type(VIEW_TYPE.surface)
        self.set_view_type(VIEW_TYPE.slice)
        #self._vtk_widget.GetRenderWindow().Render()
        self._renderer.ResetCamera()
        # camera = self._renderer.GetActiveCamera()
        # camera.SetPosition(2., 2., 2.)
        # camera.SetFocalPoint(0., 0., 0.)
        self._vtk_render_window.Render()
        # print self._renderer.GetVolumes()
        # print self._renderer.VisibleActorCount()
        # print self._surface_actor.GetBounds()
        # print self._renderer.GetActiveCamera().GetPosition()

    def set_active(self, state):
        super(ModelmapViewer, self).set_active(state)
        self._renderer.SetDraw(int(state))

    def _create_volume_map(self):
        """Create the vtk objects containing the data."""
        self._volume_max = 1.

        self._volume = vtk.vtkImageData()
        default_side = 100
        self._volume.SetExtent(0, default_side - 1, 0, default_side - 1, 0,
                               default_side - 1)

        self._volume_numpy = numpy.zeros((default_side, ) * 3,
                                         dtype="float32",
                                         order="C")
        self._volume_numpy[:] = 0.
        self._volume_max = self._volume_numpy.max()
        self._volume_scalars = vtk.vtkFloatArray()
        self._volume_scalars.SetNumberOfValues(default_side**3)
        self._volume_scalars.SetNumberOfComponents(1)
        self._volume_scalars.SetName("Values")
        self._volume_scalars.SetVoidArray(self._volume_numpy, default_side**3,
                                          1)

        self._volume.GetPointData().SetScalars(self._volume_scalars)

    def _setup_surface(self):
        """Create the isosurface object, mapper and actor"""
        self._surface_level = INIT_SURFACE_LEVEL
        self._surface_algorithm = vtk.vtkMarchingCubes()
        if VTK_VERSION < 6:
            self._surface_algorithm.SetInput(self._volume)
        else:
            self._surface_algorithm.SetInputData(self._volume)
        self._surface_algorithm.ComputeNormalsOn()
        self._surface_algorithm.SetValue(0, self._surface_level)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(self._surface_algorithm.GetOutputPort())
        mapper.ScalarVisibilityOff()
        self._surface_actor = vtk.vtkActor()
        self._surface_actor.GetProperty().SetColor(self._color[0],
                                                   self._color[1],
                                                   self._color[2])
        self._surface_actor.SetMapper(mapper)

        self._renderer.AddViewProp(self._surface_actor)

    def _setup_slices(self):
        """Create the slices. No actor required in this case"""
        picker = vtk.vtkCellPicker()
        picker_tolerance = 0.005
        picker.SetTolerance(picker_tolerance)
        text_color = (0., 0., 0.)

        if len(self._planes) != 0:
            raise RuntimeError("planes initialized twice")
        self._planes.append(vtk.vtkImagePlaneWidget())
        if VTK_VERSION < 6:
            self._planes[0].SetInput(self._volume)
        else:
            self._planes[0].SetInputData(self._volume)
        self._planes[0].UserControlledLookupTableOn()
        self._planes[0].SetLookupTable(self._lut)
        self._planes[0].SetPlaneOrientationToXAxes()
        self._planes[0].SetSliceIndex(
            self._volume.GetExtent()[1] /
            2)  # GetExtent returns a six length array, begin-end pairs
        self._planes[0].DisplayTextOn()
        self._planes[0].GetTextProperty().SetColor(text_color)
        self._planes[0].SetPicker(picker)
        self._planes[0].SetLeftButtonAction(1)
        self._planes[0].SetMiddleButtonAction(2)
        self._planes[0].SetRightButtonAction(0)
        self._planes[0].SetInteractor(self._vtk_widget)
        # self._planes[0].On()

        self._planes.append(vtk.vtkImagePlaneWidget())
        if VTK_VERSION < 6:
            self._planes[1].SetInput(self._volume)
        else:
            self._planes[1].SetInputData(self._volume)
        self._planes[1].UserControlledLookupTableOn()
        self._planes[1].SetLookupTable(self._lut)
        self._planes[1].SetPlaneOrientationToZAxes()
        self._planes[1].SetSliceIndex(
            self._volume.GetExtent()[5] /
            2)  # GetExtent returns a six length array, begin-end pairs
        self._planes[1].DisplayTextOn()
        self._planes[1].GetTextProperty().SetColor(text_color)
        self._planes[1].SetPicker(picker)
        self._planes[1].SetLeftButtonAction(1)
        self._planes[1].SetMiddleButtonAction(2)
        self._planes[1].SetRightButtonAction(0)
        self._planes[1].SetInteractor(self._vtk_widget)
        # self._planes[1].On()

    def set_surface_visibility(self, state):
        """Hide or show the surface, used when swithching between the surface and"""
        if state:
            self._surface_actor.SetVisibility(1)
        else:
            self._surface_actor.SetVisibility(0)

    def set_slice_visibility(self, state):
        """Hide or show the slices, used when swithching between the surface and"""
        if state:
            self._planes[0].SetEnabled(1)
            self._planes[1].SetEnabled(1)
        else:
            self._planes[0].SetEnabled(0)
            self._planes[1].SetEnabled(0)

    def set_view_type(self, view_type):
        """Switch between viewing slices or isosurface."""
        if view_type == VIEW_TYPE.surface:
            self.set_slice_visibility(False)
            self.set_surface_visibility(True)
        elif view_type == VIEW_TYPE.slice:
            self.set_surface_visibility(False)
            self.set_slice_visibility(True)

    def _update_surface_level(self):
        """Set the isosurface level based on the relative level in _surface_level
        and the maximum value of the current model."""
        if self._surface_algorithm != None:
            self._surface_algorithm.SetValue(
                0, self._surface_level * self._volume_max)
            self._surface_algorithm.Modified()
            self._vtk_widget.Render()

    def set_surface_level(self, value):
        """Change the relative isosurface level"""
        if value < 0. or value > 1.:
            raise ValueError("Surface value must be in [0.,1.], was %g\n",
                             value)
        self._surface_level = value
        self._update_surface_level()

    def get_surface_level(self):
        """Get the relative isosurface level"""
        return self._surface_level

    def plot_map(self, new_data_array):
        """Update the viwer to show the provided map."""
        if (new_data_array.shape != self._volume_numpy.shape):
            self.plot_map_init(new_data_array)
            return
        self._volume_numpy[:, :, :] = new_data_array
        self._volume_max = new_data_array.max()
        self._lut.SetTableRange(new_data_array.min(), new_data_array.max())
        self._update_surface_level()
        self._volume_scalars.Modified()
        #self._vtk_widget.GetRenderWindow().Render()
        self._vtk_render_window.Render()

    def plot_map_init(self, new_data_array):
        """As opposed to plot_map() this function accepts maps of different side than
        the active one"""
        self._volume_max = new_data_array.max()

        old_extent = numpy.array(self._volume.GetExtent())

        self._volume.SetExtent(0, new_data_array.shape[0] - 1, 0,
                               new_data_array.shape[1] - 1, 0,
                               new_data_array.shape[2] - 1)

        self._volume_numpy = numpy.ascontiguousarray(new_data_array,
                                                     dtype="float32")

        self._volume_scalars = vtk.vtkFloatArray()
        self._volume_scalars.SetNumberOfValues(
            numpy.product(self._volume_numpy.shape))
        self._volume_scalars.SetNumberOfComponents(1)
        self._volume_scalars.SetName("Values")
        self._volume_scalars.SetVoidArray(
            self._volume_numpy, numpy.product(self._volume_numpy.shape), 1)

        self._volume.GetPointData().SetScalars(self._volume_scalars)

        # self._volume_scalars.SetNumberOfValues(new_data_array.shape[0]*new_data_array.shape[1]*new_data_array.shape[2])

        # for i, this_value in enumerate(numpy.ravel(new_data_array.swapaxes(0, 2))):
        #     self._volume_scalars.SetValue(i, this_value)

        self._lut.SetTableRange(new_data_array.min(), new_data_array.max())
        #self._volume.GetPointData().SetScalars(self._volume_scalars)
        self._update_surface_level()
        self._volume_scalars.Modified()
        self._volume.Modified()
        new_extent = numpy.array(self._volume.GetExtent())
        scaling_factors = numpy.float64(new_extent[1::2]) / numpy.float64(
            old_extent[1::2])

        self._planes[0].SetOrigin(
            numpy.array(self._planes[0].GetOrigin() * scaling_factors))
        self._planes[0].SetPoint1(
            numpy.array(self._planes[0].GetPoint1() * scaling_factors))
        self._planes[0].SetPoint2(
            numpy.array(self._planes[0].GetPoint2() * scaling_factors))
        self._planes[1].SetOrigin(
            numpy.array(self._planes[1].GetOrigin() * scaling_factors))
        self._planes[1].SetPoint1(
            numpy.array(self._planes[1].GetPoint1() * scaling_factors))
        self._planes[1].SetPoint2(
            numpy.array(self._planes[1].GetPoint2() * scaling_factors))
        # self._planes[0].Modified()
        # self._planes[1].Modified()
        self._planes[0].UpdatePlacement()
        self._planes[1].UpdatePlacement()

        self._vtk_widget.Render()
        self._renderer.Render()
Exemplo n.º 6
0
class VTKCanvas(QtGui.QFrame):
    ''' the Qt4 frame that holds the main VTK canvas '''
    def __init__(self, parent, Qt4GUI):
        super(VTKCanvas, self).__init__(parent)
        # dictionary to keep track of tree widget items that correspond to actors/icons - used to handle vtk->Qt4 scene changes
        self.actors_to_tree_widget_items = {}

        # Qt4 GUI that this canvas is associated with
        self.Qt4GUI = Qt4GUI

        # camera perspective type check
        self.camera_perspective = False

        # setup the vtk renderers - one for objects, one for overlay icons/text (which always renders on top)
        self.vtk_renderer = vtk.vtkRenderer()

        # setup the vtk interactor
        self.vtk_interactor = QVTKRenderWindowInteractor(self)

        # setup the vtk render window
        self.vtk_render_window = self.vtk_interactor.GetRenderWindow()
        self.vtk_render_window.AddRenderer(self.vtk_renderer)
        self.vtk_render_window.SetInteractor(self.vtk_interactor)

        #setup the layout of the vtk interactor in Qt
        self.layout = QtGui.QHBoxLayout()
        self.layout.addWidget(self.vtk_interactor)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)

    def setupTimerCallback(self, targetFPS=30):
        # calling this function will setup a timer and callback to continuously render the scene at the target FPS
        self.vtk_interactor.AddObserver('TimerEvent', self.requestUpdate)
        self.vtk_interactor.CreateRepeatingTimer(long(targetFPS))

    def requestUpdate(self, obj, event):
        # request a render update of the scene
        self.vtk_render_window.Render()

    def start(self):
        # setup the vtk background - as default, set to light
        self.vtk_renderer.GradientBackgroundOn()
        self.setBackgroundLight()

        # setup the default camera
        self.camera_perspective = False
        self.defaultPerspectiveCamera()

        # setup a default light kit (simple sun illumination + camera spotlight)
        self.light_kit = vtk.vtkLightKit()
        self.light_kit.MaintainLuminanceOn()
        self.light_kit.AddLightsToRenderer(self.vtk_renderer)

        # add the orientation axes to the bottom left of the canvas
        self.Qt4GUI.addOrientationAxes()

        # setup the default base grid - 1x1km, 10m squares
        self.Qt4GUI.addGrid(['grids', '1 km x 1 km, 10 m'], 1000, 10)

        # startup vtk
        self.vtk_interactor.Initialize()
        self.vtk_interactor.Start()

    def resetCamera(self):
        if self.camera_perspective:
            self.camera_perspective = False
            self.defaultPerspectiveCamera()
        else:
            self.camera_perspective = True
            self.defaultTopDownCamera()

    def defaultPerspectiveCamera(self):
        self.Qt4GUI.camera_perspective_signal.emit(True)
        if not self.camera_perspective:
            self.vtk_renderer.SetActiveCamera(vtk.vtkCamera())
            self.vtk_interactor.SetInteractorStyle(TerrainInteractorStyle())
            self.vtk_renderer.GetActiveCamera().SetViewUp(0, 0, 1)
            self.vtk_renderer.GetActiveCamera().SetPosition(0, 1, 10)
            self.vtk_renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
            self.vtk_renderer.GetActiveCamera().Azimuth(135)
            self.vtk_renderer.GetActiveCamera().Elevation(86)
            self.vtk_renderer.GetActiveCamera().Dolly(0.4)
            self.vtk_renderer.GetActiveCamera().Zoom(1)
            self.vtk_renderer.ResetCameraClippingRange()
            self.camera_perspective = True
            self.vtk_interactor.Render()

    def perspectiveCamera(self):
        self.Qt4GUI.camera_perspective_signal.emit(True)
        if not self.camera_perspective:
            curr_fp = self.vtk_renderer.GetActiveCamera().GetFocalPoint()
            curr_pos = [curr_fp[0], curr_fp[1] + 1, 10]
            curr_fp = [curr_fp[0], curr_fp[1], 0]
            self.vtk_renderer.SetActiveCamera(vtk.vtkCamera())
            self.vtk_interactor.SetInteractorStyle(TerrainInteractorStyle())
            self.vtk_renderer.GetActiveCamera().SetViewUp(0, 0, 1)
            self.vtk_renderer.GetActiveCamera().SetPosition(curr_pos)
            self.vtk_renderer.GetActiveCamera().SetFocalPoint(curr_fp)
            self.vtk_renderer.GetActiveCamera().Azimuth(135)
            self.vtk_renderer.GetActiveCamera().Elevation(86)
            self.vtk_renderer.GetActiveCamera().Dolly(0.4)
            self.vtk_renderer.GetActiveCamera().Zoom(1)
            self.vtk_renderer.ResetCameraClippingRange()
            self.camera_perspective = True
            self.vtk_interactor.Render()

    def defaultTopDownCamera(self):
        self.Qt4GUI.camera_perspective_signal.emit(False)
        if self.camera_perspective:
            self.vtk_renderer.SetActiveCamera(vtk.vtkCamera())
            self.vtk_interactor.SetInteractorStyle(TopDownInteractorStyle())
            self.vtk_renderer.GetActiveCamera().SetViewUp(0, 1, 0)
            self.vtk_renderer.GetActiveCamera().ParallelProjectionOn()
            self.vtk_renderer.GetActiveCamera().SetParallelScale(1000)
            self.vtk_renderer.GetActiveCamera().SetPosition(0, 0, 1e4)
            self.vtk_renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
            self.vtk_renderer.GetActiveCamera().Elevation(0)
            self.vtk_renderer.GetActiveCamera().Azimuth(0)
            self.vtk_renderer.GetActiveCamera().Dolly(0.4)
            self.vtk_renderer.GetActiveCamera().Zoom(100)
            self.vtk_renderer.ResetCameraClippingRange()
            self.camera_perspective = False
            self.vtk_interactor.Render()

    def topDownCamera(self):
        self.Qt4GUI.camera_perspective_signal.emit(False)
        if self.camera_perspective:
            curr_fp = self.vtk_renderer.GetActiveCamera().GetFocalPoint()
            curr_pos = [curr_fp[0], curr_fp[1], 1e4]
            curr_fp = [curr_fp[0], curr_fp[1], 0]
            self.vtk_renderer.SetActiveCamera(vtk.vtkCamera())
            self.vtk_interactor.SetInteractorStyle(TopDownInteractorStyle())
            self.vtk_renderer.GetActiveCamera().SetViewUp(0, 1, 0)
            self.vtk_renderer.GetActiveCamera().ParallelProjectionOn()
            self.vtk_renderer.GetActiveCamera().SetParallelScale(1000)
            self.vtk_renderer.GetActiveCamera().SetPosition(curr_pos)
            self.vtk_renderer.GetActiveCamera().SetFocalPoint(curr_fp)
            self.vtk_renderer.GetActiveCamera().Elevation(0)
            self.vtk_renderer.GetActiveCamera().Azimuth(0)
            self.vtk_renderer.GetActiveCamera().Dolly(0.4)
            self.vtk_renderer.GetActiveCamera().Zoom(100)
            self.vtk_renderer.ResetCameraClippingRange()
            self.camera_perspective = False
            self.vtk_interactor.Render()

    def setBackgroundLight(self):
        self.Qt4GUI.background_light_signal.emit(True)
        self.vtk_renderer.SetBackground2(220.0 / 255, 225.0 / 255, 235.0 / 255)
        self.vtk_renderer.SetBackground(105.0 / 255, 135.0 / 255, 155.0 / 255)
        self.vtk_interactor.Render()

    def setBackgroundDark(self):
        self.Qt4GUI.background_light_signal.emit(False)
        self.vtk_renderer.SetBackground(0.0 / 255, 10.0 / 255, 15.0 / 255)
        self.vtk_renderer.SetBackground2(60.0 / 255, 80.0 / 255, 110.0 / 255)
        self.vtk_interactor.Render()

    def addActorFrameAxes(self, tree_widget):
        frame_axes = Primitives.Axes()
        frame_axes.AxisLabelsOff()
        frame_axes.VisibilityOff()
        self.vtk_renderer.AddActor(frame_axes)
        self.vtk_interactor.Render()
        return frame_axes

    def removeActorFrameAxes(self, actor):
        self.vtk_renderer.RemoveActor(actor)
        self.vtk_interactor.Render()

    def addActor(self, tree_widget, actor):
        self.actors_to_tree_widget_items[actor] = tree_widget
        self.vtk_renderer.AddActor(actor)
        self.vtk_interactor.Render()

    def removeActor(self, actor):
        del self.actors_to_tree_widget_items[actor]
        self.vtk_renderer.RemoveActor(actor)
        self.vtk_interactor.Render()

    def replaceActor(self, remove_actor, tree_widget, actor):
        self.removeActor(remove_actor)
        self.addActor(tree_widget, actor)

    def setActorVisibility(self, actor, visible):
        if visible:
            actor.VisibilityOn()
        else:
            actor.VisibilityOff()
        self.vtk_interactor.Render()

    def setActorScale(self, actor, scale):
        if actor.GetClassName() == "vtkAxesActor":
            actor.SetTotalLength(scale, scale, scale)
        else:
            if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
                # billboards have no scaling
                return
            actor.SetScale(scale)
        self.vtk_interactor.Render()

    def getActorScale(self, actor):
        if actor.GetClassName() == "vtkAxesActor":
            return actor.GetTotalLength()
        else:
            if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
                # billboards have no scaling
                return [1, 1, 1]
            return actor.GetScale()

    def setActorOpacity(self, actor, opacity):
        actor.GetProperty().SetOpacity(opacity)
        self.vtk_interactor.Render()

    def getActorOpacity(self, actor):
        return actor.GetProperty().GetOpacity()

    def setActorPointSize(self, actor, size):
        actor.GetProperty().SetPointSize(size)
        self.vtk_interactor.Render()

    def getActorPointSize(self, actor):
        return actor.GetProperty().GetPointSize()

    def setActorLineWidth(self, actor, width):
        actor.GetProperty().SetLineWidth(width)
        self.vtk_interactor.Render()

    def getActorLineWidth(self, actor):
        return actor.GetProperty().GetLineWidth()

    def setActorToSurface(self, actor):
        if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
            # billboards have no render mode
            return
        actor.GetProperty().EdgeVisibilityOff()
        actor.GetProperty().SetRepresentationToSurface()
        self.vtk_interactor.Render()

    def setActorToWireframe(self, actor):
        if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
            # billboards have no render mode
            return
        actor.GetProperty().EdgeVisibilityOff()
        actor.GetProperty().SetRepresentationToWireframe()
        self.vtk_interactor.Render()

    def setActorToSurfaceEdges(self, actor):
        if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
            # billboards have no render mode
            return
        actor.GetProperty().EdgeVisibilityOn()
        actor.GetProperty().SetRepresentationToSurface()
        self.vtk_interactor.Render()

    def setActorToPoints(self, actor):
        if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
            # billboards have no render mode
            return
        actor.GetProperty().EdgeVisibilityOff()
        actor.GetProperty().SetRepresentationToPoints()
        self.vtk_interactor.Render()

    def getActorRenderMode(self, actor):
        if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
            # billboards have no render mode
            return None, None
        edge = actor.GetProperty().GetEdgeVisibility()
        mode = actor.GetProperty().GetRepresentation()
        return edge, mode

    def getActorColor(self, actor):
        return actor.GetProperty().GetColor()

    def setActorColor(self, actor, r, g, b):
        actor.GetProperty().SetColor(r, g, b)
        self.vtk_interactor.Render()

    def setActorTexture(self, actor, image_path):
        if actor.__class__ == Billboards.TextBillboard:
            # text billboards have no texture
            return
        if image_path[-4:].lower() == '.jpg' or image_path[-4:].lower(
        ) == '.jpeg':
            reader = vtk.vtkJPEGReader()
            reader.SetFileName(image_path)
            reader.Update()
        elif image_path[-4:].lower() == '.png':
            reader = vtk.vtkPNGReader()
            reader.SetFileName(image_path)
            reader.Update()
        texture = vtk.vtkTexture()
        texture.RepeatOn()
        texture.SetInputConnection(reader.GetOutputPort())

        actor.SetTexture(texture)

        # polydata = actor.GetMapper().GetInput()
        # pointdata = polydata.GetPointData()
        # celldata = polydata.GetCellData()
        # numtuples = celldata.GetNumberOfTuples()
        # numpolygons = polydata.GetNumberOfPolys()

        self.vtk_interactor.Render()

    def removeActorTexture(self, actor):
        actor.SetTexture(None)
        self.vtk_interactor.Render()

    def setActorOffset(self, actor, x_offset, y_offset, z_offset):
        if actor.__class__ == Billboards.TextBillboard or actor.__class__ == Billboards.ImageBillboard:
            # billboards are unaffected by offset changes
            pass
        else:
            actor.SetPosition(x_offset, y_offset, z_offset)
            self.vtk_interactor.Render()

    def setActorOrientation(self, actor, roll, pitch, yaw):
        actor.SetOrientation(roll, pitch, yaw)
        self.vtk_interactor.Render()
Exemplo n.º 7
0
class VtkWindow(QtGui.QFrame):
    """
    VtkWindow integrates a QVTKRenderWindowInteractor for Python and Qt. Uses a
    vtkGenericRenderWindowInteractor to handle the interactions.  Use
    GetRenderWindow() to get the vtkRenderWindow.  Create with the
    keyword stereo=1 in order to generate a stereo-capable window.

    The user interface is summarized in vtkInteractorStyle.h:

    - Keypress j / Keypress t: toggle between joystick (position
    sensitive) and trackball (motion sensitive) styles. In joystick
    style, motion occurs continuously as long as a mouse button is
    pressed. In trackball style, motion occurs when the mouse button
    is pressed and the mouse pointer moves.

    - Keypress c / Keypress o: toggle between camera and object
    (actor) modes. In camera mode, mouse events affect the camera
    position and focal point. In object mode, mouse events affect
    the actor that is under the mouse pointer.

    - Button 1: rotate the camera around its focal point (if camera
    mode) or rotate the actor around its origin (if actor mode). The
    rotation is in the direction defined from the center of the
    renderer's viewport towards the mouse position. In joystick mode,
    the magnitude of the rotation is determined by the distance the
    mouse is from the center of the render window.

    - Button 2: pan the camera (if camera mode) or translate the actor
    (if object mode). In joystick mode, the direction of pan or
    translation is from the center of the viewport towards the mouse
    position. In trackball mode, the direction of motion is the
    direction the mouse moves. (Note: with 2-button mice, pan is
    defined as <Shift>-Button 1.)

    - Button 3: zoom the camera (if camera mode) or scale the actor
    (if object mode). Zoom in/increase scale if the mouse position is
    in the top half of the viewport; zoom out/decrease scale if the
    mouse position is in the bottom half. In joystick mode, the amount
    of zoom is controlled by the distance of the mouse pointer from
    the horizontal centerline of the window.

    - Keypress 3: toggle the render window into and out of stereo
    mode.  By default, red-blue stereo pairs are created. Some systems
    support Crystal Eyes LCD stereo glasses; you have to invoke
    SetStereoTypeToCrystalEyes() on the rendering window.  Note: to
    use stereo you also need to pass a stereo=1 keyword argument to
    the constructor.

    - Keypress e: exit the application.

    - Keypress f: fly to the picked point

    - Keypress p: perform a pick operation. The render window interactor
    has an internal instance of vtkCellPicker that it uses to pick.

    - Keypress r: reset the camera view along the current view
    direction. Centers the actors and moves the camera so that all actors
    are visible.

    - Keypress s: modify the representation of all actors so that they
    are surfaces.

    - Keypress u: invoke the user-defined function. Typically, this
    keypress will bring up an interactor that you can type commands in.

    - Keypress w: modify the representation of all actors so that they
    are wireframe.
    """
    def __init__(self, parent=None):
        super(VtkWindow, self).__init__(parent)

        self.parent = parent

        self.outline = False

        self.vl = QtGui.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.vl.addWidget(self.vtkWidget)
        self.setLayout(self.vl)

        self.renderer = vtk.vtkRenderer()

        self.vtkwindow = self.vtkWidget.GetRenderWindow()
        self.vtkwindow.AddRenderer(self.renderer)

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

        self.renderer.GradientBackgroundOn()
        self.renderer.SetBackground(1, 1, 1)
        self.renderer.SetBackground2(0, 0, 1)

        self.interactor.Initialize()

        self.vtkWidget.AddObserver('KeyPressEvent', self.onKeyPress)

    def onKeyPress(self, obj, event):
        """"Define hotkeys. Partially overwriting base functionality of
        QVTKRenderWindowInteractor.
        """
        key = obj.GetKeyCode()
        # logger.log.debug('Key code returned is %s' % (key))
        if key == 'o':
            self.toggleOutline()
        elif key == 'p':
            self.setDisplay('points')
        elif key == 'w':
            self.setDisplay('wireframe')
        elif key == 's':
            self.setDisplay('shaded')
        elif key == 'f':
            self.setShading('flat')
        elif key == 'g':
            self.setShading('gouraud')
        elif key == 'W':
            # FIXME
            # FIXME add dialog for filename
            # FIXME
            self.writeStl('test_writing_STL.stl')
        elif key == 'h':
            self.makeScreenshot()

    def readStl(self, name):
        self.reader = vtk.vtkSTLReader()
        self.reader.SetFileName(str(name))

        logger.log.info('STL file <b><font color=%s>' % (LOGCOLOR) +
                        str(name) + '</b> loaded')

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.reader.GetOutputPort())

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetColor(0, 1, 0.2)  # (R,G,B)
        self.actor.GetProperty().SetLineWidth(2.0)

        # create outline mapper
        self.outl = vtk.vtkOutlineFilter()
        self.outl.SetInputConnection(self.reader.GetOutputPort())
        self.outlineMapper = vtk.vtkPolyDataMapper()
        self.outlineMapper.SetInputConnection(self.outl.GetOutputPort())

        # create outline actor
        self.outlineActor = vtk.vtkActor()
        self.outlineActor.SetMapper(self.outlineMapper)

        self.renderer.AddActor(self.actor)
        self.renderer.ResetCamera()

        self.setDisplay('shaded')
        self.setShading('gouraud')

        # set tab to VTK window after loading an STL file
        ntabs = self.parent.centralwidget.tabs.count()
        self.parent.centralwidget.tabs.setCurrentIndex(ntabs - 1)

    def writeStl(self, name):
        # Write the stl file to disk
        self.writer = vtk.vtkSTLWriter()
        self.writer.SetFileName(name)
        # self.writer.SetFileTypeToASCII()
        self.writer.SetFileTypeToBinary()
        self.writer.SetInputConnection(self.reader.GetOutputPort())
        self.writer.Write()

    def setShading(self, style):
        if style.lower() == 'flat':
            self.actor.GetProperty().SetInterpolationToFlat()
        if style.lower() == 'gouraud':
            self.actor.GetProperty().SetInterpolationToGouraud()
        if style.lower() == 'phong':
            self.actor.GetProperty().SetInterpolationToPhong()

    def setDisplay(self, style):
        if style.lower() == 'points':
            self.actor.GetProperty().SetRepresentationToPoints()
        if style.lower() == 'wireframe':
            self.actor.GetProperty().SetRepresentationToWireframe()
        if style.lower() == 'shaded':
            self.actor.GetProperty().SetRepresentationToSurface()

    def edgesOn(self):
        self.actor.GetProperty().EdgeVisibilityOn()

    def toggleOutline(self):
        self.outline = not self.outline
        if self.outline:
            self.renderer.AddActor(self.outlineActor)
        else:
            self.renderer.RemoveActor(self.outlineActor)

        # redraw everything
        self.vtkWidget.Render()

    def makeScreenshot(self):
        w2if = vtk.vtkWindowToImageFilter()
        w2if.SetInput(self.vtkwindow)
        w2if.Update()

        title = PyAero.__appname__ + ' - Message'
        dlg = QtGui.QInputDialog(self)
        dlg.resize(400, 200)
        dlg.setWindowTitle(title)
        dlg.setInputMode(QtGui.QInputDialog.TextInput)
        dlg.setLabelText('Enter screenshot name (*.png):')
        dlg.exec_()
        if not dlg.result():
            return

        fname = str(dlg.textValue())
        if not fname.endswith('.png'):
            fname = fname + '.png'

        writer = vtk.vtkPNGWriter()
        writer.SetFileName(fname)
        writer.SetInputData(w2if.GetOutput())
        writer.Write()

        text = 'Screenshot <b>%s</b> generated in current folder.' % (fname)
        msgbox = QtGui.QMessageBox()
        msgbox.setWindowTitle(title)
        msgbox.setText(text)
        msgbox.exec_()

        logger.log.info(text)
Exemplo n.º 8
0
class RenderWidget(QWidget):
    """
	RenderWidget for rendering volumes. It has a few render types which can be
	set and adjusted.
	"""

    dataChanged = Signal()
    updated = Signal()

    def __init__(self):
        super(RenderWidget, self).__init__()

        # Default volume renderer
        self.renderer = vtkRenderer()
        self.renderer.SetBackground2(0.4, 0.4, 0.4)
        self.renderer.SetBackground(0.1, 0.1, 0.1)
        self.renderer.SetGradientBackground(True)
        self.renderer.SetLayer(0)

        # Overlay renderer which is synced with the default renderer
        self.rendererOverlay = vtkRenderer()
        self.rendererOverlay.SetLayer(1)
        self.rendererOverlay.SetInteractive(0)
        self.renderer.GetActiveCamera().AddObserver("ModifiedEvent",
                                                    self._syncCameras)

        self.rwi = QVTKRenderWindowInteractor(parent=self)
        self.rwi.SetInteractorStyle(vtkInteractorStyleTrackballCamera())
        self.rwi.GetRenderWindow().AddRenderer(self.renderer)
        self.rwi.GetRenderWindow().AddRenderer(self.rendererOverlay)
        self.rwi.GetRenderWindow().SetNumberOfLayers(2)
        self.rwi.SetDesiredUpdateRate(0)

        self.imagePlaneWidgets = [vtkImagePlaneWidget() for i in range(3)]
        for index in range(3):
            self.imagePlaneWidgets[index].DisplayTextOn()
            self.imagePlaneWidgets[index].SetInteractor(self.rwi)
            # Disable the margin for free rotation
            self.imagePlaneWidgets[index].SetMarginSizeX(0.0)
            self.imagePlaneWidgets[index].SetMarginSizeY(0.0)

        self.mapper = vtkOpenGLGPUVolumeRayCastMapper()
        self.mapper.SetAutoAdjustSampleDistances(1)
        self.volume = None
        self.imageData = None
        self.VolumeVisualization = None
        self.shouldResetCamera = False
        self.gridItems = []
        self.orientationGridItems = []

        self.clippingBox = ClippingBox()
        self.clippingBox.setWidget(self)

        # Keep track of the base and user transforms
        self.baseTransform = vtkTransform()
        self.userTransform = vtkTransform()

        self.setMinimumWidth(340)
        self.setMinimumHeight(340)

        layout = QGridLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.rwi, 0, 0)
        self.setLayout(layout)

    def render(self):
        self.clippingBox.update()
        if self.shouldResetCamera:
            self.renderer.ResetCamera()
            self.shouldResetCamera = False
        self.rwi.Render()
        # Prevent warning messages on OSX by not asking to render
        # when the render window has never rendered before
        if not self.rwi.GetRenderWindow().GetNeverRendered():
            self.rwi.GetRenderWindow().Render()

    @Slot(object)
    def setData(self, imageData):
        """
		Updates the image data. If the image data is none, then
		the volume gets removed from the renderer. Otherwise, the
		new image data is given to the mapper.
		"""
        self.imageData = imageData
        # Clean up the data grid
        self._cleanUpGrids()

        if self.imageData is None:
            if self.volume is not None:
                self.renderer.RemoveViewProp(self.volume)
            print "Warning: image data is None"
            self.clippingBox.setImageData(None)
            self.mapper.RemoveAllInputs()
            self.render()
            return

        # Set the image data for the mapper
        self.mapper.SetInputData(self.imageData)

        # Set the image data for the slices
        for index in range(3):
            self.imagePlaneWidgets[index].SetInputData(self.imageData)
            self.imagePlaneWidgets[index].SetPlaneOrientation(index)

        self._createGrid()
        self._createOrientationGrid()
        self.clippingBox.setImageData(self.imageData)
        self.clippingBox.resetClippingBox()
        self.shouldResetCamera = True
        # Don't call render, because camera should only be reset
        # when a volume property is loaded

    def showClippingBox(self, show):
        self.clippingBox.showClippingBox(show)
        self.render()

    def showClippingPlanes(self, show):
        self.clippingBox.showClippingPlanes(show)
        self.render()

    def resetClippingBox(self):
        self.clippingBox.resetClippingBox()
        self.render()

    @Slot(object)
    def setVolumeVisualization(self, volumeVisualization):
        """
		Updates the volume property. It actually removes the volume,
		creates a new volume and sets the updated volume property and
		then adds the new volume to the renderer.
		Just updating the vtkVolumeProperty gives artifacts and seems
		to not work correctly.
		:type volumeVisualization: volumeVisualization
		"""
        self.volumeVisualization = volumeVisualization

        if self.imageData is None or self.volumeVisualization is None:
            if self.volume is not None:
                self.renderer.RemoveViewProp(self.volume)
                self.volume = None
            return

        if self.volume is None:
            self.volume = vtkVolume()
            self.renderer.AddViewProp(self.volume)

        self.volumeVisualization.setMapper(self.mapper)
        self.mapper.SetShaderType(self.volumeVisualization.shaderType())
        if self.volume.GetProperty() != self.volumeVisualization.volProp:
            self.volume.SetProperty(self.volumeVisualization.volProp)
        if self.volume.GetMapper() != self.mapper:
            self.volume.SetMapper(self.mapper)

        self.render()

    @Slot(object)
    def setSlices(self, slices):
        for sliceIndex in range(len(slices)):
            if slices[sliceIndex]:
                self.imagePlaneWidgets[sliceIndex].On()
            else:
                self.imagePlaneWidgets[sliceIndex].Off()

    @Slot(object)
    def transformationsUpdated(self, transformations):
        """
		Get the scaling transform from the transformations and apply
		it to the volume and to the grid that shows the bounds of the
		volume.

		At the moment it is deprecated. It makes more trouble than that
		it solves any real (user) problem...
		"""
        # transform = transformations.scalingTransform()
        # if self.volume:
        # 	self.volume.SetUserTransform(transform)
        # for item in self.gridItems:
        # 	item.SetUserTransform(transform)
        # self.clippingBox.setTransform(transform)
        pass

    def _syncCameras(self, camera, ev):
        """
		Camera modified event callback. Copies the parameters of
		the renderer camera into the camera of the overlay so they
		stay synced at all times.
		"""
        self.rendererOverlay.GetActiveCamera().ShallowCopy(camera)

    def _createGrid(self):
        """
		Create a grid that shows the bounds of the dataset.
		These parts need to be updated when the user is transformed.
		"""
        bounds = self.imageData.GetBounds()
        self.gridItems = CreateBounds(bounds)
        for item in self.gridItems:
            self.renderer.AddViewProp(item)

    def _createOrientationGrid(self):
        """
		Create 3 axis that show the location / coords in 3D space.
		"""
        bounds = self.imageData.GetBounds()
        self.orientationGridItems = CreateOrientationGrid(
            bounds, self.renderer.GetActiveCamera())
        for item in self.orientationGridItems:
            self.renderer.AddViewProp(item)

    def _cleanUpGrids(self):
        for item in self.gridItems:
            self.renderer.RemoveViewProp(item)
        for item in self.orientationGridItems:
            self.renderer.RemoveViewProp(item)
        self.gridItems = []
        self.orientationGridItems = []
Exemplo n.º 9
0
class MeshViewer(QtGui.QWidget):

    app = QtGui.QApplication(sys.argv)
    
    """
    Qt GUI for visu. the output
    """
    def __init__(self, truss, algo): 
        QtGui.QWidget.__init__(self) 
        
        self.truss = truss
        self.algo = algo
        self.algo.dhook = self
        
        self.running = 'init'
        
        print "starting MeshViewer init..."
        
        self.__setupGUI()
        self.__setupVTK()
        
        self.app.lastWindowClosed.connect(self.app.quit)
        self.show() 
        print "MeshViewer ready." 
        
    def closeEvent(self, event):
        self.algo.stopit=True 
        self.running='running' # sort de "while self.running=='pause'"      
        print "GUI killed!"
        QtGui.QWidget.closeEvent(self,event)


    def start(self):
        self.app.exec_()

    def __setupGUI(self):

        self.setWindowTitle("MeshViewer")
        self.resize(800, 600)
        
        # vtk window
        
        self.vtkwidget = QVTKRenderWindowInteractor(self) # "self" sinon, rien ne s'affiche
        self.vtkwidget.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, 
                                                  QtGui.QSizePolicy.Expanding))
        self.vtkwidget.setMinimumSize(QtCore.QSize(300, 300));
        self.vtkwidget.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        
                      
        self.vtkwidget.Initialize() 
                       
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)     
        self.vtkwidget.GetRenderWindow().AddRenderer(self.renderer) 
        
        style = vtk.vtkInteractorStyleTrackballCamera()
        self.vtkwidget.SetInteractorStyle(style) 


        hbox = QtGui.QHBoxLayout()
        self.setLayout(hbox)
        hbox.addWidget(self.vtkwidget)
        
        pan = QtGui.QFrame()
        pan.setMaximumSize(QtCore.QSize(200,999999))
        hbox.addWidget(pan)
        
        vbox = QtGui.QVBoxLayout()
        pan.setLayout(vbox)
        
        self.startBut = QtGui.QPushButton(self.tr("start!"))
        self.connect(self.startBut, QtCore.SIGNAL("clicked()"), self.startSlot)
        vbox.addWidget(self.startBut)
        
        groupBox = QtGui.QGroupBox("Infos")
        self.steplabel = QtGui.QLabel("step # 0")
        self.loadlabel = QtGui.QLabel("lambda = %2.8f" % 0)
        gbox = QtGui.QVBoxLayout()
        groupBox.setLayout(gbox) 
        gbox.addWidget(self.steplabel)   
        gbox.addWidget(self.loadlabel)   
        vbox.addWidget(groupBox)
        
        vbox.addStretch(1)
        
    def startSlot(self):
        if self.running=='init':  
            self.startBut.setText('Pause') # on demarre et on affiche "pause"
            self.running='running'
            self.algo.run()
            self.startBut.setText("Quit")
            self.running='quit'
        elif self.running=='running':  # on stoppe et on affiche 'continue"
            self.running='pause'
            self.startBut.setText("Continue")
            while self.running=='pause':
                self.app.processEvents(QtCore.QEventLoop.WaitForMoreEvents)
        elif self.running=='pause':
            self.running='running'
            self.startBut.setText("Pause")
        elif self.running=='quit':
            self.app.quit()
        
    def disableStart(self):
        self.startBut.setDisabled(True)
        
    def __setupVTK(self):
        # polydata
        self.__createPolyData()
        self.poly = PolyData(self.polydata)
        self.renderer.AddActor(self.poly.actor)
        self.renderer.AddActor2D(self.poly.pointLabels)
        
        self.resetCamera() 

    def resetCamera(self):
        self.renderer.ResetCamera()
        cam1 = self.renderer.GetActiveCamera()
        # 3D
        if 0:
            cam1.Elevation(35)
            cam1.SetViewUp(0, 1, 0)
            cam1.Azimuth(30)
        #2D
        else:
            cam1.Elevation(0)
            cam1.SetViewUp(0, 1, 0)
            cam1.Azimuth(0)
            self.renderer.ResetCameraClippingRange()        
        
    def display(self, step, lamda):
        
        self.steplabel.setText("step # %d" % step)
        self.loadlabel.setText("lambda = %2.8f" % lamda)
        
        self.points.Reset()
        self.vertices.Reset()
        self.lines.Reset()
        self.scalars.Reset()
        
        # points
        nmap={}
        i=0
        for nod in self.truss.nodes:
            nmap[nod.nb]=i
            self.points.InsertPoint(i, nod.x, nod.y, 0.0)
            self.scalars.InsertNextValue(nod.nb)
            # node cells
            vertex = vtk.vtkVertex()
            vertex.GetPointIds().SetId(0, i)
            self.vertices.InsertNextCell(vertex)
            i+=1
        self.points.Modified()
        self.vertices.Modified()
        
        for bar in self.truss.bars:
            line = vtk.vtkLine()
            ids = line.GetPointIds()
            ids.SetNumberOfIds(2)
            for j in range(len(bar.nodes)):
                ids.SetId(j, nmap[bar.nodes[j].nb])
            self.lines.InsertNextCell(line) 
        self.lines.Modified()
        
        self.polydata.Modified()
        
        self.render()
    
    def ragequit(self):
        print "rage quit!"
        self.algo.stopit=True
        self.app.quit()
        
    def render(self): 
        # draw the scene
        self.vtkwidget.Render()
        self.app.processEvents()
    
    def refresh(self):
        self.app.processEvents()
        
    def __createPolyData(self):
        print 'creating vtkPolyData...'
        self.points = vtk.vtkPoints()
        self.polydata  = vtk.vtkPolyData()
        self.vertices = vtk.vtkCellArray()
        self.lines = vtk.vtkCellArray()
        
        self.polydata.SetPoints(self.points)
        self.polydata.SetVerts(self.vertices)
        self.polydata.SetLines(self.lines)
        
        # points
        self.scalars = vtk.vtkFloatArray()
        self.scalars.SetNumberOfComponents(1)
        self.polydata.GetPointData().SetScalars(self.scalars)
     
        nmap={}
        i=0
        for nod in self.truss.nodes:
            nmap[nod.nb]=i
            self.points.InsertPoint(i, nod.x, nod.y, 0.0)
            self.scalars.InsertNextValue(nod.nb)
            # node cells
            vertex = vtk.vtkVertex()
            vertex.GetPointIds().SetId(0, i)
            self.vertices.InsertNextCell(vertex)
            i+=1
        self.points.Modified()
        self.vertices.Modified()
        
        for bar in self.truss.bars:
            line = vtk.vtkLine()
            ids = line.GetPointIds()
            ids.SetNumberOfIds(2)
            for j in range(len(bar.nodes)):
                ids.SetId(j, nmap[bar.nodes[j].nb])
            self.lines.InsertNextCell(line) 
        self.lines.Modified()