Пример #1
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebStartupRemoteConnection(
                _FileOpener.dsHost, _FileOpener.dsPort, _FileOpener.rsHost,
                _FileOpener.rsPort))
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebFileListing(_FileOpener.pathToList,
                                                "Home"))
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebViewPortImageDelivery())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebTimeHandler())

        # Update authentication key to use
        self.updateSecret(_FileOpener.authKey)

        # Create default pipeline
        if _FileOpener.fileToLoad:
            _FileOpener.reader = simple.OpenDataFile(_FileOpener.fileToLoad)
            simple.Show()

            _FileOpener.view = simple.Render()
            _FileOpener.view.ViewSize = [800, 800]
            # If this is running on a Mac DO NOT use Offscreen Rendering
            #view.UseOffscreenRendering = 1
            simple.ResetCamera()
        else:
            _FileOpener.view = simple.GetRenderView()
            simple.Render()
            _FileOpener.view.ViewSize = [800, 800]
        simple.SetActiveView(_FileOpener.view)
Пример #2
0
def customStartupProcessing(files):
    rv = simple.Render()
    rv.ResetCamera()
    rv.Background = [0.0, 0.0, 0.0]
    simple.Render()

    gior = simple.GenericIOReader(FileName=files)

    gior.xAxis = 'x'
    gior.yAxis = 'y'
    gior.zAxis = 'z'
    gior.PointArrayStatus = ['vx', 'vy', 'vz', 'id', 'fof_halo_tag']

    gior_rep = simple.Show(gior)
    gior_rep.SetRepresentationType('Outline')
    simple.Render()

    gior_rep.ColorArrayName = 'id'
    tag_array = gior.PointData.GetArray('id')
    simple.AssignLookupTable(tag_array, 'erdc_rainbow_bright')

    calc = simple.Calculator()
    calc.Function = 'iHat*vx + jHat*vy + kHat*vz'
    calc.ResultArrayName = 'velocity'

    simple.Render()

    calc_rep = simple.Show(calc)
    calc_rep.ColorArrayName = 'velocity'
    vel_array = calc.PointData.GetArray('velocity')
    simple.AssignLookupTable(vel_array, 'Cool to Warm')

    rv.ResetCamera()
    simple.Render()
Пример #3
0
    def setDrawMode(self, choice, **kwargs):
        """ helper for Color tracks so that they can cause ParaView to
        render in the right mode."""
        if choice == 'color':
            self.view.StopCaptureValues()
            if self.UsingGL2:
                self.view.StopCaptureLuminance()
            self.CaptureDepth = False
            self.CaptureLuminance = False
            self.CaptureValues = False
        if choice == 'luminance':
            self.view.StopCaptureValues()
            if self.UsingGL2:
                self.view.StartCaptureLuminance()
            self.CaptureDepth = False
            self.CaptureLuminance = True
            self.CaptureValues = False
        if choice == 'depth':
            self.view.StopCaptureValues()
            if self.UsingGL2:
                self.view.StopCaptureLuminance()
            self.CaptureDepth = True
            self.CaptureLuminance = False
            self.CaptureValues = False
        if choice == 'value':
            if self.UsingGL2:
                self.view.StopCaptureLuminance()

            if self.CaptureValues is not True:
                # this is a workaround for a bug in VTK
                # in valuepass, we need the arrays we will render,
                # but with CompositePolyDataMapper we need to render
                # to find out what arrays are needed
                self.view.StopCaptureValues()
                simple.Render()

            self.view.DrawCells = kwargs['field']
            self.view.ArrayNameToDraw = kwargs['name']
            self.view.ArrayComponentToDraw = kwargs['component']
            self.view.ScalarRange = kwargs['range']

            self.view.StartCaptureValues()
            self.view.SetValueRenderingMode(self.ValueMode)
            # Ensure context support
            if (self.CheckFloatSupport
                    and self.ValueMode == ValueMode().FLOATING_POINT):
                # Force a proxy update to make sure the rendering mode is set
                self.view.UpdateVTKObjects()
                simple.Render()
                self.ValueMode = self.view.GetValueRenderingMode()
                self.CheckFloatSupport = False
                self.store.add_metadata({'value_mode': self.ValueMode})

            self.CaptureDepth = False
            self.CaptureLuminance = False
            self.CaptureValues = True
Пример #4
0
def applyMaterialToRepresentation(filepath):
    view = simple.Render()
    with open(filepath) as json_file:
        props = json.load(json_file)

        for key in props:
            for proxy in proxyMapping[str(key)]:
                simple.Show(proxy=proxy, view=view, **props[key])

    simple.Render()
Пример #5
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebStartupRemoteConnection(
                _FileOpener.dsHost, _FileOpener.dsPort, _FileOpener.rsHost,
                _FileOpener.rsPort))
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebFileListing(_FileOpener.pathToList,
                                                "Home"))
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebViewPortImageDelivery())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebTimeHandler())

        # Update authentication key to use
        self.updateSecret(_FileOpener.authKey)

        # Create default pipeline
        if _FileOpener.fileToLoad:
            _FileOpener.reader = simple.OpenDataFile(_FileOpener.fileToLoad)
            simple.Show()

            _FileOpener.view = simple.Render()
            _FileOpener.view.ViewSize = [800, 800]
            # If this is running on a Mac DO NOT use Offscreen Rendering
            #view.UseOffscreenRendering = 1
            simple.ResetCamera()
        else:
            _FileOpener.view = simple.GetRenderView()
            simple.Render()
            _FileOpener.view.ViewSize = [800, 800]

            # test to prove server's working
            # independently from the web components
            #c = simple.Cone()
            #c.Resolution = 128
            #simple.Hide(c)
            #p = simple.ProcessIdScalars()
            #r = simple.Show(p)
            #a = p.PointData.GetArray('ProcessId')
            #r.ColorArrayName = 'ProcessId'
            #simple.AssignLookupTable(a,'Cool to Warm')
            #simple.Render()
            #simple.SaveScreenshot('/usr/common/graphics/ParaView/4.2.0-PDACS/data/test.png')

        simple.SetActiveView(_FileOpener.view)
def createTemporalTransformsAxes(source="default", renderView="default"):
    """ Display orientation part of a TemporalTransforms

    Allow visualizing the orientations part of the TemporalTransforms by
    displaying the x, y and z unitary vector of the sensor reference frame.

    The source must provide transforms, for example it could be:
    a TemporalTransformReader, or the trajectory output of Lidar SLAM

    ParaView pipeline elements are created. These elements can be deleted
    using function deleteAllTemporalTransformsAxes().
    """
    # GetActiveSource() and GetRenderView() do not work if used as default
    # parameter value, so they are called here if needs be:
    if source == "default":
        source = smp.GetActiveSource()
    if renderView == "default":
        renderView = smp.GetRenderView()
    smp.SetActiveSource(source)  # maybe useless
    calculatorX = setupCalculator(source, "RX", [1.0, 0.0, 0.0], fx,
                                  renderView)
    calculatorY = setupCalculator(source, "RY", [0.0, 1.0, 0.0], fy,
                                  renderView)
    calculatorZ = setupCalculator(source, "RZ", [0.0, 0.0, 1.0], fz,
                                  renderView)
    smp.Render()
Пример #7
0
def tick(self):
	""" function called at each timestep """
	view = smp.GetActiveView()

	# lidar orientation and position
	R_l = self.orientations[self.i]
	T_l = self.pts[self.i, :]

	# move camera
	for c in self.cameras:
		if c.timestep_inside_range(self.i):
			print c.type
			view.CameraPosition = c.interpolate_position(self.i, R_l, T_l, np.asarray(list(view.CameraPosition)))
			view.CameraFocalPoint = c.interpolate_focal_point(self.i, R_l, T_l)
			view.CameraViewUp = c.interpolate_up_vector(self.i, R_l)
			break

	# move 3d model (vtk Transform rotation are angle axis in degrees)
	if self.model is not None:
		self.model.Transform.Translate = self.pts[self.i, :3]
		o = R_l.as_rotvec()
		angle_rad = np.linalg.norm(o)
		angle_deg = np.rad2deg(angle_rad)
		self.model.Transform.Rotate = o * angle_deg / angle_rad

	smp.Render()

	# save frame
	if len(frames_output_dir) > 0:
		imageName = os.path.join(frames_output_dir, "image_%04d.png" % (self.image_index))
		smp.WriteImage(imageName)

	self.image_index += 1
	self.i += 1
def test():
    w = simple.Wavelet()

    dataRange = [40.0, 270.0]
    arrayName = ('POINT_DATA', 'RTData')
    fileGenerator = FileNameGenerator(
        '/tmp/iso', '{contourBy}_{contourValue}_{theta}_{phi}.jpg')

    cExplorer = ContourExplorer(fileGenerator, w, arrayName, dataRange, 25)
    proxy = cExplorer.getContour()
    rep = simple.Show(proxy)

    lut = simple.GetLookupTableForArray("RTData",
                                        1,
                                        RGBPoints=[
                                            43.34006881713867, 0.23, 0.299,
                                            0.754, 160.01158714294434, 0.865,
                                            0.865, 0.865, 276.68310546875,
                                            0.706, 0.016, 0.15
                                        ])
    rep.LookupTable = lut
    rep.ColorArrayName = arrayName
    view = simple.Render()

    exp = ThreeSixtyImageStackExporter(fileGenerator, view, [0, 0, 0], 100,
                                       [0, 0, 1], [30, 45])
    for progress in cExplorer:
        exp.UpdatePipeline()
        print progress
Пример #9
0
    def __init__(self, port, serverHost=None, serverPort=11111):

        self.tcpServer = QtNetwork.QTcpServer()
        if not self.tcpServer.listen(QtNetwork.QHostAddress.Any, port):
            print 'Could not list on port %d' % port
            return
        self.tcpServer.newConnection.connect(self.acceptClient)

        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.render)

        if serverHost:
            pvsimple.Connect(serverHost, serverPort)
        self.createPipeline()

        self.setupManipulators()

        self.widget = \
            QVTKRenderWindowInteractor.QVTKRenderWindowInteractor(\
            rw=self.renderView.GetRenderWindow(),
            iren=self.renderView.GetInteractor())
        self.widget.Initialize()
        self.widget.Start()
        self.widget.show()

        pvsimple.Render(self.renderView)
Пример #10
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebPublishImageDelivery(decode=False))
        self.updateSecret(_DemoServer.authKey)

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Disable interactor-based render calls
        simple.GetRenderView().EnableRenderOnInteraction = 0
        simple.GetRenderView().Background = [0, 0, 0]
        cone = simple.Cone()
        simple.Show(cone)
        simple.Render()

        # Update interaction mode
        pxm = simple.servermanager.ProxyManager()
        interactionProxy = pxm.GetProxy('settings',
                                        'RenderViewInteractionSettings')
        interactionProxy.Camera3DManipulators = [
            'Rotate', 'Pan', 'Zoom', 'Pan', 'Roll', 'Pan', 'Zoom', 'Rotate',
            'Zoom'
        ]
Пример #11
0
def run(filename=None):
    """Create a dummy pipeline and save the coprocessing state in the filename
        specified, if any, else dumps it out on stdout."""

    from paraview import simple, servermanager
    simple.LoadDistributedPlugin("CatalystScriptGeneratorPlugin")
    wavelet = simple.Wavelet(registrationName="Wavelet1")
    contour = simple.Contour()
    display = simple.Show()
    view = simple.Render()
    # create a new 'Parallel PolyData Writer'
    parallelPolyDataWriter0 = simple.ParallelPolyDataWriter()

    viewname = servermanager.ProxyManager().GetProxyName("views", view.SMProxy)
    script = DumpPipeline(
        export_rendering=True,
        simulation_input_map={"Wavelet1": "input"},
        screenshot_info={viewname: ['image.png', '1', '1', '2', '400', '400']})
    if filename:
        f = open(filename, "w")
        f.write(script)
        f.close()
    else:
        print "# *** Generated Script Begin ***"
        print script
        print "# *** Generated Script End ***"
Пример #12
0
    def setupApplication(cls):
        """Setups the default application state."""
        # read data directory.

        root = {"name": "ROOT", "dirs": [], "files": []}
        directory_map = {}
        directory_map[_DataProber.DataPath] = root
        for path, dirs, files in os.walk(_DataProber.DataPath):
            element = directory_map[path]

            for name in dirs:
                item = {"name": name, "dirs": [], "files": []}
                item["name"] = name
                directory_map[os.path.join(path, name)] = item
                element["dirs"].append(item)
            element["files"] = []
            for name in files:
                relpath = os.path.relpath(os.path.join(path, name),
                                          _DataProber.DataPath)
                item = {"name": name, "itemValue": relpath}
                element["files"].append(item)
        cls.Database = root
        cls.View = simple.CreateRenderView()
        simple.Render()

        # setup animation scene
        scene = simple.GetAnimationScene()
        simple.GetTimeTrack()
        scene.PlayMode = "Snap To TimeSteps"
 def endSelection(self, area, extract):
     """
     Method used to finalize an interactive selection by providing
     the [ startPointX, startPointY, endPointX, endPointY ] area
     where (0,0) match the lower left corner of the pixel screen.
     """
     if self.active_view:
         self.active_view.InteractionMode = self.previous_interaction
         representations = vtkCollection()
         sources = vtkCollection()
         if self.selection_type == 0:
             self.active_view.SelectSurfacePoints(area, representations, sources, False)
         elif self.selection_type == 1:
             self.active_view.SelectSurfaceCells(area, representations, sources, False)
         elif self.selection_type == 2:
             self.active_view.SelectFrustumPoints(area, representations, sources, False)
         elif self.selection_type == 3:
             self.active_view.SelectFrustumCells(area, representations, sources, False)
         else:
             self.active_view.SelectSurfacePoints(area, representations, sources, False)
         # Don't know what to do if more than one representation/source
         if representations.GetNumberOfItems() == sources.GetNumberOfItems() and sources.GetNumberOfItems() == 1:
             # We are good for selection
             rep = servermanager._getPyProxy(representations.GetItemAsObject(0))
             selection = servermanager._getPyProxy(sources.GetItemAsObject(0))
             if extract:
                 extract = simple.ExtractSelection(Input=rep.Input, Selection=selection)
                 simple.Show(extract)
                 simple.Render()
             else:
                 rep.Input.SMProxy.SetSelectionInput(0, selection.SMProxy, 0)
Пример #14
0
def testUserInput():
    fileName = QtGui.QFileDialog.getOpenFileName(getMainWindow(), 'Open file',)
    if fileName:
        smp.OpenDataFile(fileName, guiName=os.path.basename(fileName))
        smp.Show()
        smp.ResetCamera()
        smp.Render()
Пример #15
0
 def insert(self, document):
     if not self.view:
         return
     if self.CaptureDepth:
         simple.Render()
         image = self.view.CaptureDepthBuffer()
         idata = numpy_support.vtk_to_numpy(image)
         rw = self.view.GetRenderWindow()
         width, height = rw.GetSize()
         try:
             imageslice = idata.reshape(height, width)
         except ValueError:
             imageslice = None
         #import Image
         #img = Image.fromarray(imageslice)
         #img.show()
         #try:
         #    input("Press enter to continue ")
         #except NameError:
         #    pass
         document.data = imageslice
         self.CaptureDepth = False
     else:
         imageslice = None
         if self.CaptureLuminance and not self.UsingGL2:
             try:
                 rep = simple.GetRepresentation()
                 if rep != None:
                     rep.DiffuseColor = [1, 1, 1]
                     rep.ColorArrayName = None
             except ValueError:
                 pass
             image = self.view.CaptureWindow(1)
             ext = image.GetExtent()
             width = ext[1] - ext[0] + 1
             height = ext[3] - ext[2] + 1
             imagescalars = image.GetPointData().GetScalars()
             idata = numpy_support.vtk_to_numpy(imagescalars)
             idata = self.rgb2grey(idata, height, width)
             imageslice = np.dstack((idata, idata, idata))
             image.UnRegister(None)
         else:
             image = self.view.CaptureWindow(1)
             ext = image.GetExtent()
             width = ext[1] - ext[0] + 1
             height = ext[3] - ext[2] + 1
             imagescalars = image.GetPointData().GetScalars()
             idata = numpy_support.vtk_to_numpy(imagescalars)
             imageslice = idata.reshape(height, width, 3)
             image.UnRegister(None)
         #import Image
         #img = Image.fromarray(imageslice)
         #img.show()
         #try:
         #    input("Press enter to continue ")
         #except NameError:
         #    pass
         document.data = imageslice
     if self.iSave:
         super(ImageExplorer, self).insert(document)
Пример #16
0
    def initialize(self):
        from paraview import simple
        from paraview.web import protocols as pv_protocols

        # Make sure ParaView is initialized
        if not simple.servermanager.ActiveConnection:
            simple.Connect()

        if not IPythonProtocol.producer:
            IPythonProtocol.producer = simple.DistributedTrivialProducer()
            IPythonProtocol.ActivateDataSet('iPython-demo')
            simple.Show(IPythonProtocol.producer)
            simple.Render()

        # Bring used components
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebFileListing(IPythonProtocol.dataDir, "Home", IPythonProtocol.excludeRegex, IPythonProtocol.groupRegex))
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebPipelineManager(IPythonProtocol.dataDir, IPythonProtocol.fileToLoad))
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPortImageDelivery())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebTimeHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebRemoteConnection())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebFileManager(IPythonProtocol.dataDir))

        # Update authentication key to use
        self.updateSecret(IPythonProtocol.authKey)
Пример #17
0
    def processFile(self):
        self._download_mesh_file()

        reader = simple.OpenDataFile(_MeshViewer.meshFile)
        reader.UpdatePipeline()
        self.outline = simple.Show(reader)
        self.outline.Representation = 'Outline'

        # Get information about cell data arrays
        nbFaces = 0
        cdInfo = reader.GetCellDataInformation()
        numberOfCellArrays = cdInfo.GetNumberOfArrays()
        for idx in xrange(numberOfCellArrays):
            array = cdInfo.GetArray(idx)
            if array.GetName() != 'modelfaceids':
                continue
            nbFaces = int(array.GetRange(-1)[1])

        # Extract each face and keep representation around
        _MeshViewer.faces = []
        for idx in range(nbFaces):
            threshold = simple.Threshold(Scalars=['CELLS', 'modelfaceids'],
                                         Input=reader,
                                         ThresholdRange=[idx, idx])
            rep = simple.Show(threshold)
            _MeshViewer.faces.append(rep)

        self.view = simple.Render()
        self.view.Background = [0, 0, 0]
Пример #18
0
    def updateDisplayProperty(self, options):
        proxy = helper.idToProxy(options['proxy_id'])
        rep = simple.GetDisplayProperties(proxy)
        helper.updateProxyProperties(rep, options)

        # Try to bind the proper lookup table if need be
        if options.has_key('ColorArrayName') and len(
                options['ColorArrayName']) > 0:
            name = options['ColorArrayName']
            type = options['ColorAttributeType']
            nbComp = 1

            if type == 'POINT_DATA':
                data = rep.GetRepresentedDataInformation(
                ).GetPointDataInformation()
                for i in range(data.GetNumberOfArrays()):
                    array = data.GetArrayInformation(i)
                    if array.GetName() == name:
                        nbComp = array.GetNumberOfComponents()
            elif type == 'CELL_DATA':
                data = rep.GetRepresentedDataInformation(
                ).GetCellDataInformation()
                for i in range(data.GetNumberOfArrays()):
                    array = data.GetArrayInformation(i)
                    if array.GetName() == name:
                        nbComp = array.GetNumberOfComponents()
            lut = self.lutManager.getLookupTable(name, nbComp)
            rep.LookupTable = lut

        simple.Render()
Пример #19
0
    def toggleEdges(self):
        if self.rep.Representation == 'Surface':
            self.rep.Representation = 'Surface With Edges'
        else:
            self.rep.Representation = 'Surface'

        simple.Render()
Пример #20
0
    def openRelativeFile(self, relativePath):
        fileToLoad = []
        if type(relativePath) == list:
            for file in relativePath:
                fileToLoad.append(os.path.join(self.baseDir, file))
        else:
            fileToLoad.append(os.path.join(self.baseDir, relativePath))

        reader = simple.OpenDataFile(fileToLoad)
        name = fileToLoad[0].split("/")[-1]
        if len(name) > 15:
            name = name[:15] + '*'
        simple.RenameSource(name, reader)
        simple.Show()
        simple.Render()
        simple.ResetCamera()

        # Add node to pipeline
        self.pipeline.addNode('0', reader.GetGlobalIDAsString())

        # Create LUT if need be
        self.lutManager.registerFieldData(reader.GetPointDataInformation())
        self.lutManager.registerFieldData(reader.GetCellDataInformation())

        return helper.getProxyAsPipelineNode(reader.GetGlobalIDAsString(),
                                             self.lutManager)
Пример #21
0
    def loadData(self):
        global dataPath
        mainpath = os.path.join(dataPath, "main")

        if os.path.isdir(mainpath):
            files = os.listdir(mainpath)
            for file in files:
                fullpath = os.path.join(mainpath, file)
                if os.path.isfile(fullpath):
                    self.srcObj = simple.OpenDataFile(fullpath)
                    simple.SetActiveSource(self.srcObj)
                    self.rep = simple.GetDisplayProperties()
                    simple.Hide()

                    print 'Loaded %s into scene' % fullpath
        else:
            print 'Error: ' + mainpath + ' does not exist\n'
            raise Exception("The main directory does not exist")

        surfacespath = os.path.join(dataPath, "surfaces")
        files = os.listdir(surfacespath)
        for file in files:
            fullpath = os.path.join(surfacespath, file)
            if os.path.isfile(fullpath):
                self._loadSurfaceWithProperties(fullpath)

        simple.SetActiveSource(self.srcObj)
        simple.ResetCamera()
        simple.Render()
Пример #22
0
    def addSource(self, algo_name, parent):
        pid = str(parent)
        parentProxy = helper.idToProxy(parent)
        if parentProxy:
            simple.SetActiveSource(parentProxy)
        else:
            pid = '0'

        # Create new source/filter
        cmdLine = 'simple.' + algo_name + '()'
        newProxy = eval(cmdLine)

        # Create its representation and render
        simple.Show()
        simple.Render()
        simple.ResetCamera()

        # Add node to pipeline
        self.pipeline.addNode(pid, newProxy.GetGlobalIDAsString())

        # Handle domains
        helper.apply_domains(parentProxy, newProxy.GetGlobalIDAsString())

        # Create LUT if need be
        if pid == '0':
            self.lutManager.registerFieldData(
                newProxy.GetPointDataInformation())
            self.lutManager.registerFieldData(
                newProxy.GetCellDataInformation())

        # Return the newly created proxy pipeline node
        return helper.getProxyAsPipelineNode(newProxy.GetGlobalIDAsString(),
                                             self.lutManager)
Пример #23
0
def loadScene(objFilePath, mtlFilePath):
    mtlReader = MTLParser(mtlFilePath)
    mtlReader.reduceMaterialDefinitions()

    objReader = OBJParser(objFilePath, 'usemtl')
    meshBaseDirectory = os.path.join(os.path.dirname(objFilePath),
                                     os.path.basename(objFilePath)[:-4])

    # custom remap
    mapToSha = {}
    for key in mtlReader.reducedMaterialMap:
        mapToSha[key] = mtlReader.reducedMaterialMap[nameRemap(key)]

    meshMapping = writeMeshes(meshBaseDirectory, objReader, mapToSha)
    for name in meshMapping:
        source = simple.OpenDataFile(meshMapping[name], guiName=name)
        rep = simple.Show(source)
        mtlReader.applyMaterialToRepresentation(name, rep)

    with open('%s/representations.json' % meshBaseDirectory,
              "w",
              encoding="utf-8") as text_file:
        text_file.write(
            json.dumps(mtlReader.representationsParameters,
                       indent=2,
                       sort_keys=True))

    simple.Render()
    def UpdatePipeline(self, time=0):
        """
        Probe dataset and dump images to the disk
        """
        self.file_name_generator.update_active_arguments(time=time)
        self.slice.SMProxy.InvokeEvent('UserEvent', 'HideWidget')
        self.view_proxy.CameraParallelProjection = 1
        self.view_proxy.CameraViewUp = self.viewup
        self.view_proxy.CameraFocalPoint = [0, 0, 0]
        self.view_proxy.CameraPosition = self.slice.SliceType.Normal
        self.slice.SliceType.Origin = [
            (self.dataBounds[0] + self.dataBounds[1]) / 2,
            (self.dataBounds[2] + self.dataBounds[3]) / 2,
            (self.dataBounds[4] + self.dataBounds[5]) / 2
        ]
        simple.Render()
        simple.ResetCamera()
        self.view_proxy.CameraParallelScale = self.view_proxy.CameraParallelScale / self.parallelScaleRatio

        for step in range(int(self.number_of_steps)):
            self.slice.SliceType.Origin = [
                self.origin[0] + float(step) * self.origin_inc[0],
                self.origin[1] + float(step) * self.origin_inc[1],
                self.origin[2] + float(step) * self.origin_inc[2]
            ]

            # Loop over each color withour changing geometry
            for name in self.colorByArray:
                # Choose color by
                self.sliceRepresentation.ColorArrayName = (
                    self.colorByArray[name]["type"], name)
                self.sliceRepresentation.LookupTable = self.colorByArray[name][
                    "lut"]
                self.file_name_generator.update_active_arguments(
                    sliceColor=name)

                # Update file name pattern
                self.file_name_generator.update_active_arguments(
                    slicePosition=step)
                simple.Render()
                simple.WriteImage(self.file_name_generator.get_fullpath())

        # Generate metadata
        self.file_name_generator.update_label_arguments(sliceColor="Color by:")
        self.file_name_generator.WriteMetaData()
        self.view_proxy.CameraParallelProjection = 0
 def pushState(self, state):
     for proxy_id in state:
         if proxy_id == 'proxy':
             continue
         proxy = helper.idToProxy(proxy_id);
         helper.updateProxyProperties(proxy, state[proxy_id])
         simple.Render()
     return helper.getProxyAsPipelineNode(state['proxy'], self.lutManager)
Пример #26
0
    def draw(self):

        if self.plotRecipe.get('EnumPlotType') == 'contour':
            self.makeContour()
        else:
            self.makeStream()

        simple.Render()
Пример #27
0
    def processFile(self):
        self._download_mesh_file()
        self.sideVisibility = []
        self.sideNames = []
        self.sideObjectValue = []

        self.reader = simple.OpenDataFile(_MeshViewer.fileName)
        domain = self.reader.GetProperty('SideSetArrayStatus').GetDomain(
            'array_list')
        sides = []

        for i in range(domain.GetNumberOfStrings()):
            sideName = domain.GetString(i)
            self.sideVisibility.append(True)
            self.sideObjectValue.append(int(sideName.split(': ')[1]))
            self.sideNames.append(sideName)
            sides.append(sideName)

        self.reader.SideSetArrayStatus = sides
        self.reader.ElementBlocks = []
        self.reader.UpdatePipeline()

        bounds = self.reader.GetDataInformation().GetBounds()
        box = simple.Box(XLength=(bounds[1] - bounds[0]),
                         YLength=(bounds[3] - bounds[2]),
                         ZLength=(bounds[5] - bounds[4]),
                         Center=[
                             0.5 * (bounds[0] + bounds[1]),
                             0.5 * (bounds[2] + bounds[3]),
                             0.5 * (bounds[4] + bounds[5])
                         ])
        self.outline = simple.Show(box)
        self.outline.Representation = 'Outline'

        # Color/Annotation management
        annotations = []
        self.colors = []

        for i in range(domain.GetNumberOfStrings()):
            annotations.append(str(self.sideObjectValue[i]))
            annotations.append(self.sideNames[i])
            self.colors.append(0.5)
            self.colors.append(0.5)
            self.colors.append(0.5)

        # Color management
        self.lut = simple.GetColorTransferFunction('ObjectId')
        self.lut.InterpretValuesAsCategories = 1
        self.lut.Annotations = annotations
        self.lut.IndexedColors = self.colors

        mainRep = simple.Show(self.reader)
        vtkSMPVRepresentationProxy.SetScalarColoring(mainRep.SMProxy,
                                                     'ObjectId',
                                                     vtkDataObject.CELL)

        self.view = simple.Render()
        self.view.Background = [0, 0, 0]
Пример #28
0
def initView(width, height):
    global view
    view = simple.GetRenderView()
    simple.Render()
    view.ViewSize = [width, height]
    view.Background = [1, 1, 1]
    view.OrientationAxesLabelColor = [0, 0, 0]

    print 'View created successfully (%dx%d)' % (width, height)
Пример #29
0
def animate(fn):
    casefoam = pv.OpenFOAMReader(FileName=fn)
    pv.Show(casefoam)
    dp = pv.GetDisplayProperties(casefoam)
    dp.SetPropertyWithName('ColorArrayName', ['POINTS', 'U'])
    view = pv.GetActiveView()
    reader = pv.GetActiveSource()
    tsteps = reader.TimestepValues
    annTime = pv.AnnotateTimeFilter(reader)
    pv.Show(annTime)
    pv.Render()
    while True:
        try:
            for t in tsteps:
                view.ViewTime = t
                pv.Render()
        except KeyboardInterrupt:
            sys.exit(0)
Пример #30
0
    def changeBgColor(self, rgb):
        global view
        view.Background = rgb

        if (sum(rgb) / 3.0) > 0.5:
            view.OrientationAxesLabelColor = [0, 0, 0]
        else:
            view.OrientationAxesLabelColor = [1, 1, 1]
        simple.Render()