예제 #1
0
def main(argv):
    
    arguments = osg.ArgumentParser( argc, argv )
    usage = arguments.getApplicationUsage()
    usage.setDescription( arguments.getApplicationName() +
                           " is the example which demonstrates how to render high-resolution images (posters).")
    usage.setCommandLineUsage( arguments.getApplicationName() + " [options] scene_file" )
    usage.addCommandLineOption( "-h or --help", "Display this information." )
    usage.addCommandLineOption( "--color <r> <g> <b>", "The background color." )
    usage.addCommandLineOption( "--ext <ext>", "The output tiles' extension (Default: bmp)." )
    usage.addCommandLineOption( "--poster <filename>", "The output poster's name (Default: poster.bmp)." )
    usage.addCommandLineOption( "--tilesize <w> <h>", "Size of each image tile (Default: 640 480)." )
    usage.addCommandLineOption( "--finalsize <w> <h>", "Size of the poster (Default: 6400 4800)." )
    usage.addCommandLineOption( "--enable-output-poster", "Output the final poster file (Default)." )
    usage.addCommandLineOption( "--disable-output-poster", "Don't output the final poster file." )
    #usage.addCommandLineOption( "--enable-output-tiles", "Output all tile files." )
    #usage.addCommandLineOption( "--disable-output-tiles", "Don't output all tile files (Default)." )
    usage.addCommandLineOption( "--use-fb", "Use Frame Buffer for rendering tiles (Default, recommended).")
    usage.addCommandLineOption( "--use-fbo", "Use Frame Buffer Object for rendering tiles.")
    usage.addCommandLineOption( "--use-pbuffer","Use Pixel Buffer for rendering tiles.")
    usage.addCommandLineOption( "--use-pbuffer-rtt","Use Pixel Buffer RTT for rendering tiles.")
    usage.addCommandLineOption( "--inactive", "Inactive capturing mode." )
    usage.addCommandLineOption( "--camera-eye <x> <y> <z>", "Set eye position in inactive mode." )
    usage.addCommandLineOption( "--camera-latlongheight <lat> <lon> <h>", "Set eye position on earth in inactive mode." )
    usage.addCommandLineOption( "--camera-hpr <h> <p> <r>", "Set eye rotation in inactive mode." )
    
    if  arguments.read("-h")  or  arguments.read("--help")  :
        usage.write( std.cout )
        return 1
    
    # Poster arguments
    activeMode = True
    outputPoster = True
    #bool outputTiles = False
    tileWidth = 640, tileHeight = 480
    posterWidth = 640*2, posterHeight = 480*2
    posterName = "poster.bmp", extName = "bmp"
    bgColor = osg.Vec4(0.2, 0.2, 0.6, 1.0)
    renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT
    
    while  arguments.read("--inactive")  :  activeMode = False 
    while  arguments.read("--color", bgColor.r(), bgColor.g(), bgColor.b())  : 
    while  arguments.read("--tilesize", tileWidth, tileHeight)  : 
    while  arguments.read("--finalsize", posterWidth, posterHeight)  : 
    while  arguments.read("--poster", posterName)  : 
    while  arguments.read("--ext", extName)  : 
    while  arguments.read("--enable-output-poster")  :  outputPoster = True 
    while  arguments.read("--disable-output-poster")  :  outputPoster = False 
    #while  arguments.read("--enable-output-tiles")  :  outputTiles = True 
    #while  arguments.read("--disable-output-tiles")  :  outputTiles = False 
    while  arguments.read("--use-fbo") :  renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT 
    while  arguments.read("--use-pbuffer") :  renderImplementation = osg.Camera.PIXEL_BUFFER 
    while  arguments.read("--use-pbuffer-rtt") :  renderImplementation = osg.Camera.PIXEL_BUFFER_RTT 
    while  arguments.read("--use-fb") :  renderImplementation = osg.Camera.FRAME_BUFFER 
    
    # Camera settings for inactive screenshot
    useLatLongHeight = True
    eye = osg.Vec3d()
    latLongHeight = osg.Vec3d( 50.0, 10.0, 2000.0 )
    hpr = osg.Vec3d( 0.0, 0.0, 0.0 )
    if  arguments.read("--camera-eye", eye.x(), eye.y(), eye.z())  :
        useLatLongHeight = False
        activeMode = False
    elif  arguments.read("--camera-latlongheight", latLongHeight.x(), latLongHeight.y(), latLongHeight.z())  :
        activeMode = False
        latLongHeight.x() = osg.DegreesToRadians( latLongHeight.x() )
        latLongHeight.y() = osg.DegreesToRadians( latLongHeight.y() )
    if  arguments.read("--camera-hpr", hpr.x(), hpr.y(), hpr.z())  :
        activeMode = False
        hpr.x() = osg.DegreesToRadians( hpr.x() )
        hpr.y() = osg.DegreesToRadians( hpr.y() )
        hpr.z() = osg.DegreesToRadians( hpr.z() )
    
    # Construct scene graph
    scene = osgDB.readNodeFiles( arguments )
    if   not scene  : scene = osgDB.readNodeFile( "cow.osgt" )
    if   not scene  :
        print arguments.getApplicationName(), ": No data loaded"
        return 1
    
    # Create camera for rendering tiles offscreen. FrameBuffer is recommended because it requires less memory.
    camera = osg.Camera()
    camera.setClearColor( bgColor )
    camera.setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )
    camera.setReferenceFrame( osg.Transform.ABSOLUTE_RF )
    camera.setRenderOrder( osg.Camera.PRE_RENDER )
    camera.setRenderTargetImplementation( renderImplementation )
    camera.setViewport( 0, 0, tileWidth, tileHeight )
    camera.addChild( scene )
    
    # Set the printer
    printer = PosterPrinter()
    printer.setTileSize( tileWidth, tileHeight )
    printer.setPosterSize( posterWidth, posterHeight )
    printer.setCamera( camera )
    
    posterImage = 0
    if  outputPoster  :
        posterImage = osg.Image()
        posterImage.allocateImage( posterWidth, posterHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE )
        printer.setFinalPoster( posterImage )
        printer.setOutputPosterName( posterName )
    
#if 0
    # While recording sub-images of the poster, the scene will always be traversed twice, from its two
    # parent node: root and camera. Sometimes this may not be so comfortable.
    # To prevent this behaviour, we can use a switch node to enable one parent and disable the other.
    # However, the solution also needs to be used with care, as the window will go blank while taking
    # snapshots and recover later.
    root = osg.Switch()
    root.addChild( scene, True )
    root.addChild( camera, False )
#else:
    root = osg.Group()
    root.addChild( scene )
    root.addChild( camera )
#endif
    
    viewer = osgViewer.Viewer()
    viewer.setSceneData( root )
    viewer.getDatabasePager().setDoPreCompile( False )
    
    if  renderImplementation==osg.Camera.FRAME_BUFFER  :
        # FRAME_BUFFER requires the window resolution equal or greater than the to-be-copied size
        viewer.setUpViewInWindow( 100, 100, tileWidth, tileHeight )
    else:
        # We want to see the console output, so just render in a window
        viewer.setUpViewInWindow( 100, 100, 800, 600 )
    
    if  activeMode  :
        viewer.addEventHandler( PrintPosterHandler(printer) )
        viewer.addEventHandler( osgViewer.StatsHandler )()
        viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
        viewer.setCameraManipulator( osgGA.TrackballManipulator )()
        viewer.run()
    else:
        camera = viewer.getCamera()
        if   not useLatLongHeight  : computeViewMatrix( camera, eye, hpr )
        computeViewMatrixOnEarth = else( camera, scene, latLongHeight, hpr )
        
        renderer = CustomRenderer( camera )
        camera.setRenderer( renderer )
        viewer.setThreadingModel( osgViewer.Viewer.SingleThreaded )
        
        # Realize and initiate the first PagedLOD request
        viewer.realize()
        viewer.frame()
        
        printer.init( camera )
        while   not printer.done()  :
            viewer.advance()
            
            # Keep updating and culling until full level of detail is reached
            renderer.setCullOnly( True )
            while  viewer.getDatabasePager().getRequestsInProgress()  :
                viewer.updateTraversal()
                viewer.renderingTraversals()
            
            renderer.setCullOnly( False )
            printer.frame( viewer.getFrameStamp(), viewer.getSceneData() )
            viewer.renderingTraversals()
    return 0

# Translated from file 'PosterPrinter.cpp'

#include <osg/ClusterCullingCallback>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <string.h>
#include <iostream>
#include <sstream>
#include "PosterPrinter.h"

# PagedLoadingCallback: Callback for loading paged nodes while doing intersecting test 
class PagedLoadingCallback (osgUtil.IntersectionVisitor.ReadCallback) :
def readNodeFile(filename):
    
        return osgDB.readNodeFile( filename )

static PagedLoadingCallback g_pagedLoadingCallback = PagedLoadingCallback()

# LodCullingCallback: Callback for culling LODs and selecting the highest level 
class LodCullingCallback (osg.NodeCallback) :
    virtual void operator()( osg.Node* node, osg.NodeVisitor* nv )
        lod = static_cast<osg.LOD*>(node)
        if  lod  and  lod.getNumChildren()>0  :
            lod.getChild(lod.getNumChildren()-1).accept(*nv)

static LodCullingCallback g_lodCullingCallback = LodCullingCallback()

# PagedCullingCallback: Callback for culling paged nodes and selecting the highest level 
class PagedCullingCallback (osg.NodeCallback) :
    virtual void operator()( osg.Node* node, osg.NodeVisitor* nv )
        pagedLOD = static_cast<osg.PagedLOD*>(node)
        if  pagedLOD  and  pagedLOD.getNumChildren()>0  :
            numChildren = pagedLOD.getNumChildren()
            updateTimeStamp = nv.getVisitorType()==osg.NodeVisitor.CULL_VISITOR
            if  nv.getFrameStamp()  and  updateTimeStamp  :
                timeStamp =  nv.getFrameStamp().getReferenceTime() if (nv.getFrameStamp()) else 0.0
                frameNumber =  nv.getFrameStamp().getFrameNumber() if (nv.getFrameStamp()) else 0
                
                pagedLOD.setFrameNumberOfLastTraversal( frameNumber )
                pagedLOD.setTimeStamp( numChildren-1, timeStamp )
                pagedLOD.setFrameNumber( numChildren-1, frameNumber )
                pagedLOD.getChild(numChildren-1).accept(*nv)
            
            # Request for child
            if   not pagedLOD.getDisableExternalChildrenPaging()  and 
                 nv.getDatabaseRequestHandler()  and 
                 numChildren<pagedLOD.getNumRanges()  :
                if  pagedLOD.getDatabasePath().empty()  :
                    nv.getDatabaseRequestHandler().requestNodeFile(
                        pagedLOD.getFileName(numChildren), nv.getNodePath(),
                        1.0, nv.getFrameStamp(),
                        pagedLOD.getDatabaseRequest(numChildren), pagedLOD.getDatabaseOptions() )
                else:
                    nv.getDatabaseRequestHandler().requestNodeFile(
                        pagedLOD.getDatabasePath()+pagedLOD.getFileName(numChildren), nv.getNodePath(),
                        1.0, nv.getFrameStamp(),
                        pagedLOD.getDatabaseRequest(numChildren), pagedLOD.getDatabaseOptions() )
        #node.traverse(*nv)

static PagedCullingCallback g_pagedCullingCallback = PagedCullingCallback()

# PosterVisitor: A visitor for adding culling callbacks to newly allocated paged nodes 
PosterVisitor.PosterVisitor()
:   osg.NodeVisitor(osg.NodeVisitor.TRAVERSE_ALL_CHILDREN),
    _appliedCount(0), _needToApplyCount(0),
    _addingCallbacks(True)

void PosterVisitor.apply( osg.LOD node )
    #if   not hasCullCallback(node.getCullCallback(), g_lodCullingCallback)  :
#    
#        if   not node.getName().empty()  :
#        
#            itr = _pagedNodeNames.find( node.getName() )
#            if  itr not =_pagedNodeNames.end()  :
#            
#                insertCullCallback( node, g_lodCullingCallback )
#                _appliedCount++
#            
#        
#    
#    def if _addingCallbacks .
#        
#        node.removeCullCallback( g_lodCullingCallback )
#        _appliedCount--
#    
    traverse( node )

void PosterVisitor.apply( osg.PagedLOD node )
    if   not hasCullCallback(node.getCullCallback(), g_pagedCullingCallback)  :
        for ( unsigned int i=0 i<node.getNumFileNames() ++i )
            if  node.getFileName(i).empty()  : continue
            
            itr = _pagedNodeNames.find( node.getFileName(i) )
            if  itr not =_pagedNodeNames.end()  :
                node.addCullCallback( g_pagedCullingCallback )
                _appliedCount++
            break
        pathfile = str()
        keyForAnimationPath = ord("5")
        while arguments.read("-p",pathfile) :
            apm = osgGA.AnimationPathManipulator(pathfile)
            if apm  or   not apm.valid() : 
                num = keyswitchManipulator.getNumMatrixManipulators()
                keyswitchManipulator.addMatrixManipulator( keyForAnimationPath, "Path", apm )
                keyswitchManipulator.selectMatrixManipulator(num)
                ++keyForAnimationPath

        viewer.setCameraManipulator( keyswitchManipulator )


    # add the state manipulator
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    # add the stats handler
    viewer.addEventHandler(osgViewer.StatsHandler)()

    # add the record camera path handler
    viewer.addEventHandler(osgViewer.RecordCameraPathHandler)()

    # attach an IncrementaCompileOperation to allow the master loading 
    # to be handled with an incremental compile to avoid frame drops when large objects are added.
    viewer.setIncrementalCompileOperation(osgUtil.IncrementalCompileOperation())

    x = 0.0
    y = 0.0
    w = 1.0
    h = 1.0
예제 #3
0
def main(argv):

    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)
    arguments.getApplicationUsage().addCommandLineOption("-v","Set the terrain vertical scale.")
    arguments.getApplicationUsage().addCommandLineOption("-r","Set the terrain sample ratio.")
    arguments.getApplicationUsage().addCommandLineOption("--login <url> <username> <password>","Provide authentication information for http file access.")
   
    # construct the viewer.
    viewer = osgViewer.Viewer(arguments)


    # set the tile loaded callback to load the optional imagery
    whiteList = osgTerrain.WhiteListTileLoadedCallback()
    setname = str()
    while arguments.read("--allow",setname) :
        whiteList.allow(setname)
    while arguments.read("--allow-all") :
        whiteList.setAllowAll(True)
    osgTerrain.TerrainTile.setTileLoadedCallback(whiteList)


    # obtain the vertical scale
    verticalScale = 1.0
    while arguments.read("-v",verticalScale) : 
    
    # obtain the sample ratio
    sampleRatio = 1.0
    while arguments.read("-r",sampleRatio) : 


    # set up any authentication.
    str url, username, password
    while arguments.read("--login",url, username, password) :
        if  not osgDB.Registry.instance().getAuthenticationMap() :
            osgDB.Registry.instance().setAuthenticationMap(osgDB.AuthenticationMap)()
            osgDB.Registry.instance().getAuthenticationMap().addAuthenticationDetails(
                url,
                osgDB.AuthenticationDetails(username, password)
            )

    # add all the event handlers to the viewer
        # add the state manipulator
        viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

        # add the thread model handler
        viewer.addEventHandler(osgViewer.ThreadingHandler)()

        # add the window size toggle handler
        viewer.addEventHandler(osgViewer.WindowSizeHandler)()

        # add the stats handler
        viewer.addEventHandler(osgViewer.StatsHandler)()

        # add the help handler
        viewer.addEventHandler(osgViewer.HelpHandler(arguments.getApplicationUsage()))

        # add the record camera path handler
        viewer.addEventHandler(osgViewer.RecordCameraPathHandler)()

        # add the LOD Scale handler
        viewer.addEventHandler(osgViewer.LODScaleHandler)()

    # add all the camera manipulators
        keyswitchManipulator = osgGA.KeySwitchMatrixManipulator()

        keyswitchManipulator.addMatrixManipulator( ord("1"), "Trackball", osgGA.TrackballManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("2"), "Flight", osgGA.FlightManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("3"), "Drive", osgGA.DriveManipulator() )

        num = keyswitchManipulator.getNumMatrixManipulators()
        keyswitchManipulator.addMatrixManipulator( ord("4"), "Terrain", osgGA.TerrainManipulator() )

        pathfile = str()
        keyForAnimationPath = ord("5")
        while arguments.read("-p",pathfile) :
            apm = osgGA.AnimationPathManipulator(pathfile)
            if apm  or   not apm.valid() : 
                num = keyswitchManipulator.getNumMatrixManipulators()
                keyswitchManipulator.addMatrixManipulator( keyForAnimationPath, "Path", apm )
                ++keyForAnimationPath

        keyswitchManipulator.selectMatrixManipulator(num)

        viewer.setCameraManipulator( keyswitchManipulator )

    # set up the scene graph
        # load the nodes from the commandline arguments.
        rootnode = osgDB.readNodeFiles(arguments)

        if  not rootnode :
            osg.notify(osg.NOTICE), "Warning: no valid data loaded, please specify a database on the command line."
            return 1

        terrain = findTopMostNodeOfType<osgTerrain.Terrain>(rootnode)
        if  not terrain :
            terrain = osgTerrain.Terrain()

            csn = findTopMostNodeOfType<osg.CoordinateSystemNode>(rootnode)
            if csn :
                terrain.set(*csn)

            terrain.addChild(rootnode)

            rootnode = terrain
            csn = terrain

        terrain.setSampleRatio(sampleRatio)
        terrain.setVerticalScale(verticalScale)

        # register our custom handler for adjust Terrain settings
        viewer.addEventHandler(TerrainHandler(terrain))


        numLayers = 1
        mtc = findTopMostNodeOfType<osgFX.MultiTextureControl>(rootnode)
        if mtc :

            numLayers = mtc.getNumTextureWeights()

            # switch on just the first texture layer.
            mtc.setTextureWeight(0,1.0)
            for(unsigned int i=1 i<numLayers ++i)
                mtc.setTextureWeight(i,0.0)

        if numLayers<2 :
            osg.notify(osg.NOTICE), "Warning: scene must have MultiTextureControl node with at least 2 texture units defined."
            return 1

        maxElevationTransition = 1e6
        elevations = ElevationLayerBlendingCallback.Elevations()
        for(unsigned int i=0 i<numLayers ++i)
            elevations.push_back(maxElevationTransition)
            maxElevationTransition /= 2.0


        # we must assign callback as both an update and cull callback, as update callback to do the update of
        # the the osgFX.MultiTextureControl node a thread safe way, and as a cull callback to gather the camera
        # position information.
        elbc = ElevationLayerBlendingCallback(mtc, elevations)
        terrain.setUpdateCallback(elbc)
        terrain.setCullCallback(elbc)

        # add a viewport to the viewer and attach the scene graph.
        viewer.setSceneData( rootnode )
    


    # create the windows and run the threads.
    viewer.realize()

    return viewer.run()
예제 #4
0
def main(argv):


    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    arguments.getApplicationUsage().setApplicationName(arguments.getApplicationName())
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" demonstrates OpenGL occlusion query in OSG using the OcclusionQueryNode.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] [filename(s)]")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display command line parameters")

    # if user request help write it out to cout.
    if arguments.read("-h")  or  arguments.read("--help") :
        arguments.getApplicationUsage().write(std.cout, osg.ApplicationUsage.COMMAND_LINE_OPTION)
        return 1

    # report any errors if they have occurred when parsing the program arguments.
    if arguments.errors() :
        arguments.writeErrorMessages(std.cout)
        return 1

    viewer = osgViewer.Viewer( arguments )

    # add the state manipulator
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    # add the stats handler
    viewer.addEventHandler(osgViewer.StatsHandler)()

    # add the help handler
    viewer.addEventHandler(osgViewer.HelpHandler(arguments.getApplicationUsage()))

    optimize = arguments.read( "--opt" )

    # load the specified model
    root = 0

    if arguments.argc()>1 :
        root = osgDB.readNodeFiles( arguments )
        if root.valid() :
            # Run a NodeVisitor to insert OcclusionQueryNodes in the scene graph.
            oqv = OcclusionQueryVisitor()
            root.accept( oqv )
        else:
            print arguments.getApplicationName(), ": unable to load specified data."
            return 1
    else:
        root = createStockScene()
        if  not root :
            print arguments.getApplicationName(), ": Failed to create stock scene."
            return 1

    # any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized()

    # report any errors if they have occurred when parsing the program arguments.
    if arguments.errors() :
        arguments.writeErrorMessages(std.cout)
        return 1


    # optimize the scene graph, remove redundant nodes and state etc.
    if optimize :
        optimizer = osgUtil.Optimizer()
        optimizer.optimize( root )

    viewer.setSceneData( root )

    kh = KeyHandler( *root )
    viewer.addEventHandler( kh )

    return viewer.run()
예제 #5
0
def main(argv):


    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)
    
    # set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" is the example which demonstrates use of node tracker.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName())
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    

    # construct the viewer.
    viewer = osgViewer.Viewer(arguments)

    # add the state manipulator
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    
    # add the thread model handler
    viewer.addEventHandler(osgViewer.ThreadingHandler)()

    # add the window size toggle handler
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
        
    # add the stats handler
    viewer.addEventHandler(osgViewer.StatsHandler)()
        
    # add the record camera path  handler
    viewer.addEventHandler(osgViewer.RecordCameraPathHandler)()

    # add the help handler
    viewer.addEventHandler(osgViewer.HelpHandler(arguments.getApplicationUsage()))

    # set the near far ration computation up.
    viewer.getCamera().setComputeNearFarMode(osg.CullSettings.COMPUTE_NEAR_FAR_USING_PRIMITIVES)
    viewer.getCamera().setNearFarRatio(0.000003)


    speed = 1.0
    while arguments.read("-f")  or  arguments.read("--fixed") : speed = 0.0


    rotation = osg.Quat()
    vec4 = osg.Vec4()
    while arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]) :
        local_rotate = osg.Quat()
        local_rotate.makeRotate(osg.DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3])
        
        rotation = rotation * local_rotate

    nc = 0
    flightpath_filename = str()
    while arguments.read("--flight-path",flightpath_filename) :
        fin = osgDB.ifstream(flightpath_filename.c_str())
        if fin :
            path = osg.AnimationPath()
            path.read(fin)
            nc = osg.AnimationPathCallback(path)
    
    trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER_AND_ROTATION
    mode = str()
    while arguments.read("--tracker-mode",mode) :
        if mode=="NODE_CENTER_AND_ROTATION" : trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER_AND_ROTATION
        elif mode=="NODE_CENTER_AND_AZIM" : trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER_AND_AZIM
        elif mode=="NODE_CENTER" : trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER
        else:
            print "Unrecognized --tracker-mode option ", mode, ", valid options are:"
            print "    NODE_CENTER_AND_ROTATION"
            print "    NODE_CENTER_AND_AZIM"
            print "    NODE_CENTER"
            return 1
    
    
    rotationMode = osgGA.NodeTrackerManipulator.TRACKBALL
    while arguments.read("--rotation-mode",mode) :
        if mode=="TRACKBALL" : rotationMode = osgGA.NodeTrackerManipulator.TRACKBALL
        elif mode=="ELEVATION_AZIM" : rotationMode = osgGA.NodeTrackerManipulator.ELEVATION_AZIM
        else:
            print "Unrecognized --rotation-mode option ", mode, ", valid options are:"
            print "    TRACKBALL"
            print "    ELEVATION_AZIM"
            return 1

    useOverlay = True
    while arguments.read("--no-overlay")  or  arguments.read("-n") : useOverlay = False
    
    technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY
    while arguments.read("--object") : technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY
    while arguments.read("--ortho")  or  arguments.read("--orthographic") : technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY
    while arguments.read("--persp")  or  arguments.read("--perspective") : technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY

    overlayTextureUnit = 1
    while arguments.read("--unit", overlayTextureUnit) : 
    
    pathfile = str()
    while arguments.read("-p",pathfile) : 

    addFireEffect = arguments.read("--fire")

    # if user request help write it out to cout.
    if arguments.read("-h")  or  arguments.read("--help") :
        arguments.getApplicationUsage().write(std.cout)
        return 1
    
    
    tm = osgGA.NodeTrackerManipulator()
    
    overlayFilename = str()
    while arguments.read("--overlay", overlayFilename) : 

    # read the scene from the list of file specified commandline args.
    root = osgDB.readNodeFiles(arguments)

    if  not root : root = createEarth()

    if  not root : return 0


    if  not overlayFilename.empty() :
        #osg.Object *pObj = osgDB.readObjectFile("alaska_clean.shp")
        #osg.Geode shapefile = dynamic_cast<osg.Geode*> (pObj)
        #
        #ConvertLatLon2EllipsoidCoordinates latlon2em
        #shapefile.accept(latlon2em)

        shapefile = osgDB.readNodeFile(overlayFilename)
        
        if  not shapefile :
            osg.notify(osg.NOTICE), "File `", overlayFilename, "` not found"
            return 1

        csn = dynamic_cast<osg.CoordinateSystemNode*>(root)
        if csn :

            overlayNode = osgSim.OverlayNode(technique)
            overlayNode.getOrCreateStateSet().setTextureAttribute(1, osg.TexEnv(osg.TexEnv.DECAL))
            overlayNode.setOverlaySubgraph(shapefile)
            overlayNode.setOverlayTextureSizeHint(1024)
            overlayNode.setOverlayTextureUnit(overlayTextureUnit)

            # insert the OverlayNode between the coordinate system node and its children.
            for(unsigned int i=0 i<csn.getNumChildren() ++i)
                overlayNode.addChild( csn.getChild(i) )

            csn.removeChildren(0, csn.getNumChildren())
            csn.addChild(overlayNode)

            viewer.setSceneData(csn)
        else:
            overlayNode = osgSim.OverlayNode(technique)
            overlayNode.getOrCreateStateSet().setTextureAttribute(1, osg.TexEnv(osg.TexEnv.DECAL))
            overlayNode.setOverlaySubgraph(shapefile)
            overlayNode.setOverlayTextureSizeHint(1024)
            overlayNode.addChild(root)

            viewer.setSceneData(overlayNode)
    else:
    

        # add a viewport to the viewer and attach the scene graph.
        viewer.setSceneData(root)

        csn = dynamic_cast<osg.CoordinateSystemNode*>(root)
        if csn :

            overlayNode = osgSim.OverlayNode()
            if useOverlay :
                overlayNode = osgSim.OverlayNode(technique)

                # insert the OverlayNode between the coordinate system node and its children.
                for(unsigned int i=0 i<csn.getNumChildren() ++i)
                    overlayNode.addChild( csn.getChild(i) )

                csn.removeChildren(0, csn.getNumChildren())
                csn.addChild(overlayNode)

                # tell the overlay node to continously update its overlay texture
                # as we know we'll be tracking a moving target.
                overlayNode.setContinuousUpdate(True)


            cessna = osgDB.readNodeFile("cessna.osgt")
            if cessna :
                s = 200000.0 / cessna.getBound().radius()

                scaler = osg.MatrixTransform()
                scaler.addChild(cessna)
                scaler.setMatrix(osg.Matrixd.scale(s,s,s)*osg.Matrixd.rotate(rotation))
                scaler.getOrCreateStateSet().setMode(GL_RESCALE_NORMAL,osg.StateAttribute.ON)
                
                if addFireEffect :
                    center = cessna.getBound().center()
                    
                    fire = osgParticle.FireEffect(center, 10.0)
                    scaler.addChild(fire)
                

                if False :
                    ss = osgSim.SphereSegment(
                                        osg.Vec3(0.0,0.0,0.0), # center
                                        19.9, # radius
                                        osg.DegreesToRadians(135.0),
                                        osg.DegreesToRadians(240.0),
                                        osg.DegreesToRadians(-10.0),
                                        osg.DegreesToRadians(30.0),
                                        60)

                    scaler.addChild(ss)

                mt = osg.MatrixTransform()
                mt.addChild(scaler)


                if  not nc : nc = ModelPositionCallback(speed)

                mt.setUpdateCallback(nc)

                csn.addChild(mt)

                # if we are using an overaly node, use the cessna subgraph as the overlay subgraph
                if overlayNode.valid() :
                    overlayNode.setOverlaySubgraph(mt)

                tm = osgGA.NodeTrackerManipulator()
                tm.setTrackerMode(trackerMode)
                tm.setRotationMode(rotationMode)
                tm.setTrackNode(scaler)
            else:
                 print "Failed to read cessna.osgt"


    # set up camera manipulators.
        keyswitchManipulator = osgGA.KeySwitchMatrixManipulator()

        if tm.valid() : keyswitchManipulator.addMatrixManipulator( ord("0"), "NodeTracker", tm )

        keyswitchManipulator.addMatrixManipulator( ord("1"), "Trackball", osgGA.TrackballManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("2"), "Flight", osgGA.FlightManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("3"), "Drive", osgGA.DriveManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("4"), "Terrain", osgGA.TerrainManipulator() )

        if  not pathfile.empty() :
            apm = osgGA.AnimationPathManipulator(pathfile)
            if apm  or   not apm.valid() : 
                num = keyswitchManipulator.getNumMatrixManipulators()
                keyswitchManipulator.addMatrixManipulator( ord("5"), "Path", apm )
                keyswitchManipulator.selectMatrixManipulator(num)

        viewer.setCameraManipulator( keyswitchManipulator )

    # viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)

    return viewer.run()


if __name__ == "__main__":
    main(sys.argv)
예제 #6
0
def main(argv):

    
    arguments = osg.ArgumentParser(argv)

    # construct the viewer.
    viewer = osgViewer.Viewer(arguments)

    # set up camera manipulators
        keyswitchManipulator = osgGA.KeySwitchMatrixManipulator()

        keyswitchManipulator.addMatrixManipulator( ord("1"), "Trackball", osgGA.TrackballManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("2"), "Flight", osgGA.FlightManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("3"), "Drive", osgGA.DriveManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("4"), "Terrain", osgGA.TerrainManipulator() )

        keyForAnimationPath = ord("8")
        animationSpeed = 1.0
        while arguments.read("--speed",animationSpeed)  : 

        pathfile = str()
        while arguments.read("-p",pathfile) :
            apm = osgGA.AnimationPathManipulator(pathfile)
            if apm  or   not apm.valid() :
                apm.setTimeScale(animationSpeed)
                apm.setAnimationCompletedCallback(ReportStatsAnimationCompletedCallback())
                
                num = keyswitchManipulator.getNumMatrixManipulators()
                keyswitchManipulator.addMatrixManipulator( keyForAnimationPath, "Path", apm )
                keyswitchManipulator.selectMatrixManipulator(num)
                ++keyForAnimationPath

        viewer.setCameraManipulator( keyswitchManipulator )

    # set up event handlers 
        viewer.addEventHandler( osgViewer.StatsHandler())
        viewer.addEventHandler( osgViewer.WindowSizeHandler() )
        viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
        viewer.addEventHandler( TexturePoolHandler() )

    ########################################/
    #
    # IncrementalCompileOperation settings
    #
    incrementalCompile = osgUtil.IncrementalCompileOperation()
    viewer.setIncrementalCompileOperation(incrementalCompile)

    if arguments.read("--force")  or  arguments.read("-f") :
        incrementalCompile.assignForceTextureDownloadGeometry()

    if arguments.read("-a") :
        incrementalCompile.setMinimumTimeAvailableForGLCompileAndDeletePerFrame(1)
        incrementalCompile.setConservativeTimeRatio(1)
        incrementalCompile.setMaximumNumOfObjectsToCompilePerFrame(100)
    elif arguments.read("-c") :
        incrementalCompile.setMinimumTimeAvailableForGLCompileAndDeletePerFrame(0.0001)
        incrementalCompile.setConservativeTimeRatio(0.01)
        incrementalCompile.setMaximumNumOfObjectsToCompilePerFrame(1)

    ########################################/
    #
    # SceneGraph processing setup
    #
    sceneGraphProcessor = SceneGraphProcessor(arguments)

    ########################################/
    #
    # Database settings
    #
    timeBetweenMerges = 2.0
    while arguments.read("--interval",timeBetweenMerges) : 

    outputPostfix = str()
    while arguments.read("-o",outputPostfix) :  OSG_NOTICE, "Set ouputPostfix to ", outputPostfix 


    typedef std.vector< str > FileNames
    fileNames = FileNames()
    for(int pos=1pos<arguments.argc()++pos)
        if  not arguments.isOption(pos) :
            fileNames.push_back(arguments[pos])

    if fileNames.empty() :
        OSG_NOTICE, "No files loaded, please specify files on commandline."
        return 1

    # load the models using a paging thread and use the incremental compile operation to
    # manage the compilation of GL objects without breaking frame.

    modelIndex = 0

    databasePagingThread = osg.OperationThread()
    databasePagingOperation = DatabasePagingOperation()

    databasePagingThread = osg.OperationThread()
    databasePagingThread.startThread()


    group = osg.Group()
    viewer.setSceneData(group)

    viewer.realize()

    filename = fileNames[modelIndex++]
    outputFilename =  str() : osgDB: if (outputPostfix.empty()) else getStrippedName(filename)+outputPostfix

    databasePagingOperation = DatabasePagingOperation(
        filename,
        outputFilename,
        sceneGraphProcessor,
        incrementalCompile)

    databasePagingThread.add(databasePagingOperation)


    timeOfLastMerge = viewer.getFrameStamp().getReferenceTime()

    while  not viewer.done() :
        viewer.frame()

        currentTime = viewer.getFrameStamp().getReferenceTime()

        if  not databasePagingOperation  and 
            modelIndex<fileNames.size()  and 
            (currentTime-timeOfLastMerge)>timeBetweenMerges :
            filename = fileNames[modelIndex++]
            outputFilename =  str() : osgDB: if (outputPostfix.empty()) else getStrippedName(filename)+outputPostfix

            databasePagingOperation = DatabasePagingOperation(
                filename,
                outputFilename,
                sceneGraphProcessor,
                incrementalCompile)

            databasePagingThread.add(databasePagingOperation)

        if databasePagingOperation  and  databasePagingOperation._modelReadyToMerge :
            OSG_NOTICE, "Merging subgraph"
            
            timeOfLastMerge = currentTime

            group.removeChildren(0,group.getNumChildren())

            group.addChild(databasePagingOperation._loadedModel)

            viewer.home()

            # we no longer need the paging operation as it's done it's job.
            databasePagingOperation = 0

            viewer.home()
예제 #7
0
def main(argv):

    
    viewer = osgViewer.Viewer()
    
    # Let's get busy not  The WindowManager class is actually an osg.Switch,
    # so you can add it to (ideally) an orthographic camera and have it behave as
    # expected. Note that you create a WindowManager with a NodeMask--it is very important
    # that this be unique for picking to work properly. This also makes it possible to have
    # multiple WindowManagers each operating on their own, unique set of Window objects.
    # The final bool argument is a group of flags that introduce optional functionality
    # for the WindowManager. In our case we include the flags USE_PYTHON and USE_LUA,
    # to demonstrate (and test) their usage. Finally, we pass the temporary WM_NO_BETA_WARN
    # argument, which prevents creating the orange warning window. :) It will be shown
    # in other examples...
    wm = osgWidget.WindowManager(
        viewer,
        1280.0,
        1024.0,
        MASK_2D,
        osgWidget.WindowManager.WM_USE_LUA |
        osgWidget.WindowManager.WM_USE_PYTHON |
        osgWidget.WindowManager.WM_PICK_DEBUG
    )

    # An actual osgWidget.Window is pure virtual, so we've got to use the osgWidget.Box
    # implementation for now. At a later time, support for Tables and other kinds of
    # advanced layout Window types will be added.
    box = osgWidget.Box("box", osgWidget.Box.HORIZONTAL)

    # Now we actually attach our two types of callbacks to the box instance. The first
    # uses the simple function signature, the second uses a bound method, passing "this"
    # as the second argument to the Callback constructor.
    # Object obj

    static str data = "lol ur face not "

    #
#    box.addCallback(osgWidget.Callback(windowClicked, osgWidget.EVENT_MOUSE_PUSH, data))
#    box.addCallback(osgWidget.Callback(windowScrolled, osgWidget.EVENT_MOUSE_SCROLL))
#    box.addCallback(osgWidget.Callback(
#        Object.windowClicked,
#        obj,
#        osgWidget.EVENT_MOUSE_PUSH
#    ))
#    

    box.addCallback(CallbackObject(osgWidget.EVENT_MOUSE_PUSH))

    # Create some of our "testing" Widgets included are two Widget subclasses I made
    # during testing which I've kept around for testing purposes. You'll notice
    # that you cannot move the box using the NullWidget, and that the NotifyWidget
    # is a bit verbose. :)
    widget1 = osgWidget.NotifyWidget("widget1", 300.0, 100.0)
    widget2 = osgWidget.NullWidget("widget2", 400.0, 75.0)
    widget3 = osgWidget.Widget("widget3", 100.0, 100.0)
    # Set the colors of widget1 and widget3 to green.
    widget1.setColor(0.0, 1.0, 0.0, 1.0)
    widget1.setCanFill(True)
    widget3.setColor(0.0, 1.0, 0.0, 1.0)

    widget1.setImage(osgDB.readImageFile("Images/Saturn.TGA"), True)

    # Set the color of widget2, to differentiate it and make it sassy. This is
    # like a poor man's gradient not 
    widget2.setColor(0.9, 0.0, 0.0, 0.9, osgWidget.Widget.LOWER_LEFT)
    widget2.setColor(0.9, 0.0, 0.0, 0.9, osgWidget.Widget.LOWER_RIGHT)
    widget2.setColor(0.0, 0.0, 0.9, 0.9, osgWidget.Widget.UPPER_RIGHT)
    widget2.setColor(0.0, 0.0, 0.9, 0.9, osgWidget.Widget.UPPER_LEFT)

    # Now add our newly created widgets to our box.
    box.addWidget(widget1)
    box.addWidget(widget2)
    box.addWidget(widget3)

    # For maximum efficiency, Windows don't automatically reallocate their geometry
    # and internal positioning every time a widget is added. Thus, we either have to
    # call the WindowManger.resizeAllWindows method or manually call
    # Window.resize when we're ready.
    box.resize()

    # Now, lets clone our existing box and create a copy of of it, also adding that
    # to the WindowManager. This demonstrates the usages of OSG's .clone() support,
    # though that is abstracted by our META_UIObject macro.
    boxCopy = osg.clone(box, "newBox", osg.CopyOp.DEEP_COPY_ALL)

    # Move our copy to make it visible.
    boxCopy.setOrigin(0.0, 125.0)

    boxCopy.getByName("widget1").setColor(0.5, 0.0, 1.0, 1.0)
    boxCopy.getByName("widget3").setColor(0.5, 0.0, 1.0, 1.0)

    # Add the successfully created Box (if we get this far) into the WindowManager, so
    # that they can receive events.
    wm.addChild(box)
    wm.addChild(boxCopy)

    # Now, ask our box to be 100% the width of the WindowManager.
    boxCopy.resizePercent(100.0, 0.0)

    # Here we demonstrate the use of osgWidget/io_utils. This is really only useful for
    # debugging at the moment.
    # print *box, *boxCopy

    # Setup our OSG objects for our scene note the use of the utility function
    # createOrthoCamera, which is just a helper for setting up a proper viewing area.
    # An alternative (and a MUCH easier alternative at that not ) is to
    # simply use the createParentOrthoCamera method of the WindowManager class,
    # which will wrap the calls to createOrthoCamera and addChild for us not  Check out
    # some of the other examples to see this in action...
    group = osg.Group()
    camera = osgWidget.createOrthoCamera(1280.0, 1024.0)
    model = osgDB.readNodeFile("cow.osgt")

    # Add our event handler is this better as a MatrixManipulator? Add a few other
    # helpful ViewerEventHandlers.
    viewer.addEventHandler(osgWidget.MouseHandler(wm))
    viewer.addEventHandler(osgWidget.KeyboardHandler(wm))
    viewer.addEventHandler(osgWidget.ResizeHandler(wm, camera))
    viewer.addEventHandler(osgWidget.CameraSwitchHandler(wm, camera))
    viewer.addEventHandler(osgViewer.StatsHandler())
    viewer.addEventHandler(osgViewer.WindowSizeHandler())
    viewer.addEventHandler(osgGA.StateSetManipulator(
        viewer.getCamera().getOrCreateStateSet()
    ))

    # Set our first non-UI node to be something other than the mask we created our
    # WindowManager with to avoid picking.
    # TODO: Do I need to create a mechanism for doing this automatically, or should
    # that be the responsibility of the users of osgWidget?
    model.setNodeMask(MASK_3D)

    # Add the WindowManager instance to the 2D camera. This isn't strictly necessary,
    # and you can get some cool results putting the WindowManager directly into a
    # 3D scene. This is not necessary if you use WindowManager.createParentOrthoCamera.
    camera.addChild(wm)

    # Add our camera and a testing 3D model to the scene.
    group.addChild(camera)
    group.addChild(model)

    # Here we show how to both run simple strings of code AND run entire files. These
    # assume that you're running the osgwidgetwindow example from the build directory,
    # otherwise you'll need to adjust the file path below in the call to runFile().
    wm.getLuaEngine().eval("window = osgwidget.newWindow()")
    wm.getLuaEngine().runFile("osgWidget/osgwidgetwindow.lua")

    wm.getPythonEngine().eval("import osgwidget")
    wm.getPythonEngine().runFile("osgWidget/osgwidgetwindow.py")

    viewer.setUpViewInWindow(0, 0, 1280, 1024)
    viewer.setSceneData(group)

    #
#    cameras = osgViewer.Viewer.Cameras() 
#    viewer.getCameras(cameras)
#    c = cameras[0]
#    s = osg.Matrix.scale(1.0, -1.0, 1.0)
#    c.setProjectionMatrix(s * c.getProjectionMatrix())
#    

    return viewer.run()
예제 #8
0
#import the needed modules
from osgpypp import osg, osgDB, osgGA, osgViewer, osgUtil

osg.Vec3 = osg.Vec3f
osg.Matrix = osg.Matrixd
import sys

modelFile = 'cow.osg'
try:
    modelFile = sys.argv[1]
except:
    print 'You did not specify a model file. Using cow.osg as default.'

#load the model
loadedModel = osgDB.readNodeFile(modelFile)
if loadedModel == None:
    raise Exception('Loading model file failed')

root = osg.Group()
dynamicTransform1 = osg.MatrixTransform()
dynamicTransform1.addChild(loadedModel)
root.addChild(dynamicTransform1)

#create the viewer, set the scene and run
viewer = osgViewer.Viewer()
viewer.setSceneData(root)
viewer.addEventHandler(osgViewer.HelpHandler())
viewer.addEventHandler(osgViewer.StatsHandler())
viewer.addEventHandler(osgGA.StateSetManipulator(root.stateSet))
viewer.run()
예제 #9
0
            viewer.advance(simulationTime)
            
            pl = fc.getProperties()
            for(gsc.CaptureSettings.Properties.iterator plitr = pl.begin()
                not = pl.end()
                ++plitr)
                (*plitr).update(viewer)

            viewer.eventTraversal()
            viewer.updateTraversal()
            viewer.renderingTraversals()

            # advance simulationTime and number of frames rendered
            simulationTime += 1.0/fc.getFrameRate()

    object = osgGA.StateSetManipulator()
    ss = dynamic_cast<osgGA.StateSetManipulator*>(object)
   
    return 0

# Translated from file 'UpdateProperty.cpp'

#include "UpdateProperty.h"

using namespace gsc


# Translated from file 'UpdateProperty.h'

#ifndef UPDATEPROPERTY_H
#define UPDATEPROPERTY_H
예제 #10
0
def main(argv):


    

    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    # read the scene from the list of file specified commandline args.
    scene = osgDB.readNodeFiles(arguments)

    if  not scene :
        print argv[0], ": requires filename argument."
        return 1

    # construct the viewer.
    viewer = osgViewer.CompositeViewer(arguments)

    if arguments.read("-1") :
            view = osgViewer.View()
            view.setName("Single view")
            view.setSceneData(osgDB.readNodeFile("fountain.osgt"))

            view.addEventHandler( osgViewer.StatsHandler )()

            view.setUpViewAcrossAllScreens()
            view.setCameraManipulator(osgGA.TrackballManipulator)()
            viewer.addView(view)

    if arguments.read("-2") :

        # view one
            view = osgViewer.View()
            view.setName("View one")
            viewer.addView(view)

            view.setUpViewOnSingleScreen(0)
            view.setSceneData(scene)
            view.setCameraManipulator(osgGA.TrackballManipulator)()

            # add the state manipulator
            statesetManipulator = osgGA.StateSetManipulator()
            statesetManipulator.setStateSet(view.getCamera().getOrCreateStateSet())

            view.addEventHandler( statesetManipulator )

        # view two
            view = osgViewer.View()
            view.setName("View two")
            viewer.addView(view)

            view.setUpViewOnSingleScreen(1)
            view.setSceneData(scene)
            view.setCameraManipulator(osgGA.TrackballManipulator)()

            view.addEventHandler( osgViewer.StatsHandler )()


            # add the handler for doing the picking
            view.addEventHandler(PickHandler())


    if arguments.read("-3")  or  viewer.getNumViews()==0 :

        wsi = osg.GraphicsContext.getWindowingSystemInterface()
        if  not wsi :
            osg.notify(osg.NOTICE), "Error, no WindowSystemInterface available, cannot create windows."
            return 1

        unsigned int width, height
        wsi.getScreenResolution(osg.GraphicsContext.ScreenIdentifier(0), width, height)

        traits = osg.GraphicsContext.Traits()
        traits.x = 100
        traits.y = 100
        traits.width = 1000
        traits.height = 800
        traits.windowDecoration = True
        traits.doubleBuffer = True
        traits.sharedContext = 0

        gc = osg.GraphicsContext.createGraphicsContext(traits)
        if gc.valid() :
            osg.notify(osg.INFO), "  GraphicsWindow has been created successfully."

            # need to ensure that the window is cleared make sure that the complete window is set the correct colour
            # rather than just the parts of the window that are under the camera's viewports
            gc.setClearColor(osg.Vec4f(0.2,0.2,0.6,1.0))
            gc.setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        else:
            osg.notify(osg.NOTICE), "  GraphicsWindow has not been created successfully."

        # view one
            view = osgViewer.View()
            view.setName("View one")
            viewer.addView(view)

            view.setSceneData(scene)
            view.getCamera().setName("Cam one")
            view.getCamera().setViewport(osg.Viewport(0,0, traits.width/2, traits.height/2))
            view.getCamera().setGraphicsContext(gc)
            view.setCameraManipulator(osgGA.TrackballManipulator)()

            # add the state manipulator
            statesetManipulator = osgGA.StateSetManipulator()
            statesetManipulator.setStateSet(view.getCamera().getOrCreateStateSet())

            view.addEventHandler( statesetManipulator )

            view.addEventHandler( osgViewer.StatsHandler )()
            view.addEventHandler( osgViewer.HelpHandler )()
            view.addEventHandler( osgViewer.WindowSizeHandler )()
            view.addEventHandler( osgViewer.ThreadingHandler )()
            view.addEventHandler( osgViewer.RecordCameraPathHandler )()

        # view two
            view = osgViewer.View()
            view.setName("View two")
            viewer.addView(view)

            view.setSceneData(scene)
            view.getCamera().setName("Cam two")
            view.getCamera().setViewport(osg.Viewport(traits.width/2,0, traits.width/2, traits.height/2))
            view.getCamera().setGraphicsContext(gc)
            view.setCameraManipulator(osgGA.TrackballManipulator)()

            # add the handler for doing the picking
            view.addEventHandler(PickHandler())


        # view three
            view = osgViewer.View()
            view.setName("View three")
            viewer.addView(view)

            view.setSceneData(osgDB.readNodeFile("cessnafire.osgt"))

            view.getCamera().setName("Cam three")
            view.getCamera().setProjectionMatrixAsPerspective(30.0, double(traits.width) / double(traits.height/2), 1.0, 1000.0)
            view.getCamera().setViewport(osg.Viewport(0, traits.height/2, traits.width, traits.height/2))
            view.getCamera().setGraphicsContext(gc)
            view.setCameraManipulator(osgGA.TrackballManipulator)()



    while arguments.read("-s") :  viewer.setThreadingModel(osgViewer.CompositeViewer.SingleThreaded) 
    while arguments.read("-g") :  viewer.setThreadingModel(osgViewer.CompositeViewer.CullDrawThreadPerContext) 
    while arguments.read("-c") :  viewer.setThreadingModel(osgViewer.CompositeViewer.CullThreadPerCameraDrawThreadPerContext) 

     # run the viewer's main frame loop
     return viewer.run()
예제 #11
0
        view = osgViewer.View()
        view.setName("View one")
        viewer.addView(view)

        g = osg.Group()
        g.addChild(scene)
        g.addChild(createHUD())
        view.setSceneData(g)
        view.getCamera().setName("Cam one")
        view.getCamera().setViewport(osg.Viewport(0,0, traits.width, traits.height))
        view.getCamera().setGraphicsContext(gc)
        view.setCameraManipulator(osgGA.TrackballManipulator)()

        # add the state manipulator
        statesetManipulator = osgGA.StateSetManipulator()
        statesetManipulator.setStateSet(view.getCamera().getOrCreateStateSet())

        view.addEventHandler( statesetManipulator )
        view.addEventHandler( osgViewer.StatsHandler )()

        if use_zeroconf :
            zeroconf_device = osgDB.readFile<osgGA.Device>("_osc._udp.discover.zeroconf")
            if zeroconf_device : 
                view.addDevice(zeroconf_device)
                view.getEventHandlers().push_front(OscServiceDiscoveredEventHandler())

        else:
            device = osgDB.readFile<osgGA.Device>("localhost:9000.sender.osc")
            if device.valid()  and  (device.getCapabilities()  osgGA.Device.SEND_EVENTS) :
                # add as first event handler, so it gets ALL events ...
예제 #12
0
def main(argv):


    
    arguments = osg.ArgumentParser(argv)

    viewer = osgViewer.Viewer(arguments)

    fontFile = str("arial.ttf")
    while arguments.read("-f",fontFile) : 

    font = osgText.readFontFile(fontFile)
    if  not font : return 1
    OSG_NOTICE, "Read font ", fontFile, " font=", font

    word = str("This is a test.")()
    while arguments.read("-w",word) : 

    style = osgText.Style()

    thickness = 0.1
    while arguments.read("--thickness",thickness) : 
    style.setThicknessRatio(thickness)

    # set up any bevel if required
    r = float()
    bevel = osgText.Bevel()
    while arguments.read("--rounded",r) :  bevel = osgText.Bevel() bevel.roundedBevel2(r) 
    while arguments.read("--rounded") :  bevel = osgText.Bevel() bevel.roundedBevel2(0.25) 
    while arguments.read("--flat",r) :  bevel = osgText.Bevel() bevel.flatBevel(r) 
    while arguments.read("--flat") :  bevel = osgText.Bevel() bevel.flatBevel(0.25) 
    while arguments.read("--bevel-thickness",r) :  if bevel.valid() : bevel.setBevelThickness(r) 

    style.setBevel(bevel)

    # set up outline.
    while arguments.read("--outline",r) :  style.setOutlineRatio(r) 


    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    viewer.addEventHandler(osgViewer.StatsHandler)()

#if 1
    group = osg.Group()

    characterSize = 1.0
    while arguments.read("--size",characterSize) : 

    if arguments.read("--2d") :
        text2D = osgText.Text()
        text2D.setFont(font)
        text2D.setCharacterSize(characterSize)
        text2D.setFontResolution(256,256)
        text2D.setDrawMode(osgText.Text.TEXT | osgText.Text.BOUNDINGBOX)
        text2D.setAxisAlignment(osgText.Text.XZ_PLANE)
        text2D.setText(word)
        geode = osg.Geode()
        geode.addDrawable(text2D)
        group.addChild(geode)

    if arguments.read("--TextNode") :
        # experimental text node
        text = osgText.TextNode()
        text.setFont(font)
        text.setStyle(style)
        text.setTextTechnique(osgText.TextTechnique)()
        text.setText(word)
        text.update()

        group.addChild(text)
    elif  not arguments.read("--no-3d") :
        text3D = osgText.Text3D()
        text3D.setFont(font)
        text3D.setStyle(style)
        text3D.setCharacterSize(characterSize)
        text3D.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
        text3D.setAxisAlignment(osgText.Text3D.XZ_PLANE)
        text3D.setText(word)

        geode = osg.Geode()
        geode.addDrawable(text3D)
        group.addChild(geode)

        color = osg.Vec4(1.0, 1.0, 1.0, 1.0)
        while arguments.read("--color",color.r(),color.g(),color.b(),color.a()) :
            OSG_NOTICE, "--color ", color
            text3D.setColor(color)

        imageFilename = str()
        while arguments.read("--image",imageFilename) :
            OSG_NOTICE, "--image ", imageFilename
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                OSG_NOTICE, "  loaded image ", imageFilename
                stateset = text3D.getOrCreateStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        while arguments.read("--wall-color",color.r(),color.g(),color.b(),color.a()) :
            stateset = text3D.getOrCreateWallStateSet()
            material = osg.Material()
            material.setDiffuse(osg.Material.FRONT_AND_BACK, color)
            stateset.setAttribute(material)

        while arguments.read("--wall-image",imageFilename) :
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                stateset = text3D.getOrCreateWallStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        while arguments.read("--back-color",color.r(),color.g(),color.b(),color.a()) :
            stateset = text3D.getOrCreateBackStateSet()
            material = osg.Material()
            material.setDiffuse(osg.Material.FRONT_AND_BACK, color)
            stateset.setAttribute(material)

        while arguments.read("--back-image",imageFilename) :
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                stateset = text3D.getOrCreateBackStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        if arguments.read("--size-quad") :
            geode.addDrawable( osg.createTexturedQuadGeometry(osg.Vec3(0.0,characterSize*thickness,0.0),osg.Vec3(characterSize,0.0,0.0),osg.Vec3(0.0,0.0,characterSize), 0.0, 0.0, 1.0, 1.0) )

    
    viewer.setSceneData(group)

#endif

    return viewer.run()

# Translated from file 'osgtext3D_orig.cpp'

# OpenSceneGraph example, osgtext.
#*
#*  Permission is hereby granted, free of charge, to any person obtaining a copy
#*  of this software and associated documentation files (the "Software"), to deal
#*  in the Software without restriction, including without limitation the rights
#*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#*  copies of the Software, and to permit persons to whom the Software is
#*  furnished to do so, subject to the following conditions:
#*
#*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#*  THE SOFTWARE.
#


#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgText/Text3D>

#include <iostream>
#include <sstream>



# create text which sits in 3D space such as would be inserted into a normal model
def create3DText(center, radius):
    

    geode = osg.Geode()

####################################################
#    
# Examples of how to set up axis/orientation alignments
#

    characterSize = radius*0.2
    characterDepth = characterSize*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)

    text1 = osgText.Text3D()
    text1.setFont("fonts/arial.ttf")
    text1.setCharacterSize(characterSize)
    text1.setCharacterDepth(characterDepth)
    text1.setPosition(pos)
    text1.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text1.setAxisAlignment(osgText.Text3D.XY_PLANE)
    text1.setText("XY_PLANE")
    geode.addDrawable(text1)

    text2 = osgText.Text3D()
    text2.setFont("fonts/times.ttf")
    text2.setCharacterSize(characterSize)
    text2.setCharacterDepth(characterDepth)
    text2.setPosition(pos)
    text2.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text2.setAxisAlignment(osgText.Text3D.YZ_PLANE)
    text2.setText("YZ_PLANE")
    geode.addDrawable(text2)

    text3 = osgText.Text3D()
    text3.setFont("fonts/dirtydoz.ttf")
    text3.setCharacterSize(characterSize)
    text3.setCharacterDepth(characterDepth)
    text3.setPosition(pos)
    text3.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text3.setAxisAlignment(osgText.Text3D.XZ_PLANE)
    text3.setText("XZ_PLANE")
    geode.addDrawable(text3)

    style = osgText.Style()
    bevel = osgText.Bevel()
    bevel.roundedBevel2(0.25)
    style.setBevel(bevel)
    style.setWidthRatio(0.4)

    text7 = osgText.Text3D()
    text7.setFont("fonts/times.ttf")
    text7.setStyle(style)
    text7.setCharacterSize(characterSize)
    text7.setCharacterDepth(characterSize*0.2)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text7.setAxisAlignment(osgText.Text3D.SCREEN)
    text7.setCharacterSizeMode(osgText.Text3D.OBJECT_COORDS)
    text7.setText("CharacterSizeMode OBJECT_COORDS (default)")
    geode.addDrawable(text7)

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

    front = osg.Material()
    front.setAlpha(osg.Material.FRONT_AND_BACK,1)
    front.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,1.0))
    front.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(.0,.0,1.0,1.0))
    rootNode.getOrCreateStateSet().setAttributeAndModes(front)
    
    
    return rootNode    

int main_orig(int, char**)
    viewer = osgViewer.Viewer()

    center = osg.Vec3(0.0,0.0,0.0)
    radius = 1.0
    
    root = osg.Group()
    root.addChild(create3DText(center, radius))

    viewer.setSceneData(root)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
    viewer.addEventHandler(osgViewer.StatsHandler)()


    viewer.run()
    
    return 0



# Translated from file 'osgtext3D_test.cpp'


#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgText/Text3D>

#include <iostream>
#include <sstream>



def test_create3DText(center, radius):



    

    geode = osg.Geode()

    characterSize = radius*0.2
    characterDepth = characterSize*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)
#define SHOW_INTESECTION_CEASH
#ifdef SHOW_INTESECTION_CEASH
    text3 = osgText.Text3D()
    text3.setFont("fonts/dirtydoz.ttf")
    text3.setCharacterSize(characterSize)
    text3.setCharacterDepth(characterDepth)
    text3.setPosition(pos)
    text3.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text3.setAxisAlignment(osgText.Text3D.XZ_PLANE)
    text3.setText("CRAS H") #intersection crash
    geode.addDrawable(text3)
#else:
    text7 = osgText.Text3D()
    text7.setFont("fonts/times.ttf")
    text7.setCharacterSize(characterSize)
    text7.setCharacterDepth(characterSize*2.2)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text7.setAxisAlignment(osgText.Text3D.SCREEN)
    text7.setCharacterSizeMode(osgText.Text3D.OBJECT_COORDS)
    text7.setText("ABCDE") #wrong intersection
    geode.addDrawable(text7)
#endif

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

#define SHOW_WRONG_NORMAL
#ifdef SHOW_WRONG_NORMAL
    front = osg.Material() #
    front.setAlpha(osg.Material.FRONT_AND_BACK,1)
    front.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,1.0))
    front.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(.0,.0,1.0,1.0))
    rootNode.getOrCreateStateSet().setAttributeAndModes(front)
#else:
    stateset = osg.StateSet() #Show wireframe
    polymode = osg.PolygonMode()
    polymode.setMode(osg.PolygonMode.FRONT_AND_BACK,osg.PolygonMode.LINE)
    stateset.setAttributeAndModes(polymode,osg.StateAttribute.OVERRIDE|osg.StateAttribute.ON)
    rootNode.setStateSet(stateset)
#endif
    
    
    return rootNode    

#####################################
#include <osg/PositionAttitudeTransform>
#include <osg/ShapeDrawable>
class CInputHandler (osgGA.GUIEventHandler) :
  CInputHandler( osg.PositionAttitudeTransform* pPatSphere )
    m_rPatSphere = pPatSphere
  def handle(ea, aa, pObject, pNodeVisitor):
      
    pViewer = dynamic_cast<osgViewer.Viewer*>(aa)
    if   not pViewer  :
      return False

    if  ea.getEventType()==osgGA.GUIEventAdapter.PUSH  :
      cams = osgViewer.ViewerBase.Cameras()
      pViewer.getCameras( cams )

      x = ea.getXnormalized()
      y = ea.getYnormalized()

      picker = osgUtil.LineSegmentIntersector( osgUtil.Intersector.PROJECTION, x, y )
      iv = osgUtil.IntersectionVisitor( picker )
      cams[0].accept( iv )

      if  picker.containsIntersections()  :
        intersection = picker.getFirstIntersection()
        v = intersection.getWorldIntersectPoint()
        m_rPatSphere.setPosition( v )

      return True # return True, event handled

    return False
  m_rPatSphere = osg.PositionAttitudeTransform()

#####################################
int main_test(int, char**)
    viewer = osgViewer.Viewer()
    viewer.setUpViewInWindow(99,99,666,666, 0)
    rPat = osg.PositionAttitudeTransform()
    # add the handler to the viewer
    viewer.addEventHandler( CInputHandler(rPat) )
    # create a group to contain our scene and sphere
    pGroup = osg.Group()
    # create sphere
    pGeodeSphere = osg.Geode()
    pGeodeSphere.addDrawable( osg.ShapeDrawable( osg.Sphere(osg.Vec3(0.0,0.0,0.0),0.01) ) )
    rPat.addChild( pGeodeSphere )
    pGroup.addChild( rPat )

    center = osg.Vec3(0.0,0.0,0.0)
    radius = 1.0

    root = osg.Group()
    root.addChild(test_create3DText(center, radius))

    #viewer.setSceneData(root)
    pGroup.addChild(root)
    viewer.setSceneData(pGroup)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
    viewer.addEventHandler(osgViewer.StatsHandler)()

    return viewer.run()



# Translated from file 'TextNode.cpp'

# -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
# *
# * This library is open source and may be redistributed and/or modified under
# * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
# * (at your option) any later version.  The full license is in LICENSE file
# * included with this distribution, and on the openscenegraph.org website.
# *
# * This library is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# * OpenSceneGraph Public License for more details.
#

#include "TextNode.h"
#include "../../src/osgText/GlyphGeometry.h"

#include <osg/PositionAttitudeTransform>
#include <osg/Geode>
#include <osgUtil/SmoothingVisitor>

#include <osg/io_utils>

using namespace osgText

############################################/
#
# Layout
#
Layout.Layout()

Layout.Layout( Layout layout,  osg.CopyOp copyop):
    osg.Object(layout,copyop)
예제 #13
0
def main(argv):

    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    if argc<2 : 
        print argv[0], ": requires filename argument."
        return 1

    viewer = osgViewer.Viewer(arguments)
    
    outputfile = str("output.osgt")
    while arguments.read("-o",outputfile) : 

    while arguments.read("-s") :  viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded) 
    while arguments.read("-g") :  viewer.setThreadingModel(osgViewer.Viewer.CullDrawThreadPerContext) 
    while arguments.read("-d") :  viewer.setThreadingModel(osgViewer.Viewer.DrawThreadPerContext) 
    while arguments.read("-c") :  viewer.setThreadingModel(osgViewer.Viewer.CullThreadPerCameraDrawThreadPerContext) 
    
    singleWindowSideBySideCameras(viewer)

    viewer.setCameraManipulator( osgGA.TrackballManipulator() )
    viewer.addEventHandler(osgViewer.StatsHandler)()
    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler())
    viewer.addEventHandler(osgViewer.LODScaleHandler())
    viewer.addEventHandler(osgGA.StateSetManipulator())

    visit = SwitchDOFVisitor()
    viewer.addEventHandler(visit)
    
    loadedModel = osg.Node()
    # load the scene.
    loadedModel = osgDB.readNodeFiles(arguments)

    if  not loadedModel : 
        print argv[0], ": No data loaded."
        return 1

    group = osg.Group()
    
    group1 = osg.Group()
    group1.addChild(loadedModel)
    group1.setNodeMask(1)

    # Uncomment these lines if you like to compare the loaded model to the resulting model in a merge/diff tool
    #osgDB.writeNodeFile(*loadedModel, "dummy1.osgt")

    osgDB.writeNodeFile(*loadedModel, outputfile)
    convertedModel = osgDB.readNodeFile(outputfile)

    #osgDB.writeNodeFile(*convertedModel, "dummy2.osgt")

    group2 = osg.Group()
    group2.addChild(convertedModel)
    group2.setNodeMask(2)

    # Activate DOF animations and collect switches
    loadedModel.accept(*visit)
    convertedModel.accept(*visit)

    group.addChild(group1)
    group.addChild(group2)

    viewer.setSceneData(group)

    viewer.setThreadingModel(osgViewer.Viewer.DrawThreadPerContext)
    viewer.realize()

    viewer.run()

    return 0



if __name__ == "__main__":
    main(sys.argv)
예제 #14
0
def main(argv):


    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    # construct the viewer.
    viewer = osgViewer.Viewer()

    # load the nodes from the commandline arguments.
    loadedModel = osgDB.readNodeFiles(arguments)

    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not loadedModel : loadedModel = osgDB.readNodeFile("cow.osgt")

    if  not loadedModel :
        print arguments.getApplicationName(), ": No data loaded"
        return 1


    if arguments.read("--dome")  or  arguments.read("--puffer")  :

        setDomeCorrection(viewer, arguments)

        viewer.setSceneData( loadedModel )
    elif arguments.read("--faces") :

        setDomeFaces(viewer, arguments)

        viewer.setSceneData( loadedModel )
    else:
        distortionNode = createDistortionSubgraph( loadedModel, viewer.getCamera().getClearColor())
        viewer.setSceneData( distortionNode )

    while arguments.read("--sky-light") :
        viewer.setLightingMode(osg.View.SKY_LIGHT)

    if viewer.getLightingMode()==osg.View.HEADLIGHT :
        viewer.getLight().setPosition(osg.Vec4(0.0,0.0,0.0,1.0))


    # load the nodes from the commandline arguments.
    if  not viewer.getSceneData() :
        osg.notify(osg.NOTICE), "Please specify a model filename on the command line."
        return 1


    # set up the camera manipulators.
        keyswitchManipulator = osgGA.KeySwitchMatrixManipulator()

        keyswitchManipulator.addMatrixManipulator( ord("1"), "Trackball", osgGA.TrackballManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("2"), "Flight", osgGA.FlightManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("3"), "Drive", osgGA.DriveManipulator() )
        keyswitchManipulator.addMatrixManipulator( ord("4"), "Terrain", osgGA.TerrainManipulator() )

        pathfile = str()
        keyForAnimationPath = ord("5")
        while arguments.read("-p",pathfile) :
            apm = osgGA.AnimationPathManipulator(pathfile)
            if apm  or   not apm.valid() :
                num = keyswitchManipulator.getNumMatrixManipulators()
                keyswitchManipulator.addMatrixManipulator( keyForAnimationPath, "Path", apm )
                keyswitchManipulator.selectMatrixManipulator(num)
                ++keyForAnimationPath

        viewer.setCameraManipulator( keyswitchManipulator )

    viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)

    # add the state manipulator
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    # add the stats handler
    viewer.addEventHandler(osgViewer.StatsHandler)()

    return viewer.run()
예제 #15
0
def main(argv):

    
    arguments = osg.ArgumentParser( argc, argv )
    
    textureFile = str("Images/smoke.rgb")
    while  arguments.read("--texture", textureFile)  : 
    
    pointSize = 20.0
    while  arguments.read("--point", pointSize)  : 
    
    visibilityDistance = -1.0
    while  arguments.read("--visibility", visibilityDistance)  : 
    
    customShape = False
    while  arguments.read("--enable-custom")  :  customShape = True 
    
    useShaders = True
    while  arguments.read("--disable-shaders")  :  useShaders = False 
    
    #**
#    Customize particle template and system attributes
#    **
    ps = osgParticle.ParticleSystem()
    
    ps.getDefaultParticleTemplate().setLifeTime( 5.0 )
    
    if  customShape  :
        # osgParticle now supports making use of customized drawables. The draw() method will be executed
        # and display lists will be called for each particle. It is always a huge consumption of memory, and
        # hardly to use shaders to render them, so please be careful using this feature.
        ps.getDefaultParticleTemplate().setShape( osgParticle.Particle.USER )
        ps.getDefaultParticleTemplate().setDrawable( osg.ShapeDrawable(osg.Box(osg.Vec3(), 1.0)) )
        useShaders = False
    else:
        # The shader only supports rendering points at present.
        ps.getDefaultParticleTemplate().setShape( osgParticle.Particle.POINT )
    
    # Set the visibility distance of particles, due to their Z-value in the eye coordinates.
    # Particles that are out of the distance (or behind the eye) will not be rendered.
    ps.setVisibilityDistance( visibilityDistance )
    
    if  useShaders  :
        # Set using local GLSL shaders to render particles.
        # At present, this is slightly efficient than ordinary methods. The bottlenack here seems to be the cull
        # traversal time. Operators go through the particle list again and again...
        ps.setDefaultAttributesUsingShaders( textureFile, True, 0 )
    else:
        # The default methods uses glBegin()/glEnd() pairs. Fortunately the GLBeginEndAdapter does improve the
        # process, which mimics the immediate mode with glDrawArrays().
        ps.setDefaultAttributes( textureFile, True, False, 0 )
        
        # Without the help of shaders, we have to sort particles to make the visibility distance work. Sorting is
        # also useful in rendering transparent particles in back-to-front order.
        if  visibilityDistance>0.0  :
            ps.setSortMode( osgParticle.ParticleSystem.SORT_BACK_TO_FRONT )
    
    # At last, to make the point sprite work, we have to set the points size and the sprite attribute.
    stateset = ps.getOrCreateStateSet()
    stateset.setAttribute( osg.Point(pointSize) )
    stateset.setTextureAttributeAndModes( 0, osg.PointSprite, osg.StateAttribute.ON )()
    
    #**
#    Construct other particle system elements, including the emitter and program
#    **
    emitter = osgParticle.ModularEmitter()
    emitter.setParticleSystem( ps )
    
    program = osgParticle.ModularProgram()
    program.setParticleSystem( ps )
    
    createFountainEffect( emitter, program )
    
    #**
#    Add the entire particle system to the scene graph
#    **
    parent = osg.MatrixTransform()
    parent.addChild( emitter )
    parent.addChild( program )
    
    # The updater can receive particle systems as child drawables now. The addParticleSystem() method
    # is still usable, with which we should define another geode to contain a particle system.
    updater = osgParticle.ParticleSystemUpdater()
    #updater.addDrawable( ps )
    
    root = osg.Group()
    root.addChild( parent )
    root.addChild( updater )
    
    # FIXME 2010.9.19: the updater can't be a drawable otehrwise the ParticleEffect will not work properly. why?
    updater.addParticleSystem( ps )
    
    geode = osg.Geode()
    geode.addDrawable( ps )
    root.addChild( geode )
    
    #**
#    Start the viewer
#    **
    viewer = osgViewer.Viewer()
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    viewer.addEventHandler( osgViewer.StatsHandler )()
    viewer.addEventHandler( osgViewer.WindowSizeHandler )()
    viewer.setSceneData( root )
    viewer.setCameraManipulator( osgGA.TrackballManipulator )()
    
    # A floating error of delta-time should be explained here:
    # The particles emitter, program and updater all use a 'dt' to compute the time value in every frame.
    # Because the 'dt' is a double value, it is not suitable to keep three copies of it seperately, which
    # is the previous implementation. The small error makes some opeartors unable to work correctly, e.g.
    # the BounceOperator.
    # Now we make use of the getDeltaTime() of ParticleSystem to maintain and dispatch the delta time. But..
    # it is not the best solution so far, since there are still very few particles acting unexpectedly.
    return viewer.run()
    
    # FIXME 2010.9.19: At present, getDeltaTime() is not used and the implementations in the updater and processors still
    # use a (t - _t0) as the delta time, which is of course causing floating errors. ParticleEffect will not work if we
    # replace the delta time with getDeltaTime()... Need to find a solution.


if __name__ == "__main__":
    main(sys.argv)
예제 #16
0
# Create a 1x1 quad in XZ plane
g = osg.createTexturedQuadGeometry(osg.Vec3f(0, 0, 0), osg.Vec3f(1, 0, 0),
                                   osg.Vec3f(0, 0, 1), 0, 0, 1, 1)
g.getColorArray()[0] = osg.Vec4f(1, 1, 1,
                                 0.5)  # change color to semitransparent

# Add it to a geode
geode = osg.Geode()
geode.addDrawable(g)

# Add texture
i = osgDB.readImageFile("Images/osg256.png")
t = osg.Texture2D(i)
s = geode.stateSet
s.setTextureAttributeAndModes(0, t, osg.StateAttribute.Values.ON)

# Make sure blending is active and the geode is in the transparent (depth sorted) bin
s.setRenderingHint(osg.StateSet.TRANSPARENT_BIN)
s.setMode(osg.GL_BLEND, osg.StateAttribute.ON)

# Create viewer, add some standard handlers to it and run it
viewer = osgViewer.Viewer()
viewer.setUpViewInWindow(50, 50, 1024, 768)
viewer.addEventHandler(osgGA.StateSetManipulator(geode.stateSet))
viewer.addEventHandler(osgViewer.HelpHandler())
viewer.addEventHandler(osgViewer.StatsHandler())
viewer.setSceneData(geode)
viewer.run()
del viewer  # To cause the dtor to be called, hence the window to be destroyed.
def main(argv):

    
    arguments = osg.ArgumentParser(argv)
    arguments.getApplicationUsage().setApplicationName(arguments.getApplicationName())
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" is an example for viewing osgAnimation animations.")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","List command line options.")
    arguments.getApplicationUsage().addCommandLineOption("--drawbone","draw helps to display bones.")

    if arguments.read("-h")  or  arguments.read("--help") :
        arguments.getApplicationUsage().write(std.cout, osg.ApplicationUsage.COMMAND_LINE_OPTION)
        return 0

    if arguments.argc()<=1 :
        arguments.getApplicationUsage().write(std.cout, osg.ApplicationUsage.COMMAND_LINE_OPTION)
        return 1

    drawBone = False
    if arguments.read("--drawbone") :
        drawBone = True

    viewer = osgViewer.Viewer(arguments)
    group = osg.Group()

    node = dynamic_cast<osg.Group*>(osgDB.readNodeFiles(arguments)) #dynamic_cast<osgAnimation.AnimationManager*>(osgDB.readNodeFile(psr[1]))
    if  not node :
        print arguments.getApplicationName(), ": No data loaded"
        return 1

    # Set our Singleton's model.
    finder = AnimationManagerFinder()
    node.accept(finder)
    if finder._am.valid() : 
        node.setUpdateCallback(finder._am)
        AnimtkViewerModelController.setModel(finder._am)
     else:
        osg.notify(osg.WARN), "no osgAnimation.AnimationManagerBase found in the subgraph, no animations available"

    if drawBone : 
        osg.notify(osg.INFO), "Add Bones Helper"
        addHelper = AddHelperBone()
        node.accept(addHelper)
    node.addChild(createAxis())

    gui = AnimtkViewerGUI(viewer, WIDTH, HEIGHT, 0x1234)
    camera = gui.createParentOrthoCamera()

    node.setNodeMask(0x0001)

    group.addChild(node)
    group.addChild(camera)

    viewer.addEventHandler(AnimtkKeyEventHandler())
    viewer.addEventHandler(osgViewer.StatsHandler())
    viewer.addEventHandler(osgViewer.WindowSizeHandler())
    viewer.addEventHandler(osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()))
    viewer.addEventHandler(osgWidget.MouseHandler(gui))
    viewer.addEventHandler(osgWidget.KeyboardHandler(gui))
    viewer.addEventHandler(osgWidget.ResizeHandler(gui, camera))
    viewer.setSceneData(group)

    viewer.setUpViewInWindow(40, 40, WIDTH, HEIGHT)

    return viewer.run()