def main(argv):

    
    arguments = osg.ArgumentParser(argv)

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

    # 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 )
def main(argv):

    
    arguments = osg.ArgumentParser(argv)
    viewer = osgViewer.Viewer(arguments)
    
    tbm = osgGA.TrackballManipulator()

    viewer.setCameraManipulator(tbm)

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

    root = osg.Group()
    geode = osg.Geode()

    geode.setStateSet(setupStateSet())

    root.setInitialBound(osg.BoundingSphere(osg.Vec3(10,0,20), 50))
    root.addChild(setupAnimtkNode(geode))
    root.addChild(geode)

    viewer.setSceneData(root)

    # tbm.setDistance(150)

    return viewer.run()
Example #3
0
def main(argv):
    overlay = False
    arguments = osg.ArgumentParser(argv)
    while arguments.read("--overlay") : 
        overlay = True
    technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY
    while arguments.read("--object") :  
        technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY 
        overlay=True 
    while arguments.read("--ortho")  or  arguments.read("--orthographic") :  
        technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY 
        overlay=True 
    while arguments.read("--persp")  or  arguments.read("--perspective") :  
        technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY 
        overlay=True 
    # initialize the viewer.
    viewer = osgViewer.Viewer()
    # load the nodes from the commandline arguments.
    model = createModel(overlay, technique)
    if not model:
        return 1
    # tilt the scene so the default eye position is looking down on the model.
    rootnode = osg.MatrixTransform()
    rootnode.setMatrix(osg.Matrix.rotate(osg.inDegrees(30.0),1.0,0.0,0.0))
    rootnode.addChild(model)
    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)
    # set the scene to render
    viewer.setSceneData(rootnode)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    # viewer.setUpViewOnSingleScreen(1)
    # normal viewer usage.
    return viewer.run()
class cOSG :
    cOSG(HWND hWnd)
    ~cOSG()

    InitOSG = void(str filename)
    InitManipulators = void(void)
    InitSceneGraph = void(void)
    InitCameraConfig = void(void)
    SetupWindow = void(void)
    SetupCamera = void(void)
    PreFrameUpdate = void(void)
    PostFrameUpdate = void(void)
    def Done(value):
         mDone = value 
    bool Done(void)  return mDone 
    #static void Render(void* ptr)

    def getViewer():

         return mViewer 
    mDone = bool()
    m_ModelName = str()
    m_hWnd = HWND()
    mViewer = osgViewer.Viewer*()
    mRoot = osg.Group()
    mModel = osg.Node()
    trackball = osgGA.TrackballManipulator()
    keyswitchManipulator = osgGA.KeySwitchMatrixManipulator()
def main(argv):


    
    # Qt requires that we construct the global QApplication before creating any widgets.
    app = QApplication(argc, argv)

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

    useFrameLoopThread = False
    if arguments.read("--no-frame-thread") : useFrameLoopThread = False
    if arguments.read("--frame-thread") : useFrameLoopThread = True

    image = osgQt.QWebViewImage()

    if arguments.argc()>1 : image.navigateTo((arguments[1]))
    else image.navigateTo("http:#www.youtube.com/")

    hints = osgWidget.GeometryHints(osg.Vec3(0.0,0.0,0.0),
                                   osg.Vec3(1.0,0.0,0.0),
                                   osg.Vec3(0.0,0.0,1.0),
                                   osg.Vec4(1.0,1.0,1.0,1.0),
                                   osgWidget.GeometryHints.RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO)


    browser = osgWidget.Browser()
    browser.assign(image, hints)

    # image.focusBrowser(True)

    viewer = osgViewer.Viewer(arguments)
    viewer.setSceneData(browser)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler(osgViewer.StatsHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()

    if useFrameLoopThread :
        # create a thread to run the viewer's frame loop
        viewerThread = ViewerFrameThread(viewer, True)
        viewerThread.startThread()

        # now start the standard Qt event loop, then exists when the viewerThead sends the QApplication.exit() signal.
        return QApplication.exec()

    else:
        # run the frame loop, interleaving Qt and the main OSG frame loop
        while  not viewer.done() :
            # process Qt events - this handles both events and paints the browser image
            QCoreApplication.processEvents(QEventLoop.AllEvents, 100)

            viewer.frame()

        return 0
Example #6
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().setApplicationName(arguments.getApplicationName())
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" example provides an interactive viewer for visualising point clouds..")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("--snow <density>","Set the snow with a density between 0 and 1.0")
    arguments.getApplicationUsage().addCommandLineOption("--rain <density>","")
    arguments.getApplicationUsage().addCommandLineOption("--particleSize <size>","")
    arguments.getApplicationUsage().addCommandLineOption("--particleColour <red> <green> <blue> <alpha>","")
    arguments.getApplicationUsage().addCommandLineOption("--wind <x> <y> <z>","Set the wind speed in model coordinates")
    arguments.getApplicationUsage().addCommandLineOption("--particleSpeed <float>","Set the particle speed")
    arguments.getApplicationUsage().addCommandLineOption("--nearTransition <distance>","Set the near transistion distance")
    arguments.getApplicationUsage().addCommandLineOption("--farTransition  <distance>","Set the far transistion distance")
    arguments.getApplicationUsage().addCommandLineOption("--particleDensity <density>","Set the particle density")
    arguments.getApplicationUsage().addCommandLineOption("--cellSize <x> <y> <z>","Set the cell size in model coordinates")
    arguments.getApplicationUsage().addCommandLineOption("--fogDensity <density>","Set the fog density")
    arguments.getApplicationUsage().addCommandLineOption("--fogColour <red> <green> <blue> <alpha>","Set fog colour.")
    arguments.getApplicationUsage().addCommandLineOption("-useFarLineSegments","Switch on the use of line segments")
    

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

    # 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 )
def main(argv):

    
    viewer = osgViewer.Viewer()

    wm = osgWidget.WindowManager(
        viewer,
        WINDOW_WIDTH,
        WINDOW_HEIGHT,
        MASK_2D
        )

    menu = osgWidget.Box("menu", osgWidget.Box.HORIZONTAL)

    menu.addWidget(ColorLabelMenu("Choose EaseMotion"))
    menu.getBackground().setColor(1.0, 1.0, 1.0, 1.0)
    menu.setPosition(15.0, 15.0, 0.0)

    wm.addChild(menu)

    group = osg.Group()
    geode = osg.Geode()
    mt = osg.MatrixTransform()

    geode.addDrawable(osg.ShapeDrawable(osg.Sphere(osg.Vec3(), 4.0)))

    EASE_MOTION_SAMPLER = EaseMotionSampler(osg.Vec3(50.0, 0.0, 0.0))
    EASE_MOTION_GEODE   = osg.Geode()

    mt.addChild(geode)
    mt.setUpdateCallback(EASE_MOTION_SAMPLER)
    mt.setNodeMask(MASK_3D)

    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.getCameraManipulator().setHomePosition(
        osg.Vec3d(0.0, 0.0, 200.0),
        osg.Vec3d(20.0, 0.0, 0.0),
        osg.Vec3d(0.0, 1.0, 0.0)
        )
    viewer.home()

    group.addChild(mt)
    group.addChild(EASE_MOTION_GEODE)

    return osgWidget.createExample(viewer, wm, group)
Example #8
0
def main(argv):


    
    arguments = osg.ArgumentParser(argv)
    
    # initialize the viewer.
    viewer = osgViewer.Viewer(arguments)
    
    ds =  viewer.getDisplaySettings() : osg.DisplaySettings: if (viewer.getDisplaySettings()) else instance()
    ds.readCommandLine(arguments)

    model = osgDB.readNodeFiles(arguments)

    if  not model :
        OSG_NOTICE, "No models loaded, please specify a model file on the command line"
        return 1


    OSG_NOTICE, "Stereo ", ds.getStereo()
    OSG_NOTICE, "StereoMode ", ds.getStereoMode()

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

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

    # add camera manipulator
    viewer.setCameraManipulator(osgGA.TrackballManipulator())

    OSG_NOTICE, "KeystoneFileNames.size()=", ds.getKeystoneFileNames().size()
    for(osg.DisplaySettings.FileNames.iterator itr = ds.getKeystoneFileNames().begin()
        not = ds.getKeystoneFileNames().end()
        ++itr)
        OSG_NOTICE, "   keystone filename = ", *itr
Example #9
0
def main(argv):

    
    arguments = osg.ArgumentParser(argv)

    # construct the viewer.
    viewer = osgViewer.CompositeViewer(arguments)
    
    if arguments.argc()<=1 :
        print "Please supply an image filename on the commnand line."
        return 1
    
    filename = arguments[1]
    image = osgDB.readImageFile(filename)
    
    if  not image :
        print "Error: unable able to read image from ", filename
        return 1

    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 = 0
    traits.y = 0
    traits.width = width
    traits.height = height
    traits.windowDecoration = False
    traits.doubleBuffer = True
    
    gc = osg.GraphicsContext.createGraphicsContext(traits)
    if  not gc :
        print "Error: GraphicsWindow has not been created successfully."

    gc.setClearColor(osg.Vec4(0.0,0.0,0.0,1.0))
    gc.setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    trackball = osgGA.TrackballManipulator()
    
    typedef std.vector< osg.Node > Models
    
    models = Models()
    models.push_back(creatQuad("no compression", image, osg.Texture.USE_IMAGE_DATA_FORMAT, osg.Texture.LINEAR))
    models.push_back(creatQuad("ARB compression", image, osg.Texture.USE_ARB_COMPRESSION, osg.Texture.LINEAR))
    models.push_back(creatQuad("DXT1 compression", image, osg.Texture.USE_S3TC_DXT1_COMPRESSION, osg.Texture.LINEAR))
    models.push_back(creatQuad("DXT3 compression", image, osg.Texture.USE_S3TC_DXT3_COMPRESSION, osg.Texture.LINEAR))
    models.push_back(creatQuad("DXT5 compression", image, osg.Texture.USE_S3TC_DXT5_COMPRESSION, osg.Texture.LINEAR))
    
    numX = 1
    numY = 1

    # compute the number of views up and across that are need
        aspectRatio = float(width)/float(height)
        multiplier = sqrtf(float(models.size())/aspectRatio)
        multiplier_x = multiplier*aspectRatio
        multiplier_y = multiplier


        if multiplier_x/ceilf(multiplier_x) : > (multiplier_y/ceilf(multiplier_y)) :
            numX = int(ceilf(multiplier_x))
            numY = int(ceilf(float(models.size())/float(numX)))
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()
Example #11
0
    keys.push_back(osgAnimation.Vec3CubicBezierKeyframe(8, osgAnimation.Vec3CubicBezier(
                                                        v[4], # pos
                                                        v[4] + (v[4] - v[3]),
                                                        v[0] - (v[0] - v[4])
                                                        )))

    callback.start()
    node.setUpdateCallback(callback)
    node.addChild(setupCube())
    return node

int main (int argc, char* argv[])
    arguments = osg.ArgumentParser(argv)
    viewer = osgViewer.Viewer(arguments)

    manipulator = osgGA.TrackballManipulator()
    viewer.setCameraManipulator(manipulator)

    root = osg.Group()
    root.setInitialBound(osg.BoundingSphere(osg.Vec3(10,0,10), 30))
    root.addChild(createAxis())

    node = setupAnimtkNode()
    node.addChild(createAxis())
    root.addChild(node)

    viewer.setSceneData( root )
    viewer.realize()

    while  not viewer.done() :
        viewer.frame()
Example #12
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()
Example #13
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  and  arguments.read("--relative-camera-scene") :
        # Create a test scene with a camera that has a relative reference frame.
        group = osg.Group()

        sphere = osg.Geode()
        sphere.setName("Sphere")
        sphere.addDrawable(osg.ShapeDrawable(osg.Sphere()))

        cube = osg.Geode()
        cube.setName("Cube")
        cube.addDrawable(osg.ShapeDrawable(osg.Box()))

        camera = osg.Camera()
        camera.setRenderOrder(osg.Camera.POST_RENDER)
        camera.setClearMask(GL_DEPTH_BUFFER_BIT)
        camera.setReferenceFrame(osg.Transform.RELATIVE_RF)
        camera.setViewMatrix(osg.Matrix.translate(-2, 0, 0))

        xform = osg.MatrixTransform(osg.Matrix.translate(1, 1, 1))
        xform.addChild(camera)

        group.addChild(sphere)
        group.addChild(xform)
        camera.addChild(cube)

        scene = group

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

    group = dynamic_cast<osg.Group*>(scene)
    if  not group :
        group = osg.Group()
        group.addChild(scene)

    updateText = osgText.Text()

    # add the HUD subgraph.
    group.addChild(createHUD(updateText))

    if arguments.read("--CompositeViewer") :
        view = osgViewer.View()
        # add the handler for doing the picking
        view.addEventHandler(PickHandler(updateText))

        # set the scene to render
        view.setSceneData(group)

        view.setUpViewAcrossAllScreens()

        viewer = osgViewer.CompositeViewer()
        viewer.addView(view)

        return viewer.run()

    else:
        viewer = osgViewer.Viewer()


        # 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 )

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

        # set the scene to render
        viewer.setSceneData(group)

        return viewer.run()
Example #14
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)
Example #15
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().setApplicationName(arguments.getApplicationName())
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" examples illustrates simplification of triangle meshes.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("--ratio <ratio>","Specify the sample ratio","0.5]")
    arguments.getApplicationUsage().addCommandLineOption("--max-error <error>","Specify the maximum error","4.0")
    

    sampleRatio = 0.5
    maxError = 4.0

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

    # read the sample ratio if one is supplied
    while arguments.read("--ratio",sampleRatio) : 
    while arguments.read("--max-error",maxError) : 

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

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

    # read the scene from the list of file specified commandline args.
    loadedModel = osgDB.readNodeFiles(arguments)
  
    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not loadedModel : loadedModel = osgDB.readNodeFile("dumptruck.osgt")
    
    # if no model has been successfully loaded report failure.
    if  not loadedModel : 
        print arguments.getApplicationName(), ": No data loaded"
        return 1
    
    #loadedModel.accept(simplifier)

    keyFlag = 0
    viewer.addEventHandler(KeyboardEventHandler(keyFlag))

    # set the scene to render
    viewer.setSceneData(loadedModel)

    viewer.setCameraManipulator(osgGA.TrackballManipulator())

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

    multiplier = 0.8
    minRatio = 0.001
    ratio = sampleRatio


    while   not viewer.done()  :
        # fire off the cull and draw traversals of the scene.
        viewer.frame()
    
        if keyFlag == 1  or  keyFlag == 2 :
            if keyFlag == 1 : ratio *= multiplier
            if keyFlag == 2 : ratio /= multiplier
            if ratio<minRatio : ratio=minRatio
            
            simplifier = osgUtil.Simplifier(ratio, maxError)

            print "Runing osgUtil.Simplifier with SampleRatio=", ratio, " maxError=", maxError, " ..."
            std.cout.flush()
            
            root = (osg.Node*)loadedModel.clone(osg.CopyOp.DEEP_COPY_ALL)

            root.accept(simplifier)
            
            print "done"
            
            viewer.setSceneData(root)
            keyFlag = 0
    
    return 0



if __name__ == "__main__":
    main(sys.argv)
Example #16
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)
Example #17
0
    # report any errors if they have occurred when parsing the program arguments.
    if arguments.errors() :
        arguments.writeErrorMessages(std.cout)
        return 1
    
    if arguments.argc()<=1 :
        arguments.getApplicationUsage().write(std.cout,osg.ApplicationUsage.COMMAND_LINE_OPTION)
        return 1

    viewer = osgViewer.Viewer()
    
    # 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 )
        if runConvertToVertexAttributes :
            # find any conventional vertex, colour, normal and tex coords arrays and convert to vertex attributes
            ctvaa = ConvertToVertexAttibArrays()
            loadedModel.accept(ctvaa)

    if  not loadedModel : return 1

    if  not outputFileName.empty() :
        osgDB.writeNodeFile(*loadedModel, outputFileName)
        return 0

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

    viewer.setCameraManipulator(osgGA.TrackballManipulator())

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

    viewer.realize()


    if runConvertToVertexAttributes :
        # switch on the uniforms that track the modelview and projection matrices
        windows = osgViewer.Viewer.Windows()
        viewer.getWindows(windows)
        for(osgViewer.Viewer.Windows.iterator itr = windows.begin()
            not = windows.end()
            ++itr)
            (*itr).getState().setUseModelViewAndProjectionUniforms(True)
Example #19
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)
Example #20
0
def main(argv):


    
    # Qt requires that we construct the global QApplication before creating any widgets.
    app = QApplication(argc, argv)

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

    # True = run osgViewer in a separate thread than Qt
    # False = interleave osgViewer and Qt in the main thread
    useFrameLoopThread = False
    if arguments.read("--no-frame-thread") : useFrameLoopThread = False
    if arguments.read("--frame-thread") : useFrameLoopThread = True

    # True = use QWidgetImage
    # False = use QWebViewImage
    useWidgetImage = False
    if arguments.read("--useWidgetImage") : useWidgetImage = True

    # True = use QWebView in a QWidgetImage to compare to QWebViewImage
    # False = make an interesting widget
    useBrowser = False
    if arguments.read("--useBrowser") : useBrowser = True

    # True = use a QLabel for text
    # False = use a QTextEdit for text
    # (only applies if useWidgetImage == True and useBrowser == False)
    useLabel = False
    if arguments.read("--useLabel") : useLabel = True

    # True = make a Qt window with the same content to compare to 
    # QWebViewImage/QWidgetImage
    # False = use QWebViewImage/QWidgetImage (depending on useWidgetImage)
    sanityCheck = False
    if arguments.read("--sanityCheck") : sanityCheck = True

    # Add n floating windows inside the QGraphicsScene.
    numFloatingWindows = 0
    while arguments.read("--numFloatingWindows", numFloatingWindows) :

    # True = Qt widgets will be displayed on a quad inside the 3D scene
    # False = Qt widgets will be an overlay over the scene (like a HUD)
    inScene = True
    if arguments.read("--fullscreen") :  inScene = False 


    root = osg.Group()

    if  not useWidgetImage :
        #-------------------------------------------------------------------
        # QWebViewImage test
        #-------------------------------------------------------------------
        # Note: When the last few issues with QWidgetImage are fixed, 
        # QWebViewImage and this if  :  section can be removed since 
        # QWidgetImage can display a QWebView just like QWebViewImage. Use 
        # --useWidgetImage --useBrowser to see that in action.

        if  not sanityCheck :
            image = osgQt.QWebViewImage()

            if arguments.argc()>1 : image.navigateTo((arguments[1]))
            else image.navigateTo("http:#www.youtube.com/")

            hints = osgWidget.GeometryHints(osg.Vec3(0.0,0.0,0.0),
                                           osg.Vec3(1.0,0.0,0.0),
                                           osg.Vec3(0.0,0.0,1.0),
                                           osg.Vec4(1.0,1.0,1.0,1.0),
                                           osgWidget.GeometryHints.RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO)

            browser = osgWidget.Browser()
            browser.assign(image, hints)

            root.addChild(browser)
        else:
            # Sanity check, do the same thing as QGraphicsViewAdapter but in 
            # a separate Qt window.
            webPage = QWebPage()
            webPage.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
            webPage.settings().setAttribute(QWebSettings.PluginsEnabled, True)

            webView = QWebView()
            webView.setPage(webPage)

            if arguments.argc()>1 : webView.load(QUrl(arguments[1]))
            else webView.load(QUrl("http:#www.youtube.com/"))

            graphicsScene = QGraphicsScene()
            graphicsScene.addWidget(webView)

            graphicsView = QGraphicsView()
            graphicsView.setScene(graphicsScene)

            mainWindow = QMainWindow()
            #mainWindow.setLayout(QVBoxLayout)()
            mainWindow.setCentralWidget(graphicsView)
            mainWindow.setGeometry(50, 50, 1024, 768)
            mainWindow.show()
            mainWindow.raise()
    else:
        #-------------------------------------------------------------------
        # QWidgetImage test
        #-------------------------------------------------------------------
        # QWidgetImage still has some issues, some examples are:
        # 
        # 1. Editing in the QTextEdit doesn't work. Also when started with 
        #    --useBrowser, editing in the search field on YouTube doesn't 
        #    work. But that same search field when using QWebViewImage 
        #    works... And editing in the text field in the pop-up getInteger 
        #    dialog works too. All these cases use QGraphicsViewAdapter 
        #    under the hood, so why do some work and others don't?
        #
        #    a) osgQtBrowser --useWidgetImage [--fullscreen] (optional)
        #    b) Try to click in the QTextEdit and type, or to select text
        #       and drag-and-drop it somewhere else in the QTextEdit. These
        #       don't work.
        #    c) osgQtBrowser --useWidgetImage --sanityCheck
        #    d) Try the operations in b), they all work.
        #    e) osgQtBrowser --useWidgetImage --useBrowser [--fullscreen]
        #    f) Try to click in the search field and type, it doesn't work.
        #    g) osgQtBrowser
        #    h) Try the operation in f), it works.
        #
        # 2. Operations on floating windows (--numFloatingWindows 1 or more). 
        #    Moving by dragging the titlebar, clicking the close button, 
        #    resizing them, none of these work. I wonder if it's because the 
        #    OS manages those functions (they're functions of the window 
        #    decorations) so we need to do something special for that? But 
        #    in --sanityCheck mode they work.
        #
        #    a) osgQtBrowser --useWidgetImage --numFloatingWindows 1 [--fullscreen]
        #    b) Try to drag the floating window, click the close button, or
        #       drag its sides to resize it. None of these work.
        #    c) osgQtBrowser --useWidgetImage --numFloatingWindows 1 --sanityCheck
        #    d) Try the operations in b), all they work.
        #    e) osgQtBrowser --useWidgetImage [--fullscreen]
        #    f) Click the button so that the getInteger() dialog is 
        #       displayed, then try to move that dialog or close it with the 
        #       close button, these don't work.
        #    g) osgQtBrowser --useWidgetImage --sanityCheck
        #    h) Try the operation in f), it works.
        #
        # 3. (Minor) The QGraphicsView's scrollbars don't appear when 
        #    using QWidgetImage or QWebViewImage. QGraphicsView is a 
        #    QAbstractScrollArea and it should display scrollbars as soon as
        #    the scene is too large to fit the view.
        #
        #    a) osgQtBrowser --useWidgetImage --fullscreen
        #    b) Resize the OSG window so it's smaller than the QTextEdit.
        #       Scrollbars should appear but don't.
        #    c) osgQtBrowser --useWidgetImage --sanityCheck
        #    d) Try the operation in b), scrollbars appear. Even if you have 
        #       floating windows (by clicking the button or by adding 
        #       --numFloatingWindows 1) and move them outside the view, 
        #       scrollbars appear too. You can't test that case in OSG for 
        #       now because of problem 2 above, but that's pretty cool.
        #
        # 4. (Minor) In sanity check mode, the widget added to the 
        #    QGraphicsView is centered. With QGraphicsViewAdapter, it is not.
        #
        #    a) osgQtBrowser --useWidgetImage [--fullscreen]
        #    b) The QTextEdit and button are not in the center of the image
        #       generated by the QGraphicsViewAdapter.
        #    c) osgQtBrowser --useWidgetImage --sanityCheck
        #    d) The QTextEdit and button are in the center of the 
        #       QGraphicsView.


        widget = 0
        if useBrowser :
            webPage = QWebPage()
            webPage.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
            webPage.settings().setAttribute(QWebSettings.PluginsEnabled, True)

            webView = QWebView()
            webView.setPage(webPage)

            if arguments.argc()>1 : webView.load(QUrl(arguments[1]))
            else webView.load(QUrl("http:#www.youtube.com/"))

            widget = webView
        else:
            widget = QWidget()
            widget.setLayout(QVBoxLayout)()

            text = QString("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque velit turpis, euismod ac ultrices et, molestie non nisi. Nullam egestas dignissim enim, quis placerat nulla suscipit sed. Donec molestie elementum risus sit amet sodales. Nunc consectetur congue neque, at viverra massa pharetra fringilla. Integer vitae mi sem. Donec dapibus semper elit nec sollicitudin. Vivamus egestas ultricies felis, in mollis mi facilisis quis. Nam suscipit bibendum eros sed cursus. Suspendisse mollis suscipit hendrerit. Etiam magna eros, convallis non congue vel, faucibus ac augue. Integer ante ante, porta in ornare ullamcorper, congue nec nibh. Etiam congue enim vitae enim sollicitudin fringilla. Mauris mattis, urna in fringilla dapibus, ipsum sem feugiat purus, ac hendrerit felis arcu sed sapien. Integer id velit quam, sit amet dignissim tortor. Sed mi tortor, placerat ac luctus id, tincidunt et urna. Nulla sed nunc ante.Sed ut sodales enim. Ut sollicitudin ultricies magna, vel ultricies ante venenatis id. Cras luctus mi in lectus rhoncus malesuada. Sed ac sollicitudin nisi. Nunc venenatis congue quam, et suscipit diam consectetur id. Donec vel enim ac enim elementum bibendum ut quis augue. Nulla posuere suscipit dolor, id convallis tortor congue eu. Vivamus sagittis consectetur dictum. Duis a ante quis dui varius fermentum. In hac habitasse platea dictumst. Nam dapibus dolor eu felis eleifend in scelerisque dolor ultrices. Donec arcu lectus, fringilla ut interdum non, tristique id dolor. Morbi sagittis sagittis volutpat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis venenatis ultrices euismod.Nam sit amet convallis libero. Integer lectus urna, eleifend et sollicitudin non, porttitor vel erat. Vestibulum pulvinar egestas leo, a porttitor turpis ullamcorper et. Vestibulum in ornare turpis. Ut nec libero a sem mattis iaculis quis id purus. Praesent ante neque, dictum vitae pretium vel, iaculis luctus dui. Etiam luctus tellus vel nunc suscipit a ullamcorper nisl semper. Nunc dapibus, eros in sodales dignissim, orci lectus egestas felis, sit amet vehicula tortor dolor eu quam. Vivamus pellentesque convallis quam aliquet pellentesque. Phasellus facilisis arcu ac orci fringilla aliquet. Donec sed euismod augue. Duis eget orci sit amet neque tempor fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae In hac habitasse platea dictumst. Duis sollicitudin, lacus ac pellentesque lacinia, lacus magna pulvinar purus, pulvinar porttitor est nibh quis augue.Duis eleifend, massa sit amet mattis fringilla, elit turpis venenatis libero, sed convallis turpis diam sit amet ligula. Morbi non dictum turpis. Integer porttitor condimentum elit, sit amet sagittis nibh ultrices sit amet. Mauris ac arcu augue, id aliquet mauris. Donec ultricies urna id enim accumsan at pharetra dui adipiscing. Nunc luctus rutrum molestie. Curabitur libero ipsum, viverra at pulvinar ut, porttitor et neque. Aliquam sit amet dolor et purus sagittis adipiscing. Nam sit amet hendrerit sem. Etiam varius, ligula non ultricies dignissim, sapien dui commodo urna, eu vehicula enim nunc molestie augue. Fusce euismod, erat vitae pharetra tempor, quam eros tincidunt lorem, ut iaculis ligula erat vitae nibh. Aenean eu ultricies dolor. Curabitur suscipit viverra bibendum.Sed egestas adipiscing mi in egestas. Proin in neque in nibh blandit consequat nec quis tortor. Vestibulum sed interdum justo. Sed volutpat velit vitae elit pulvinar aliquam egestas elit rutrum. Proin lorem nibh, bibendum vitae sollicitudin condimentum, pulvinar ut turpis. Maecenas iaculis, mauris in consequat ultrices, ante erat blandit mi, vel fermentum lorem turpis eget sem. Integer ultrices tristique erat sit amet volutpat. In sit amet diam et nunc congue pellentesque at in dolor. Mauris eget orci orci. Integer posuere augue ornare tortor tempus elementum. Quisque iaculis, nunc ac cursus fringilla, magna elit cursus eros, id feugiat diam eros et tellus. Etiam consectetur ultrices erat quis rhoncus. Mauris eu lacinia neque. Curabitur suscipit feugiat tellus in dictum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed aliquam tempus ante a tempor. Praesent viverra erat quis sapien pretium rutrum. Praesent dictum scelerisque venenatis.Proin bibendum lectus eget nisl lacinia porta. Morbi eu erat in sapien malesuada vulputate. Cras non elit quam. Ut dictum urna quis nisl feugiat ac sollicitudin libero luctus. Donec leo mauris, varius at luctus eget, placerat quis arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae Etiam tristique, mauris ut lacinia elementum, mauris erat consequat massa, ac gravida nisi tellus vitae purus. Curabitur consectetur ultricies commodo. Cras pulvinar orci nec enim adipiscing tristique. Ut ornare orci id est fringilla sit amet blandit libero pellentesque. Vestibulum tincidunt sapien ut enim venenatis vestibulum ultricies ipsum tristique. Mauris tempus eleifend varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vitae dui ac quam gravida semper. In ac enim ac ligula rutrum porttitor.Integer dictum sagittis leo, at convallis sapien facilisis eget. Etiam cursus bibendum tortor, faucibus aliquam lectus ullamcorper sed. Nulla pulvinar posuere quam, ut sagittis ligula tincidunt ut. Nulla convallis velit ut enim condimentum pulvinar. Quisque gravida accumsan scelerisque. Proin pellentesque nisi cursus tortor aliquet dapibus. Duis vel eros orci. Sed eget purus ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ullamcorper porta congue. Nunc id velit ut neque malesuada consequat in eu nisi. Nulla facilisi. Quisque pellentesque magna vitae nisl euismod ac accumsan tellus feugiat.Nulla facilisi. Integer quis orci lectus, non aliquam nisi. Vivamus varius porta est, ac porttitor orci blandit mattis. Sed dapibus facilisis dapibus. Duis tincidunt leo ac tortor faucibus hendrerit. Morbi sit amet sapien risus, vel luctus enim. Aliquam sagittis nunc id purus aliquam lobortis. Duis posuere viverra dui, sit amet convallis sem vulputate at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pellentesque, lectus id imperdiet commodo, diam diam faucibus lectus, sit amet vestibulum tortor lacus viverra eros.Maecenas nec augue lectus. Duis nec arcu eget lorem tempus sollicitudin suscipit vitae arcu. Nullam vitae mauris lectus. Vivamus id risus neque, dignissim vehicula diam. Cras rhoncus velit sed velit iaculis ac dignissim turpis luctus. Suspendisse potenti. Sed vitae ligula a ligula ornare rutrum sit amet ut quam. Duis tincidunt, nibh vitae iaculis adipiscing, dolor orci cursus arcu, vel congue tortor quam eget arcu. Suspendisse tellus felis, blandit ac accumsan vitae, fringilla id lorem. Duis tempor lorem mollis est congue ut imperdiet velit laoreet. Nullam interdum cursus mollis. Pellentesque non mauris accumsan elit laoreet viverra ut at risus. Proin rutrum sollicitudin sem, vitae ultricies augue sagittis vel. Cras quis vehicula neque. Aliquam erat volutpat. Aliquam erat volutpat. Praesent non est erat, accumsan rutrum lacus. Pellentesque tristique molestie aliquet. Cras ullamcorper facilisis faucibus. In non lorem quis velit lobortis pulvinar.Phasellus non sem ipsum. Praesent ut libero quis turpis viverra semper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In hac habitasse platea dictumst. Donec at velit tellus. Fusce commodo pharetra tincidunt. Proin lacus enim, fringilla a fermentum ut, vestibulum ut nibh. Duis commodo dolor vel felis vehicula at egestas neque bibendum. Phasellus malesuada dictum ante in aliquam. Curabitur interdum semper urna, nec placerat justo gravida in. Praesent quis mauris massa. Pellentesque porttitor lacinia tincidunt. Phasellus egestas viverra elit vel blandit. Sed dapibus nisi et lectus pharetra dignissim. Mauris hendrerit lectus nec purus dapibus condimentum. Sed ac eros nulla. Aenean semper sapien a nibh aliquam lobortis. Aliquam elementum euismod sapien, in dapibus leo dictum et. Pellentesque augue neque, ultricies non viverra eu, tincidunt ac arcu. Morbi ut porttitor lectus.")

            if useLabel :
                label = QLabel(text)
                label.setWordWrap(True)
                label.setTextInteractionFlags(Qt.TextEditorInteraction)

                palette = label.palette()
                palette.setColor(QPalette.Highlight, Qt.darkBlue)
                palette.setColor(QPalette.HighlightedText, Qt.white)
                label.setPalette(palette)

                scrollArea = QScrollArea()
                scrollArea.setWidget(label)

                widget.layout().addWidget(scrollArea)
            else:
                textEdit = QTextEdit(text)
                textEdit.setReadOnly(False)
                textEdit.setTextInteractionFlags(Qt.TextEditable)

                palette = textEdit.palette()
                palette.setColor(QPalette.Highlight, Qt.darkBlue)
                palette.setColor(QPalette.HighlightedText, Qt.white)
                textEdit.setPalette(palette)

                widget.layout().addWidget(textEdit)

            button = MyPushButton("Button")
            widget.layout().addWidget(button)

            widget.setGeometry(0, 0, 800, 600)

        graphicsScene = 0

        if  not sanityCheck :
            widgetImage = osgQt.QWidgetImage(widget)
#if QT_VERSION >= QT_VERSION_CHECK(4, 5, 0) :
            widgetImage.getQWidget().setAttribute(Qt.WA_TranslucentBackground)
#endif
            widgetImage.getQGraphicsViewAdapter().setBackgroundColor(QColor(0, 0, 0, 0))
            #widgetImage.getQGraphicsViewAdapter().resize(800, 600)
            graphicsScene = widgetImage.getQGraphicsViewAdapter().getQGraphicsScene()

            camera = 0        # Will stay NULL in the inScene case.
            quad = osg.createTexturedQuadGeometry(osg.Vec3(0,0,0), osg.Vec3(1,0,0), osg.Vec3(0,1,0), 1, 1)
            geode = osg.Geode()
            geode.addDrawable(quad)

            mt = osg.MatrixTransform()

            texture = osg.Texture2D(widgetImage)
            texture.setResizeNonPowerOfTwoHint(False)
            texture.setFilter(osg.Texture.MIN_FILTER,osg.Texture.LINEAR)
            texture.setWrap(osg.Texture.WRAP_S, osg.Texture.CLAMP_TO_EDGE)
            texture.setWrap(osg.Texture.WRAP_T, osg.Texture.CLAMP_TO_EDGE)
            mt.getOrCreateStateSet().setTextureAttributeAndModes(0, texture, osg.StateAttribute.ON)

            handler = osgViewer.InteractiveImageHandler*() 
            if inScene :
                mt.setMatrix(osg.Matrix.rotate(osg.Vec3(0,1,0), osg.Vec3(0,0,1)))
                mt.addChild(geode)

                handler = osgViewer.InteractiveImageHandler(widgetImage)
            else    # fullscreen
                # The HUD camera's viewport needs to follow the size of the 
                # window. MyInteractiveImageHandler will make sure of this.
                # As for the quad and the camera's projection, setting the 
                # projection resize policy to FIXED takes care of them, so
                # they can stay the same: (0,1,0,1) with a quad that fits.

                # Set the HUD camera's projection and viewport to match the screen.
                camera = osg.Camera()
                camera.setProjectionResizePolicy(osg.Camera.FIXED)
                camera.setProjectionMatrix(osg.Matrix.ortho2D(0,1,0,1))
                camera.setReferenceFrame(osg.Transform.ABSOLUTE_RF)
                camera.setViewMatrix(osg.Matrix.identity())
                camera.setClearMask(GL_DEPTH_BUFFER_BIT)
                camera.setRenderOrder(osg.Camera.POST_RENDER)
                camera.addChild(geode)
                camera.setViewport(0, 0, 1024, 768)

                mt.addChild(camera)

                handler = osgViewer.InteractiveImageHandler(widgetImage, texture, camera)

            mt.getOrCreateStateSet().setMode(GL_LIGHTING, osg.StateAttribute.OFF)
            mt.getOrCreateStateSet().setMode(GL_BLEND, osg.StateAttribute.ON)
            mt.getOrCreateStateSet().setRenderingHint(osg.StateSet.TRANSPARENT_BIN)
            mt.getOrCreateStateSet().setAttribute(osg.Program)()

            overlay = osg.Group()
            overlay.addChild(mt)

            root.addChild(overlay)
            
            quad.setEventCallback(handler)
            quad.setCullCallback(handler)
        else:
            # Sanity check, do the same thing as QWidgetImage and 
            # QGraphicsViewAdapter but in a separate Qt window.

            graphicsScene = QGraphicsScene()
            graphicsScene.addWidget(widget)

            graphicsView = QGraphicsView()
            graphicsView.setScene(graphicsScene)

            mainWindow = QMainWindow()
            mainWindow.setCentralWidget(graphicsView)
            mainWindow.setGeometry(50, 50, 1024, 768)
            mainWindow.show()
            mainWindow.raise()

        # Add numFloatingWindows windows to the graphicsScene.
        for (unsigned int i = 0 i < (unsigned int)numFloatingWindows ++i)
            window = QWidget(0, Qt.Window)
            window.setWindowTitle(QString("Window %1").arg(i))
            window.setLayout(QVBoxLayout)()
            window.layout().addWidget(QLabel(QString("This window %1").arg(i)))
            window.layout().addWidget(MyPushButton(QString("Button in window %1").arg(i)))
            window.setGeometry(100, 100, 300, 300)

            proxy = QGraphicsProxyWidget(0, Qt.Window)
            proxy.setWidget(window)
            proxy.setFlag(QGraphicsItem.ItemIsMovable, True)

            graphicsScene.addItem(proxy)


    root.addChild(osgDB.readNodeFile("cow.osg.(15,0,5).trans.(0.1,0.1,0.1).scale"))

    viewer = osgViewer.Viewer(arguments)
    viewer.setSceneData(root)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler(osgGA.StateSetManipulator(root.getOrCreateStateSet()))
    viewer.addEventHandler(osgViewer.StatsHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()

    viewer.setUpViewInWindow(50, 50, 1024, 768)
    viewer.getEventQueue().windowResize(0, 0, 1024, 768)

    if useFrameLoopThread :
        # create a thread to run the viewer's frame loop
        viewerThread = ViewerFrameThread(viewer, True)
        viewerThread.startThread()

        # now start the standard Qt event loop, then exists when the viewerThead sends the QApplication.exit() signal.
        return QApplication.exec()

    else:
        # run the frame loop, interleaving Qt and the main OSG frame loop
        while  not viewer.done() :
            # process Qt events - this handles both events and paints the browser image
            QCoreApplication.processEvents(QEventLoop.AllEvents, 100)

            viewer.frame()

        return 0
Example #21
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()