def createSpotLightDecoratorState(lightNum, textureUnit):

    
    stateset = osg.StateSet()
    
    stateset.setMode(GL_LIGHT0+lightNum, osg.StateAttribute.ON)

    centerColour = osg.Vec4(1.0,1.0,1.0,1.0)
    ambientColour = osg.Vec4(0.05,0.05,0.05,1.0) 

    # set up spot light texture
    texture = osg.Texture2D()
    texture.setImage(createSpotLightImage(centerColour, ambientColour, 64, 1.0))
    texture.setBorderColor(osg.Vec4(ambientColour))
    texture.setWrap(osg.Texture.WRAP_S,osg.Texture.CLAMP_TO_BORDER)
    texture.setWrap(osg.Texture.WRAP_T,osg.Texture.CLAMP_TO_BORDER)
    texture.setWrap(osg.Texture.WRAP_R,osg.Texture.CLAMP_TO_BORDER)
    
    stateset.setTextureAttributeAndModes(textureUnit, texture, osg.StateAttribute.ON)
    
    # set up tex gens
    stateset.setTextureMode(textureUnit, GL_TEXTURE_GEN_S, osg.StateAttribute.ON)
    stateset.setTextureMode(textureUnit, GL_TEXTURE_GEN_T, osg.StateAttribute.ON)
    stateset.setTextureMode(textureUnit, GL_TEXTURE_GEN_R, osg.StateAttribute.ON)
    stateset.setTextureMode(textureUnit, GL_TEXTURE_GEN_Q, osg.StateAttribute.ON)
    
    return stateset
Example #2
0
    def loadSlide(new_ndx):

        
        if new_ndx == _currentFile :
            return

        _currentFile = new_ndx
        if _currentFile < 0 :
            _currentFile = _files.size() - 1
        elif _currentFile >= static_cast<int>(_files.size()) :
            _currentFile = 0

        obj = osgDB.readRefObjectFile(_files[_currentFile], _options)
        tex = dynamic_cast<osg.Texture*>(obj)
        if  not tex : 
            stream = dynamic_cast<osg.ImageStream*>(obj)
            if  not stream :
                stream = dynamic_cast<osg.ImageStream*>(osgDB.readImageFile(_files[_currentFile], _options))

            if stream :
                tex = osg.Texture2D(stream)
                tex.setResizeNonPowerOfTwoHint(False)
        if tex : 
            stream = dynamic_cast<osg.ImageStream*>(tex.getImage(0))
            if stream :
                stream.play()
            v = ReplaceTextureVisitor(tex)
            _node.accept(v)
Example #3
0
def makeStateSet(size):

    
    set = osg.StateSet()

    #/ Setup cool blending
    set.setMode(GL_BLEND, osg.StateAttribute.ON)
    fn = osg.BlendFunc()
    fn.setFunction(osg.BlendFunc.SRC_ALPHA, osg.BlendFunc.DST_ALPHA)
    set.setAttributeAndModes(fn, osg.StateAttribute.ON)

    #/ Setup the point sprites
    sprite = osg.PointSprite()
    set.setTextureAttributeAndModes(0, sprite, osg.StateAttribute.ON)

    #/ Give some size to the points to be able to see the sprite
    point = osg.Point()
    point.setSize(size)
    set.setAttribute(point)

    #/ Disable depth test to avoid sort problems and Lighting
    set.setMode(GL_DEPTH_TEST, osg.StateAttribute.OFF)
    set.setMode(GL_LIGHTING, osg.StateAttribute.OFF)

    #/ The texture for the sprites
    tex = osg.Texture2D()
    tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
    set.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)

    return set
Example #4
0
def createTeapot():


    
    geode = osg.Geode()

    # add the teapot to the geode.
    geode.addDrawable( Teapot )()

    # add a reflection map to the teapot.     
    image = osgDB.readImageFile("Images/reflect.rgb")
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)

        texgen = osg.TexGen()
        texgen.setMode(osg.TexGen.SPHERE_MAP)

        stateset = osg.StateSet()
        stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)
        stateset.setTextureAttributeAndModes(0,texgen,osg.StateAttribute.ON)
        
        geode.setStateSet(stateset)
   
    return geode
Example #5
0
def build_world(root):

    

    terrainGeode = osg.Geode()
    # create terrain
        stateset = osg.StateSet()
        image = osgDB.readImageFile("Images/lz.rgb")
        if image :
            texture = osg.Texture2D()
            texture.setImage(image)
            stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)

        terrainGeode.setStateSet( stateset )

        size = 1000 # 10km
        scale = size/39.0 # 10km
        z_scale = scale*3.0

        grid = osg.HeightField()
        grid.allocate(38,39)
        grid.setXInterval(scale)
        grid.setYInterval(scale)

        for(unsigned int r=0r<39++r)
            for(unsigned int c=0c<38++c)
                grid.setHeight(c,r,z_scale*vertex[r+c*39][2])
Example #6
0
 def allocate():
 
     
     if _depth>1 :
         image = osg.Image()
         image.allocateImage(_width, _height, _depth, GL_RGBA, GL_UNSIGNED_BYTE)
         
         texture = osg.Texture3D()
         texture.setImage(image)
         texture.setResizeNonPowerOfTwoHint(False)
         
         return StateAttributeObject(texture)
     if _height>1 :
         image = osg.Image()
         image.allocateImage(_width, _height, 1, GL_RGBA, GL_UNSIGNED_BYTE)
         
         texture = osg.Texture2D()
         texture.setImage(image)
         texture.setResizeNonPowerOfTwoHint(False)
         
         return StateAttributeObject(texture)
     if _width>1 :
         image = osg.Image()
         image.allocateImage(_width, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE)
         
         texture = osg.Texture1D()
         texture.setImage(image)
         texture.setResizeNonPowerOfTwoHint(False)
         
         return StateAttributeObject(texture)
     else:
         throw "Invalid texture size of 0,0,0"
Example #7
0
def creatQuad(name, image, formatMode, minFilter):

    

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

        geode.addDrawable(createTexturedQuadGeometry(
                osg.Vec3(0.0,0.0,0.0),
                osg.Vec3(float(image.s()),0.0,0.0),
                osg.Vec3(0.0,0.0,float(image.t()))))

        geode.setName(name)

        stateset = geode.getOrCreateStateSet()

        texture = osg.Texture2D(image)
        texture.setInternalFormatMode(formatMode)
        texture.setFilter(osg.Texture.MIN_FILTER, minFilter)
        stateset.setTextureAttributeAndModes(0, texture, osg.StateAttribute.ON)
        
        group.addChild(geode)
    
        group.addChild(createHUD(name))
def createBase(center, radius):

    

    geode = osg.Geode()
    
    # set up the texture of the base.
    stateset = osg.StateSet()
    image = osgDB.readImageFile("Images/lz.rgb")
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)
        stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)
    
    geode.setStateSet( stateset )


    grid = osg.HeightField()
    grid.allocate(38,39)
    grid.setOrigin(center+osg.Vec3(-radius,-radius,0.0))
    grid.setXInterval(radius*2.0/(float)(38-1))
    grid.setYInterval(radius*2.0/(float)(39-1))
    
    minHeight = FLT_MAX
    maxHeight = -FLT_MAX


    r = unsigned int()
    for(r=0r<39++r)
        for(unsigned int c=0c<38++c)
            h = vertex[r+c*39][2]
            if h>maxHeight : maxHeight=h
            if h<minHeight : minHeight=h
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.
    rootnode = osgDB.readNodeFiles(arguments)
    
    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not rootnode : rootnode = osgDB.readNodeFile("cessnafire.osgt")
    
    if  not rootnode :
        osg.notify(osg.NOTICE), "Please specify a model filename on the command line."
        return 1
    
    image = osgDB.readImageFile("Images/reflect.rgb")
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)

        texgen = osg.TexGen()
        texgen.setMode(osg.TexGen.SPHERE_MAP)

        texenv = osg.TexEnv()
        texenv.setMode(osg.TexEnv.BLEND)
        texenv.setColor(osg.Vec4(0.3,0.3,0.3,0.3))

        stateset = osg.StateSet()
        stateset.setTextureAttributeAndModes(1,texture,osg.StateAttribute.ON)
        stateset.setTextureAttributeAndModes(1,texgen,osg.StateAttribute.ON)
        stateset.setTextureAttribute(1,texenv)
        
        rootnode.setStateSet(stateset)
    else:
        osg.notify(osg.NOTICE), "unable to load reflect map, model will not be mutlitextured"

    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)
     
    # add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData( rootnode )
    
    # create the windows and run the threads.
    viewer.realize()

    for(unsigned int contextID = 0 
        contextID<osg.DisplaySettings.instance().getMaxNumberOfGraphicsContexts()
        ++contextID)
        textExt = osg.Texture.getExtensions(contextID,False)
        if textExt :
            if  not textExt.isMultiTexturingSupported() :
                print "Warning: multi-texturing not supported by OpenGL drivers, unable to run application."
                return 1
Example #10
0
def createMirrorTexturedState(filename):
    dstate = osg.StateSet();
    dstate.setMode(osg.GL_CULL_FACE,osg.StateAttribute.OFF|osg.StateAttribute.PROTECTED);

    #// set up the texture.
    image = osgDB.readImageFile(filename);
    if (image):
        texture = osg.Texture2D();
        texture.setImage(image);
        dstate.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON|osg.StateAttribute.PROTECTED);

    return dstate;
Example #11
0
def main(argv):

    
    arguments = osg.ArgumentParser( argc, argv )
    
    # Create the texture as both the output of compute shader and the input of a normal quad
    tex2D = osg.Texture2D()
    tex2D.setTextureSize( 512, 512 )
    tex2D.setFilter( osg.Texture2D.MIN_FILTER, osg.Texture2D.LINEAR )
    tex2D.setFilter( osg.Texture2D.MAG_FILTER, osg.Texture2D.LINEAR )
    tex2D.setInternalFormat( GL_R32F )
    tex2D.setSourceFormat( GL_RED )
    tex2D.setSourceType( GL_FLOAT )
    tex2D.bindToImageUnit( 0, osg.Texture.WRITE_ONLY )  # So we can use 'image2D' in the compute shader
    
    # The compute shader can't work with other kinds of shaders
    # It also requires the work group numbers. Setting them to 0 will disable the compute shader
    computeProg = osg.Program()
    computeProg.setComputeGroups( 512/16, 512/16, 1 )
    computeProg.addShader( osg.Shader(osg.Shader.COMPUTE, computeSrc) )
    
    # Create a node for outputting to the texture.
    # It is OK to have just an empty node here, but seems inbuilt uniforms like osg_FrameTime won't work then.
    # TODO: maybe we can have a custom drawable which also will implement  sourceNode = osgDB: if (glMemoryBarrier) else readNodeFile("axes.osgt")
    if   not sourceNode  : sourceNode = osg.Node()
    sourceNode.setDataVariance( osg.Object.DYNAMIC )
    sourceNode.getOrCreateStateSet().setAttributeAndModes( computeProg )
    sourceNode.getOrCreateStateSet().addUniform( osg.Uniform("targetTex", (int)0) )
    sourceNode.getOrCreateStateSet().setTextureAttributeAndModes( 0, tex2D )
    
    # Display the texture on a quad. We will also be able to operate on the data if reading back to CPU side
    geom = osg.createTexturedQuadGeometry(
        osg.Vec3(), osg.Vec3(1.0,0.0,0.0), osg.Vec3(0.0,0.0,1.0) )
    quad = osg.Geode()
    quad.addDrawable( geom )
    quad.getOrCreateStateSet().setMode( GL_LIGHTING, osg.StateAttribute.OFF )
    quad.getOrCreateStateSet().setTextureAttributeAndModes( 0, tex2D )
    
    # Create the scene graph and start the viewer
    scene = osg.Group()
    scene.addChild( sourceNode )
    scene.addChild( quad )
    
    viewer = osgViewer.Viewer()
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    viewer.addEventHandler( osgViewer.StatsHandler )()
    viewer.addEventHandler( osgViewer.WindowSizeHandler )()
    viewer.setSceneData( scene )
    return viewer.run()
Example #12
0
def createMirrorTexturedState(filename):


    
    dstate = osg.StateSet()
    dstate.setMode(GL_CULL_FACE,osg.StateAttribute.OFF|osg.StateAttribute.PROTECTED)

    # set up the texture.
    image = osgDB.readImageFile(filename.c_str())
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)
        dstate.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON|osg.StateAttribute.PROTECTED)

    return dstate
Example #13
0
class Heatmap (osg.Geode) :
    Heatmap(float width, float depth, float maxheight, unsigned int K, unsigned int N, float maximum, float transparency)
    ~Heatmap()

    setData = void(float *buffer, float maxheight, float maximum, float transparency)
    m_K = unsigned int()
    m_N = unsigned int()
    *m_data = float()
    m_img2 = osg.Image()
    m_tex2 = osg.Texture2D()

    colorimg = osg.Image()
    colortex = osg.Texture1D()

    *maximumUniform = osg.Uniform()
    *maxheightUniform = osg.Uniform()
    *transparencyUniform = osg.Uniform()
Example #14
0
def createSectorForImage(image, texmat, s, t, radius, height, length):


    
    flip = image.getOrigin()==osg.Image.TOP_LEFT

    numSegments = 20
    Theta = length/radius
    dTheta = Theta/(float)(numSegments-1)

    ThetaZero = height*s/(t*radius)

    # set up the texture.
    texture = osg.Texture2D()
    texture.setFilter(osg.Texture2D.MIN_FILTER,osg.Texture2D.LINEAR)
    texture.setFilter(osg.Texture2D.MAG_FILTER,osg.Texture2D.LINEAR)
    texture.setWrap(osg.Texture2D.WRAP_S,osg.Texture2D.CLAMP_TO_BORDER)
    texture.setWrap(osg.Texture2D.WRAP_T,osg.Texture2D.CLAMP_TO_BORDER)
    texture.setResizeNonPowerOfTwoHint(False)
    texture.setImage(image)

    # set up the drawstate.
    dstate = osg.StateSet()
    dstate.setMode(GL_CULL_FACE,osg.StateAttribute.OFF)
    dstate.setMode(GL_LIGHTING,osg.StateAttribute.OFF)
    dstate.setTextureAttributeAndModes(0, texture,osg.StateAttribute.ON)
    dstate.setTextureAttribute(0, texmat)

    # set up the geoset.
    geom = osg.Geometry()
    geom.setStateSet(dstate)

    coords = osg.Vec3Array()
    tcoords = osg.Vec2Array()

    i = int()
    angle = -Theta/2.0
    for(i=0
        i<numSegments
        ++i, angle+=dTheta)
        coords.push_back(osg.Vec3(sinf(angle)*radius,cosf(angle)*radius,height*0.5)) # top
        coords.push_back(osg.Vec3(sinf(angle)*radius,cosf(angle)*radius,-height*0.5)) # bottom.

        tcoords.push_back(osg.Vec2(angle/ThetaZero+0.5,  0.0 if (flip) else  1.0)) # top
        tcoords.push_back(osg.Vec2(angle/ThetaZero+0.5,  1.0 if (flip) else  0.0)) # bottom.
Example #15
0
def createSquare(corner, width, height, image):
    
    # set up the Geometry.
    geom = osg.Geometry()

    coords = osg.Vec3Array(4)
    (*coords)[0] = corner
    (*coords)[1] = corner+width
    (*coords)[2] = corner+width+height
    (*coords)[3] = corner+height


    geom.setVertexArray(coords)

    norms = osg.Vec3Array(1)
    (*norms)[0] = width^height
    (*norms)[0].normalize()

    geom.setNormalArray(norms, osg.Array.BIND_OVERALL)

    tcoords = osg.Vec2Array(4)
    (*tcoords)[0].set(0.0,0.0)
    (*tcoords)[1].set(1.0,0.0)
    (*tcoords)[2].set(1.0,1.0)
    (*tcoords)[3].set(0.0,1.0)
    geom.setTexCoordArray(0,tcoords)

    colours = osg.Vec4Array(1)
    (*colours)[0].set(1.0,1.0,1.0,1.0)
    geom.setColorArray(colours, osg.Array.BIND_OVERALL)


    geom.addPrimitiveSet(osg.DrawArrays(osg.PrimitiveSet.QUADS,0,4))

    if image :
        stateset = osg.StateSet()
        texture = osg.Texture2D()
        texture.setImage(image)
        stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)
        stateset.setMode(GL_LIGHTING, osg.StateAttribute.OFF)
        stateset.setMode(GL_BLEND, osg.StateAttribute.ON)
        stateset.setRenderingHint(osg.StateSet.TRANSPARENT_BIN)
        geom.setStateSet(stateset)

    return geom
Example #16
0
def createShapes():

    
    geode = osg.Geode()

    
    # ---------------------------------------
    # Set up a StateSet to texture the objects
    # ---------------------------------------
    stateset = osg.StateSet()

    image = osgDB.readImageFile( "Images/lz.rgb" )
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)
        texture.setFilter(osg.Texture.MIN_FILTER, osg.Texture.LINEAR)
        stateset.setTextureAttributeAndModes(0,texture, osg.StateAttribute.ON)
    
    stateset.setMode(GL_LIGHTING, osg.StateAttribute.ON)
    
    geode.setStateSet( stateset )

    
    radius = 0.8
    height = 1.0
    
    hints = osg.TessellationHints()
    hints.setDetailRatio(0.5)
    
    geode.addDrawable(osg.ShapeDrawable(osg.Sphere(osg.Vec3(0.0,0.0,0.0),radius),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Box(osg.Vec3(2.0,0.0,0.0),2*radius),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Cone(osg.Vec3(4.0,0.0,0.0),radius,height),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Cylinder(osg.Vec3(6.0,0.0,0.0),radius,height),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Capsule(osg.Vec3(8.0,0.0,0.0),radius,height),hints))

    grid = osg.HeightField()
    grid.allocate(38,39)
    grid.setXInterval(0.28)
    grid.setYInterval(0.28)
    
    for(unsigned int r=0r<39++r)
        for(unsigned int c=0c<38++c)
            grid.setHeight(c,r,vertex[r+c*39][2])
Example #17
0
def createEarth():

    
    hints = osg.TessellationHints()
    hints.setDetailRatio(5.0)

    
    sd = osg.ShapeDrawable(osg.Sphere(osg.Vec3(0.0,0.0,0.0), osg.WGS_84_RADIUS_POLAR), hints)
    
    geode = osg.Geode()
    geode.addDrawable(sd)
    
    filename = osgDB.findDataFile("Images/land_shallow_topo_2048.jpg")
    geode.getOrCreateStateSet().setTextureAttributeAndModes(0, osg.Texture2D(osgDB.readImageFile(filename)))
    
    csn = osg.CoordinateSystemNode()
    csn.setEllipsoidModel(osg.EllipsoidModel())
    csn.addChild(geode)
    
    return csn
Example #18
0
def SetObjectTextureState(geodeCurrent, texture):


    
    # retrieve or create a StateSet
    stateTexture = geodeCurrent.getOrCreateStateSet()

    # load texture.jpg as an image
    imgTexture = osgDB.readImageFile( texture )
    
    # if the image is successfully loaded
    if imgTexture :
        # create a two-dimensional texture object
        texCube = osg.Texture2D()

        # set the texture to the loaded image
        texCube.setImage(imgTexture)

        # set the texture to the state
        stateTexture.setTextureAttributeAndModes(0,texCube,osg.StateAttribute.ON)

        # set the state of the current geode
        geodeCurrent.setStateSet(stateTexture)
Example #19
0
                                 osg.Matrix.scale(1.0, 1.0, 1.0)*
                                 osg.Matrix.rotate(osg.inDegrees( tilt ),0.0,0.0,1.0))

    return moonPositioned
# end SolarSystem.createTranslationAndTilt


osg.Geode* SolarSystem.createSpace(  str name,  str textureName )
    spaceSphere = osg.Sphere( osg.Vec3( 0.0, 0.0, 0.0 ), _radiusSpace )

    sSpaceSphere = osg.ShapeDrawable( spaceSphere )

    if   not textureName.empty()  :
        image = osgDB.readImageFile( textureName )
        if  image  :
            sSpaceSphere.getOrCreateStateSet().setTextureAttributeAndModes( 0, osg.Texture2D( image ), osg.StateAttribute.ON )

            # reset the object color to white to allow the texture to set the colour.
            sSpaceSphere.setColor( osg.Vec4(1.0,1.0,1.0,1.0) )

    geodeSpace = osg.Geode()
    geodeSpace.setName( name )

    geodeSpace.addDrawable( sSpaceSphere )

    return( geodeSpace )

# end SolarSystem.createSpace


osg.Geode* SolarSystem.createPlanet( double radius,  str name,  osg.Vec4 color ,  str textureName)
Example #20
0
    

    numIndices = sizeof(myIndices)/sizeof(unsigned short)

    # There are three variants of the DrawElements osg.Primitive, UByteDrawElements which
    # contains unsigned char indices, UShortDrawElements which contains unsigned short indices,
    # and UIntDrawElements which contains ... unsigned int indices.
    # The first parameter to DrawElements is
    polyGeom.addPrimitiveSet(osg.DrawElementsUShort(osg.PrimitiveSet.TRIANGLE_STRIP,numIndices,myIndices))

    # we need to add the texture to the Drawable, we do so by creating a
    # StateSet to contain the Texture2D StateAttribute.
    stateset = osg.StateSet()

    # set up the texture.
    texture = osg.Texture2D()
    texture.setImage(image)

    stateset.setTextureAttributeAndModes(0, texture,osg.StateAttribute.ON)

    polyGeom.setStateSet(stateset)


    # create the Geode (Geometry Node) to contain all our osg.Geometry objects.
    geode = osg.Geode()

    # add the points geometry to the geode.
    geode.addDrawable(polyGeom)

    #return geode
Example #21
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 #22
0
    return g


# 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()
def createDistortionSubgraph(subgraph, clearColour):

    
    distortionNode = osg.Group()

    tex_width = 1024
    tex_height = 1024

    texture = osg.Texture2D()
    texture.setTextureSize(tex_width, tex_height)
    texture.setInternalFormat(GL_RGBA)
    texture.setFilter(osg.Texture2D.MIN_FILTER,osg.Texture2D.LINEAR)
    texture.setFilter(osg.Texture2D.MAG_FILTER,osg.Texture2D.LINEAR)

    # set up the render to texture camera.
        camera = osg.Camera()

        # set clear the color and depth buffer
        camera.setClearColor(clearColour)
        camera.setClearMask(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        # just inherit the main cameras view
        camera.setReferenceFrame(osg.Transform.RELATIVE_RF)
        camera.setProjectionMatrix(osg.Matrixd.identity())
        camera.setViewMatrix(osg.Matrixd.identity())

        # set viewport
        camera.setViewport(0,0,tex_width,tex_height)

        # set the camera to render before the main camera.
        camera.setRenderOrder(osg.Camera.PRE_RENDER)

        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(osg.Camera.FRAME_BUFFER_OBJECT)

        # attach the texture and use it as the color buffer.
        camera.attach(osg.Camera.COLOR_BUFFER, texture)

        # add subgraph to render
        camera.addChild(subgraph)

        distortionNode.addChild(camera)

    # set up the hud camera
        # create the quad to visualize.
        polyGeom = osg.Geometry()

        polyGeom.setSupportsDisplayList(False)

        origin = osg.Vec3(0.0,0.0,0.0)
        xAxis = osg.Vec3(1.0,0.0,0.0)
        yAxis = osg.Vec3(0.0,1.0,0.0)
        height = 1024.0
        width = 1280.0
        noSteps = 50

        vertices = osg.Vec3Array()
        texcoords = osg.Vec2Array()
        colors = osg.Vec4Array()

        bottom = origin
        dx = xAxis*(width/((float)(noSteps-1)))
        dy = yAxis*(height/((float)(noSteps-1)))

        bottom_texcoord = osg.Vec2(0.0,0.0)
        dx_texcoord = osg.Vec2(1.0/(float)(noSteps-1),0.0)
        dy_texcoord = osg.Vec2(0.0,1.0/(float)(noSteps-1))

        int i,j
        for(i=0i<noSteps++i)
            cursor = bottom+dy*(float)i
            texcoord = bottom_texcoord+dy_texcoord*(float)i
            for(j=0j<noSteps++j)
Example #24
0
# node in the scene. The first section starts out the same as previous
# tutorials. Initialize a viewer and build a scene with a single pyramid.

# Declare a group to act as root node of a scene:
root = osg.Group()
pyramidGeode = createPyramid()
root.addChild(pyramidGeode)

# Now for adding a texture. Here we'll declare a texture instance and set
# its data variance as 'DYNAMIC'. (If we don't declare the texture as dynamic,
# some of the osg's optimization routines could remove it.) The texture class
# encapsulates OpenGL texture modes (wrap, filiter, etc.) as well as an
# osg.Image. The code below shows how to read an osg.Image instance from a
# file and associate this image with a texture.

KLN89FaceTexture = osg.Texture2D()

# protect from being optimized away as static state:
KLN89FaceTexture.setDataVariance(osg.Object.DYNAMIC)

# load an image by reading a file:
klnFace = osgDB.readImageFile("KLN89FaceB.tga")
if klnFace is None:
    print " Couldn't find texture, quitting."
    sys.exit(-1)

# Assign the texture to the image we read from file:
KLN89FaceTexture.setImage(klnFace)

# Textures can be associated with rendering StateSets. The next step is to
# create a StateSet, associate and enable our texture with this state set and
Example #25
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("--sprites","Point sprites.")
    arguments.getApplicationUsage().addCommandLineOption("--points","Sets the polygon mode to GL_POINT for front and back faces.")


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

    shader = False
    while arguments.read("--shader") : shader = True

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

    forcePointMode = False
    while arguments.read("--points") :  forcePointMode = True 

    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 no model has been successfully loaded report failure.
    if  not loadedModel : 
        print arguments.getApplicationName(), ": No data loaded"
        return 1

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


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

    stateset = loadedModel.getOrCreateStateSet()
    if usePointSprites :    
        #/ Setup cool blending
        fn = osg.BlendFunc()
        stateset.setAttributeAndModes(fn, osg.StateAttribute.ON)

        #/ Setup the point sprites
        sprite = osg.PointSprite()
        stateset.setTextureAttributeAndModes(0, sprite, osg.StateAttribute.ON)

        #/ The texture for the sprites
        tex = osg.Texture2D()
        tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
        stateset.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)

    if  forcePointMode  :
        #/ Set polygon mode to GL_POINT
        pm = osg.PolygonMode(
            osg.PolygonMode.FRONT_AND_BACK, osg.PolygonMode.POINT )
        stateset.setAttributeAndModes( pm, osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
    

    # register the handler for modifying the point size
    viewer.addEventHandler(KeyboardEventHandler(viewer.getCamera().getOrCreateStateSet()))


    if shader :
        stateset = loadedModel.getOrCreateStateSet()
    
        #################################/
        # vertex shader using just Vec4 coefficients
        char vertexShaderSource[] = 
            "void main(void) \n"
            " \n"
            "\n"
            "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex\n"
            "\n"



        program = osg.Program()
        stateset.setAttribute(program)

        vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource)
        program.addShader(vertex_shader)

#if 0
        #################################
        # fragment shader
        #
        char fragmentShaderSource[] = 
            "void main(void) \n"
            " \n"
            "    gl_FragColor = gl_Color \n"
            "\n"
def main():
   viewer = osgViewer.Viewer()

   # Declare a group to act as root node of a scene:
   root = osg.Group()

   # Declare a box class (derived from shape class) instance
   # This constructor takes an osg.Vec3 to define the center
   #  and a float to define the height, width and depth.
   #  (an overloaded constructor allows you to specify unique
   #   height, width and height values.)
   unitCube = osg.Box( osg.Vec3(0,0,0), 1.0)
   unitCube.setDataVariance(osg.Object.DYNAMIC)

   # Declare an instance of the shape drawable class and initialize 
   #  it with the unitCube shape we created above.
   #  This class is derived from 'drawable' so instances of this
   #  class can be added to Geode instances.
   unitCubeDrawable = osg.ShapeDrawable(unitCube)

   # Declare a instance of the geode class: 
   basicShapesGeode = osg.Geode()

   # Add the unit cube drawable to the geode:
   basicShapesGeode.addDrawable(unitCubeDrawable)

   # Add the goede to the scene:
   root.addChild(basicShapesGeode)

   unitSphere = osg.Sphere( osg.Vec3(0,0,0), 1.0)
   unitSphereDrawable = osg.ShapeDrawable(unitSphere)
   unitSphereDrawable.setColor( osg.Vec4(0.1, 0.1, 0.1, 0.1) )

   unitSphereXForm = osg.PositionAttitudeTransform()
   unitSphereXForm.setPosition(osg.Vec3(3.0,0,0))

   unitSphereGeode = osg.Geode()
   root.addChild(unitSphereXForm)
   unitSphereXForm.addChild(unitSphereGeode)
   unitSphereGeode.addDrawable(unitSphereDrawable)

   pyramidGeode = createPyramid()
   
   pyramidXForm = osg.PositionAttitudeTransform()
   pyramidXForm.setPosition(osg.Vec3(0,-3.0,0))
   root.addChild(pyramidXForm)
   pyramidXForm.addChild(pyramidGeode)

   KLN89FaceTexture = osg.Texture2D()
   # protect from being optimized away as static state:
   KLN89FaceTexture.setDataVariance(osg.Object.DYNAMIC) 
   klnFace = osgDB.readImageFile("../NPS_Data/Textures/KLN89FaceB.tga")
   if klnFace is None:
      print " couldn't find texture, quitting."
      sys.exit(-1)
   
   KLN89FaceTexture.setImage(klnFace)

   # Declare a state set for 'BLEND' texture mode
   blendStateSet = osg.StateSet()

   # Declare a TexEnv instance, set the mode to 'BLEND'
   blendTexEnv = osg.TexEnv()
   blendTexEnv.setMode(osg.TexEnv.BLEND)

   # Turn the attribute of texture 0 'ON'
   blendStateSet.setTextureAttributeAndModes(0,KLN89FaceTexture,osg.StateAttribute.ON)
   # Set the texture texture environment for texture 0 to the 
   #  texture envirnoment we declared above:
   blendStateSet.setTextureAttribute(0,blendTexEnv)

   decalStateSet = osg.StateSet()
   decalTexEnv = osg.TexEnv()
   decalTexEnv.setMode(osg.TexEnv.DECAL)

   decalStateSet.setTextureAttributeAndModes(0,KLN89FaceTexture,osg.StateAttribute.ON)
   decalStateSet.setTextureAttribute(0,decalTexEnv)

   root.setStateSet(blendStateSet)
   unitSphereGeode.setStateSet(decalStateSet)

   # OSG1 viewer.setUpViewer(osgProducer.Viewer.STANDARD_SETTINGS)
   viewer.setSceneData( root )
   viewer.setCameraManipulator(osgGA.TrackballManipulator())
   viewer.realize()

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

   return 0
Example #27
0
        MarbleProgram = osg.Program()
        MarbleProgram.setName( "marble" )
        _programList.push_back( MarbleProgram )
        MarbleVertObj = osg.Shader( osg.Shader.VERTEX )
        MarbleFragObj = osg.Shader( osg.Shader.FRAGMENT )
        MarbleProgram.addShader( MarbleFragObj )
        MarbleProgram.addShader( MarbleVertObj )
        ss.setAttributeAndModes(MarbleProgram, osg.StateAttribute.ON)

        ss.addUniform( osg.Uniform("NoiseTex", TEXUNIT_NOISE) )
        ss.addUniform( osg.Uniform("SineTex", TEXUNIT_SINE) )

#ifdef INTERNAL_3DLABS #[
    # regular GL 1.x texturing for comparison.
    ss = ModelInstance()
    tex0 = osg.Texture2D()
    tex0.setImage( osgDB.readImageFile( "images/3dl-ge100.png" ) )
    ss.setTextureAttributeAndModes(0, tex0, osg.StateAttribute.ON)
#endif #]

    reloadShaderSource()

#ifdef INTERNAL_3DLABS #[
    # add logo overlays
    rootNode.addChild( osgDB.readNodeFile( "3dl_ogl.logo" ) )
#endif #]

    return rootNode

#####################################/
#####################################/
Example #28
0
        texture.setWrap(osg.Texture.WRAP_S, osg.Texture.CLAMP_TO_EDGE)
        texture.setWrap(osg.Texture.WRAP_T, osg.Texture.CLAMP_TO_EDGE)


        pictureQuad.getOrCreateStateSet().setTextureAttributeAndModes(0,
                                                                        texture,
                                                                        osg.StateAttribute.ON)

        return pictureQuad
    else:
        pictureQuad = osg.createTexturedQuadGeometry(pos,
                                           osg.Vec3(width,0.0,0.0),
                                            osg.Vec3(0.0,height,0.0) : osg: if (xyPlane) else Vec3(0.0,0.0,height),
                                           0.0,  1.0 : 0.0 , 1.0, flip ? 0.0 if (flip) else  1.0)

        texture = osg.Texture2D(image)
        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)


        pictureQuad.getOrCreateStateSet().setTextureAttributeAndModes(0,
                    texture,
                    osg.StateAttribute.ON)

        return pictureQuad

#if USE_SDL

class SDLAudioSink (osg.AudioSink) :
Example #29
0
def createLightPointsDatabase():

    
    start = osgSim.LightPoint()
    end = osgSim.LightPoint()

    start._position.set(-500.0,-500.0,0.0)
    start._color.set(1.0,0.0,0.0,1.0)
    
    end._position.set(500.0,-500.0,0.0)
    end._color.set(1.0,1.0,1.0,1.0)
    
    transform = osg.MatrixTransform()
    
    transform.setDataVariance(osg.Object.STATIC)
    transform.setMatrix(osg.Matrix.scale(0.1,0.1,0.1))

    start_delta = osg.Vec3(0.0,10.0,0.0)
    end_delta = osg.Vec3(0.0,10.0,1.0)

    noStepsX = 100
    noStepsY = 100

#     osgSim.BlinkSequence* bs = osgSim.BlinkSequence()
#     bs.addPulse(1.0,osg.Vec4(1.0,0.0,0.0,1.0))
#     bs.addPulse(0.5,osg.Vec4(0.0,0.0,0.0,0.0)) # off
#     bs.addPulse(1.5,osg.Vec4(1.0,1.0,0.0,1.0))
#     bs.addPulse(0.5,osg.Vec4(0.0,0.0,0.0,0.0)) # off
#     bs.addPulse(1.0,osg.Vec4(1.0,1.0,1.0,1.0))
#     bs.addPulse(0.5,osg.Vec4(0.0,0.0,0.0,0.0)) # off
    

#    osgSim.Sector* sector = osgSim.ConeSector(osg.Vec3(0.0,0.0,1.0),osg.inDegrees(45.0),osg.inDegrees(45.0))
#    osgSim.Sector* sector = osgSim.ElevationSector(-osg.inDegrees(45.0),osg.inDegrees(45.0),osg.inDegrees(45.0))
#    osgSim.Sector* sector = osgSim.AzimSector(-osg.inDegrees(45.0),osg.inDegrees(45.0),osg.inDegrees(90.0))
#     osgSim.Sector* sector = osgSim.AzimElevationSector(osg.inDegrees(180),osg.inDegrees(90), # azim range
#                                                                 osg.inDegrees(0.0),osg.inDegrees(90.0), # elevation range
#                                                                 osg.inDegrees(5.0))

    for(int i=0i<noStepsY++i)

#         osgSim.BlinkSequence* local_bs = osgSim.BlinkSequence(*bs)
#         local_bs.setSequenceGroup(osgSim.BlinkSequence.SequenceGroup((double)i*0.1))        
#         start._blinkSequence = local_bs

#        start._sector = sector

        lpn = osgSim.LightPointNode()

        #
        set = lpn.getOrCreateStateSet()

        if usePointSprites :
            lpn.setPointSprite()

            # Set point sprite texture in LightPointNode StateSet.
            tex = osg.Texture2D()
            tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
            set.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)

        #set.setMode(GL_BLEND, osg.StateAttribute.ON)
        #osg.BlendFunc *fn = osg.BlendFunc()
        #fn.setFunction(osg.BlendFunc.SRC_ALPHA, osg.BlendFunc.DST_ALPHA)
        #set.setAttributeAndModes(fn, osg.StateAttribute.ON)
        #

        addToLightPointNode(*lpn,start,end,noStepsX)
        
        start._position += start_delta
        end._position += end_delta
        
        transform.addChild(lpn)    
Example #30
0
#include <osg/State>

void DepthPeeling.createPeeling()
    numTiles = ceil(sqrt(double(_numPasses)))

    # cleanup any previous scene data
    _root.removeChildren(0, _root.getNumChildren())

    # create depth textures
    _depthTextures.clear()
    _depthTextures.resize(3)
    for (unsigned int i = 0 i < 3 ++i) 
#ifdef USE_TEXTURE_RECTANGLE
        _depthTextures[i] = osg.TextureRectangle()
#else:
        _depthTextures[i] = osg.Texture2D()
#endif
        _depthTextures[i].setTextureSize(_texWidth, _texHeight)

        _depthTextures[i].setFilter(osg.Texture.MIN_FILTER, osg.Texture.NEAREST)
        _depthTextures[i].setFilter(osg.Texture.MAG_FILTER, osg.Texture.NEAREST)
        _depthTextures[i].setWrap(osg.Texture.WRAP_S, osg.Texture.CLAMP_TO_BORDER)
        _depthTextures[i].setWrap(osg.Texture.WRAP_T, osg.Texture.CLAMP_TO_BORDER)

#ifdef USE_PACKED_DEPTH_STENCIL
        _depthTextures[i].setInternalFormat(GL_DEPTH24_STENCIL8_EXT)
        _depthTextures[i].setSourceFormat(GL_DEPTH_STENCIL_EXT)
        _depthTextures[i].setSourceType(GL_UNSIGNED_INT_24_8_EXT)
#else:
        _depthTextures[i].setInternalFormat(GL_DEPTH_COMPONENT)
#endif