コード例 #1
0
    def init(geom):

        
        pos = dynamic_cast<osg.Vec3Array*>(geom.getVertexArray())
        if  not pos : 
            osg.notify(osg.WARN), "RigTransformHardware no vertex array in the geometry ", geom.getName()
            return False

        if  not geom.getSkeleton() : 
            osg.notify(osg.WARN), "RigTransformHardware no skeleting set in geometry ", geom.getName()
            return False

        mapVisitor = osgAnimation.BoneMapVisitor()
        geom.getSkeleton().accept(mapVisitor)
        bm = mapVisitor.getBoneMap()

        if  not createPalette(pos.size(),bm, geom.getVertexInfluenceSet().getVertexToBoneList()) :
            return False

        attribIndex = 11
        nbAttribs = getNumVertexAttrib()

        # use a global program for all avatar
        if  not program.valid() : 
            program = osg.Program()
            program.setName("HardwareSkinning")
            if  not _shader.valid() :
                _shader = osg.Shader.readShaderFile(osg.Shader.VERTEX,"shaders/skinning.vert")

            if  not _shader.valid() : 
                osg.notify(osg.WARN), "RigTransformHardware can't load VertexShader"
                return False

            # replace max matrix by the value from uniform
                str = _shader.getShaderSource()
                toreplace = str("MAX_MATRIX")
                start = str.find(toreplace)
                ss = strstream()
                ss, getMatrixPaletteUniform().getNumElements()
                str.replace(start, toreplace.size(), ss.str())
                _shader.setShaderSource(str)
                osg.notify(osg.INFO), "Shader ", str

            program.addShader(_shader)

            for (int i = 0 i < nbAttribs i++)
                ss = strstream()
                ss, "boneWeight", i
                program.addBindAttribLocation(ss.str(), attribIndex + i)

                osg.notify(osg.INFO), "set vertex attrib ", ss.str()
コード例 #2
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()
コード例 #3
0
def createColorToGreyscaleStateSet():

    
    stateset = osg.StateSet()

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

    fragSource = 
        "uniform sampler2D baseTexture\n"
        "uniform mat4 colorMatrix\n"
        "void main(void)\n"
        "\n"
        "    vec4 color = texture2D( baseTexture, gl_TexCoord[0].st )\n"
        "    gl_FragColor = colorMatrix * color\n"
        "\n"
コード例 #4
0
def createShader():

    
    pgm = osg.Program()
    pgm.setName( "osgshader2 demo" )

    pgm.addShader( osg.Shader( osg.Shader.VERTEX,   vertSource ) )
    pgm.addShader( osg.Shader( osg.Shader.FRAGMENT, fragSource ) )

#ifdef ENABLE_GEOMETRY_SHADER
    pgm.addShader( osg.Shader( osg.Shader.GEOMETRY, geomSource ) )
    pgm.setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 4 )
    pgm.setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS )
    pgm.setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_LINE_STRIP )
#endif

    return pgm
コード例 #5
0
def createProgram():


    

  vp = strstream()
  vp, "#version 420 compatibility\n", "\n", "void main(void)\n", "\n", "    gl_Position = ftransform()\n", "\n"
  vpShader = osg.Shader( osg.Shader.VERTEX, vp.str() )



  fp = strstream()
  fp, "#version 420 compatibility\n", "\n", "layout(binding = 0) uniform atomic_uint acRed\n", "layout(binding = 0, offset = 4) uniform atomic_uint acGreen\n", "layout(binding = 2) uniform atomic_uint acBlue\n", "\n", "uniform float invNumPixel\n", "\n", "void main(void)\n", "\n", "    float r = float(atomicCounterIncrement(acRed)) * invNumPixel\n", "    float g = float(atomicCounterIncrement(acGreen)) * invNumPixel\n", "    float b = float(atomicCounterIncrement(acBlue)) * invNumPixel\n", "    gl_FragColor = vec4(r, g, b, 1.0)\n", "\n", "\n"
  fpShader = osg.Shader( osg.Shader.FRAGMENT, fp.str() )

  program = osg.Program()
  program.addShader(vpShader)
  program.addShader(fpShader)

  return program
コード例 #6
0
            switch(_operation) 
                case SIN : uniform.set( sine ) break
        _operation = Operation()


int main(int, char **)
    # construct the viewer.
    viewer = osgViewer.Viewer()

    # use a geode with a Box ShapeDrawable
    basicModel = osg.Geode()
    basicModel.addDrawable(osg.ShapeDrawable(osg.Box(osg.Vec3(0.0,0.0,0.0),1.0)))

    # create the "blocky" shader, a simple animation test
    ss = basicModel.getOrCreateStateSet()
    program = osg.Program()
    program.setName( "blocky" )
    program.addShader( osg.Shader( osg.Shader.VERTEX, blockyVertSource ) )
    program.addShader( osg.Shader( osg.Shader.FRAGMENT, blockyFragSource ) )
    ss.setAttributeAndModes(program, osg.StateAttribute.ON)

    # attach some animated Uniform variable to the state set
    SineUniform = osg.Uniform( "Sine", 0.0 )
    ss.addUniform( SineUniform )
    SineUniform.setUpdateCallback(AnimateCallback(AnimateCallback.SIN))

    # run the osg.Viewer using our model
    viewer.setSceneData( basicModel )
    return viewer.run()

#EOF
コード例 #7
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"
コード例 #8
0
        "varying vec2 texcoord \n"
        "varying float intensity \n"
        "varying float red_intensity \n"
        "\n"
        "void main(void) \n"
        " \n"
        "   vec4 finalColor = texture2D( baseTexture, texcoord) \n"
        "   vec4 color = finalColor * intensity\n"
        "   color.w = finalColor.w\n"
        "   color.x *= red_intensity\n"
        "   gl_FragColor = color\n"
        "\n"
    


    pgm = osg.Program()
    pgm.setName( "osgshader2 demo" )

    pgm.addShader( osg.Shader( osg.Shader.VERTEX,   vertSource ) )
    pgm.addShader( osg.Shader( osg.Shader.FRAGMENT, fragSource ) )

    pgm.addShader( osg.Shader( osg.Shader.GEOMETRY, geomSource ) )
    pgm.setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 8 )
    pgm.setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, GL_LINES )
    pgm.setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP)

    return pgm

void ForestTechniqueManager.CollectTreePositions(Cell* cell, std.vector< osg.Vec3 > positions)
    needGroup = not (cell._cells.empty())
    needTrees = not (cell._trees.empty())
コード例 #9
0
        Color2Uniform = osg.Uniform( "Color2", osg.Vec3(0.0, 0.0, 0.0) )

        OffsetUniform.setUpdateCallback(AnimateCallback(AnimateCallback.OFFSET))
        SineUniform.setUpdateCallback(AnimateCallback(AnimateCallback.SIN))
        Color1Uniform.setUpdateCallback(AnimateCallback(AnimateCallback.COLOR1))
        Color2Uniform.setUpdateCallback(AnimateCallback(AnimateCallback.COLOR2))

        ss = rootNode.getOrCreateStateSet()
        ss.addUniform( OffsetUniform )
        ss.addUniform( SineUniform )
        ss.addUniform( Color1Uniform )
        ss.addUniform( Color2Uniform )

    # the simple Microshader (its source appears earlier in this file)
        ss = ModelInstance()
        program = osg.Program()
        program.setName( "microshader" )
        _programList.push_back( program )
        program.addShader( osg.Shader( osg.Shader.VERTEX, microshaderVertSource ) )
        program.addShader( osg.Shader( osg.Shader.FRAGMENT, microshaderFragSource ) )
        ss.setAttributeAndModes( program, osg.StateAttribute.ON )

    # the "blocky" shader, a simple animation test
        ss = ModelInstance()
        BlockyProgram = osg.Program()
        BlockyProgram.setName( "blocky" )
        _programList.push_back( BlockyProgram )
        BlockyVertObj = osg.Shader( osg.Shader.VERTEX )
        BlockyFragObj = osg.Shader( osg.Shader.FRAGMENT )
        BlockyProgram.addShader( BlockyFragObj )
        BlockyProgram.addShader( BlockyVertObj )
コード例 #10
0
def createModel(shader, textureFileName, terrainFileName, dynamic, useVBO):

    
    geode = osg.Geode()
    
    geom = osg.Geometry()
    geode.addDrawable(geom)
    
    # dimensions for ~one million triangles :-)
    num_x = 708
    num_y = 708

    # set up state
    
        stateset = geom.getOrCreateStateSet()

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

        if shader=="simple" :
            vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_simple)
            program.addShader(vertex_shader)

            coeff = osg.Uniform("coeff",osg.Vec4(1.0,-1.0,-1.0,1.0))
            
            stateset.addUniform(coeff)

            if dynamic :
                coeff.setUpdateCallback(UniformVarying)()
                coeff.setDataVariance(osg.Object.DYNAMIC)
                stateset.setDataVariance(osg.Object.DYNAMIC)
            
        elif shader=="matrix" :
            vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_matrix)
            program.addShader(vertex_shader)

            origin = osg.Uniform("origin",osg.Vec4(0.0,0.0,0.0,1.0))
            stateset.addUniform(origin)

            coeffMatrix = osg.Uniform("coeffMatrix",
                osg.Matrix(1.0,0.0,1.0,0.0,
                            0.0,0.0,-1.0,0.0,
                            0.0,1.0,-1.0,0.0,
                            0.0,0.0,1.0,0.0))

            stateset.addUniform(coeffMatrix)
        elif shader=="texture" :
            vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_texture)
            program.addShader(vertex_shader)

            image = 0

            if terrainFileName.empty() :
                image = osg.Image()
                tx = 38
                ty = 39
                image.allocateImage(tx,ty,1,GL_LUMINANCE,GL_FLOAT,1)
                for(unsigned int r=0r<ty++r)
                    for(unsigned int c=0c<tx++c)
                        *((float*)image.data(c,r)) = vertex[r+c*39][2]*0.1

                num_x = tx
                num_y = tx
コード例 #11
0
def CreateSimpleHierarchy(node):
    
    if   not node  : return NULL
    r = node.getBound().radius() # diameter
    root = osg.Group()
    group = osg.Group()

    # Create four matrices for translated instances of the cow
    transform0 = osg.MatrixTransform( )
    transform0.setMatrix( osg.Matrix.translate( 0,0,r ) )

    transform1 = osg.MatrixTransform( )
    transform1.setMatrix( osg.Matrix.translate( 0,0,0 ) )

    transform2 = osg.MatrixTransform( )
    transform2.setMatrix( osg.Matrix.translate( -r,0,-r ) )

    transform3 = osg.MatrixTransform( )
    transform3.setMatrix( osg.Matrix.translate(  r,0,-r ) )

    root.addChild( transform0 )
    root.addChild( group )
    group.addChild( transform1 )
    group.addChild( transform2 )
    group.addChild( transform3 )

    transform0.addChild( node )
    transform1.addChild( node )
    transform2.addChild( node )
    transform3.addChild( node )

    # At the scene root apply standard program 
    if  1  :
        program = osg.Program()
        main = osg.Shader( osg.Shader.FRAGMENT )

        main.setShaderSource(
            "uniform sampler2D base \n"
            "void main(void) \n"
            "\n"
            "    gl_FragColor = gl_Color * texture2DProj( base, gl_TexCoord[0] )\n"
            "    gl_FragColor *= vec4( 1.0, 1.0, 1.0, 0.5 ) \n"
            "\n"
            )
        program.addShader( main )

        main.setName( "White" ) 

        root.getOrCreateStateSet( ).setAttributeAndModes( program )

    # Now override root program with default VirtualProgram for three bottom cows
    if  1  :
        virtualProgram = VirtualProgram( )

        # Create main shader which declares and calls ColorFilter function 
        main = osg.Shader( osg.Shader.FRAGMENT )

        main.setShaderSource( 
            "vec4 ColorFilter( in vec4 color ) \n"
            "uniform sampler2D base \n"
            "void main(void) \n"
            " \n"
            "    gl_FragColor = gl_Color * texture2DProj( base, gl_TexCoord[0] ) \n"
            "    gl_FragColor = ColorFilter( gl_FragColor ) \n"
            "\n"
            )

        virtualProgram.setShader( "main", main )

        main.setName( "Virtual Main" )

        # Create filter shader which implements greem ColorFilter function 
        colorFilter = osg.Shader( osg.Shader.FRAGMENT )

        colorFilter.setShaderSource(       
            "vec4 ColorFilter( in vec4 color ) \n"
            " \n"
            "    return color * vec4( 0.0, 1.0, 0.0, 1.0 ) \n"
            "\n"
            )

        colorFilter.setName( "Virtual Green" )

        virtualProgram.setShader( "ColorFilter", colorFilter )

        group.getOrCreateStateSet( ).setAttributeAndModes( virtualProgram )

    # Create "incomplete" VirtualProgram overriding ColorFilter function
    # Lower left cow drawn will be red
    if  1  :
        virtualProgram = VirtualProgram()
      
        redFilter = osg.Shader( osg.Shader.FRAGMENT )
        redFilter.setShaderSource( 
            "vec4 ColorFilter( in vec4 color ) \n"
            " \n"
            "    return color * vec4( 1, 0, 0, 1 ) \n"
            "\n"
            )
        virtualProgram.setShader( "ColorFilter", redFilter )

        redFilter.setName( "Virtual Red" )

        transform2.getOrCreateStateSet( ).setAttribute( virtualProgram )

    # Create "incomplete" VirtualProgram overriding ColorFilter function
    # Lower right cow will be drawn with grid pattern on yellow background
    if  1  :
        virtualProgram = VirtualProgram()

        gridFilter = osg.Shader( osg.Shader.FRAGMENT )
        gridFilter.setShaderSource(         
            "vec4 ColorFilter( in vec4 color ) \n"
            " \n"
            "    vec2 grid = clamp( mod( gl_FragCoord.xy, 16.0 ), 0.0, 1.0 ) \n"
            "    return color * vec4( grid, 0.0, 1.0 ) \n"
            "\n"
            )
        virtualProgram.setShader( "ColorFilter", gridFilter )

        gridFilter.setName( "Virtual Grid" )
       
        transform3.getOrCreateStateSet( ).setAttribute( virtualProgram )

    return root
コード例 #12
0
        ss.addUniform( osg.Uniform( "baseTexture", 1 ) )

#if 0 # Could be useful with Fixed Vertex Pipeline
        texGen = osg.TexGen()
        texGen.setMode( osg.TexGen.SPHERE_MAP )

        # Texture states applied
        ss.setTextureAttributeAndModes( 1, texGen, osg.StateAttribute.ON )
#endif



    # Top center model usues osg.Program overriding VirtualProgram in model
    if  1  : 
        AddLabel( transformCenterTop, "Fixed Vertex + Simple Fragment osg.Program", offset )
        program = osg.Program()
        program.setName( "Trivial Fragment + Fixed Vertex Program" )

        transformCenterTop.getOrCreateStateSet( ).setAttributeAndModes
            ( program, osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE )

        shader = osg.Shader( osg.Shader.FRAGMENT )
        shader.setName( "Trivial Fragment Shader" )
        shader.setShaderSource(
            "uniform sampler2D baseTexture                                          \n"
            "void main(void)                                                         \n"
            "                                                                       \n"
            "    gl_FragColor = gl_Color * texture2D( baseTexture,gl_TexCoord[0].xy)\n"
            "                                                                       \n"
            )