Trajce,

Attached is a fixed source code. There is a lots of shadow shimmering on my 
GF8800. You will have to add some depth bias while rendering shadow map. 
Selection proper PolygonOffset values is usually a matter of trial and error so 
leave this for you.

Wojtek

----- Original Message ----- 
  From: Trajce Nikolov 
  To: OpenSceneGraph Users 
  Sent: Friday, January 15, 2010 9:58 AM
  Subject: Re: [osg-users] light lobes and shadow maps


  ABout the code. I use shader to simulate lght lobes thru phong lighting in 
the shader. Then I use shadow maps to detect the area behind the obstacles that 
need not to be lighten. Most is mixture of shadow maps technique with lighting 
scheme. Code snippets borrowed from all around

  Nick

  http://www.linkedin.com/in/tnick
  Sent from Devlet, Ankara, Turkey 


  On Fri, Jan 15, 2010 at 10:54 AM, Trajce Nikolov <[email protected]> 
wrote:

    Hi Guys,


    here is the code.

    Nick

    http://www.linkedin.com/in/tnick

    Sent from Devlet, Ankara, Turkey 



    On Thu, Jan 14, 2010 at 11:42 PM, Wojciech Lewandowski 
<[email protected]> wrote:

      Hi Nick,

      Post the troublesome code and elaborate a bit more about the problem. If 
its really a minute or two I am sure someone will be able to help.

      Wojtek Lewandowski


      From: Trajce Nikolov 
      Sent: Thursday, January 14, 2010 8:58 PM
      To: OpenSceneGraph Users 
      Subject: [osg-users] light lobes and shadow maps


      Hi community,

      I have some shader that does some lighting in the scene. Now studying 
osgShadow and the techniques. I want to a shadow map technique to disable the 
lightening of the scene behind obstacles. I have some code done, but not 
working. I need some help, someone experienced with GLSL to spend a minute or 
to to have a look and if possible to spot the problem. Anyone?

      Thanks a lot

      Nick

      http://www.linkedin.com/in/tnick
      Sent from Izmit, 41, Turkey 


--------------------------------------------------------------------------


      _______________________________________________
      osg-users mailing list
      [email protected]
      http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org



      _______________________________________________
      osg-users mailing list
      [email protected]
      http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org








------------------------------------------------------------------------------


  _______________________________________________
  osg-users mailing list
  [email protected]
  http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
 *
 * This application is open source and may be redistributed and/or modified   
 * freely and without restriction, both in commericial and non commericial 
applications,
 * as long as this copyright notice is maintained.
 * 
 * This application 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.
*/

#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgUtil/Optimizer>
#include <osg/CoordinateSystemNode>

#include <osg/Switch>
#include <osg/LightSource>
#include <osgText/Text>

#include <osgViewer/Viewer>
#include <osgViewer/CompositeViewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <osgSim/OverlayNode>
#include <osg/Geode>
#include <osgText/Text3D>
#include <osg/MatrixTransform>
#include <osg/ShapeDrawable>
#include <osg/TexGen>
#include <osg/TexGenNode>

#include <iostream>
#include <sstream>

#include <osg/Geometry>
#include <osg/Geode>
#include <osg/LightSource>
#include <osg/LightModel>
#include <osg/Program>
#include <osg/ImageStream>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/BlendFunc>
#include <osg/AlphaFunc>
#include <osg/Material>

#include <osgUtil/SmoothingVisitor>
#include <osg/ShapeDrawable>

#include <osg/PositionAttitudeTransform>
#include <osg/TextureRectangle>

#if 1
osg::Matrixd createTransformMatrix(double x, double y, double z, double h, 
double p, double r)
{
        osg::Matrixd mxR;
        mxR.makeRotate(osg::DegreesToRadians(r),osg::Vec3(0,1,0));
        osg::Matrixd mxP;
        mxP.makeRotate(osg::DegreesToRadians(p),osg::Vec3(1,0,0));
        osg::Matrixd mxH;
        mxH.makeRotate(osg::DegreesToRadians(h),osg::Vec3(0,0,1));
        osg::Matrixd mxT;
        mxT.makeTranslate(osg::Vec3(x,y,z));

        return (mxR*mxP*mxH*mxT);
}

osg::Node* makeFrustumFromCamera( osg::Camera* camera )
{
    // Projection and ModelView matrices
    osg::Matrixd proj;
    osg::Matrixd mv;
    if (camera)
    {
        proj = camera->getProjectionMatrix();
        mv = camera->getViewMatrix();
    }
    else
    {
        // Create some kind of reasonable default Projection matrix.
        proj.makePerspective( 30., 1., 1., 10. );
        // leave mv as identity
    }

    // Get near and far from the Projection matrix.
    const double near = proj(3,2) / (proj(2,2)-1.0);
    const double far = proj(3,2) / (1.0+proj(2,2));

    // Get the sides of the near plane.
    const double nLeft = near * (proj(2,0)-1.0) / proj(0,0);
    const double nRight = near * (1.0+proj(2,0)) / proj(0,0);
    const double nTop = near * (1.0+proj(2,1)) / proj(1,1);
    const double nBottom = near * (proj(2,1)-1.0) / proj(1,1);

    // Get the sides of the far plane.
    const double fLeft = far * (proj(2,0)-1.0) / proj(0,0);
    const double fRight = far * (1.0+proj(2,0)) / proj(0,0);
    const double fTop = far * (1.0+proj(2,1)) / proj(1,1);
    const double fBottom = far * (proj(2,1)-1.0) / proj(1,1);

    // Our vertex array needs only 9 vertices: The origin, and the
    // eight corners of the near and far planes.
    osg::Vec3Array* v = new osg::Vec3Array;
    v->resize( 9 );
    (*v)[0].set( 0., 0., 0. );
    (*v)[1].set( nLeft, nBottom, -near );
    (*v)[2].set( nRight, nBottom, -near );
    (*v)[3].set( nRight, nTop, -near );
    (*v)[4].set( nLeft, nTop, -near );
    (*v)[5].set( fLeft, fBottom, -far );
    (*v)[6].set( fRight, fBottom, -far );
    (*v)[7].set( fRight, fTop, -far );
    (*v)[8].set( fLeft, fTop, -far );

    osg::Geometry* geom = new osg::Geometry;
    geom->setUseDisplayList( false );
    geom->setVertexArray( v );

    osg::Vec4Array* c = new osg::Vec4Array;
    c->push_back( osg::Vec4( 1., 1., 1., 1. ) );
    geom->setColorArray( c );
    geom->setColorBinding( osg::Geometry::BIND_OVERALL );

    GLushort idxLines[8] = {
        0, 5, 0, 6, 0, 7, 0, 8 };
    GLushort idxLoops0[4] = {
        1, 2, 3, 4 };
    GLushort idxLoops1[4] = {
        5, 6, 7, 8 };
    geom->addPrimitiveSet( new osg::DrawElementsUShort( 
osg::PrimitiveSet::LINES, 8, idxLines ) );
    geom->addPrimitiveSet( new osg::DrawElementsUShort( 
osg::PrimitiveSet::LINE_LOOP, 4, idxLoops0 ) );
    geom->addPrimitiveSet( new osg::DrawElementsUShort( 
osg::PrimitiveSet::LINE_LOOP, 4, idxLoops1 ) );

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable( geom );

    geode->getOrCreateStateSet()->setMode( GL_LIGHTING, 
osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED );


    // Create parent MatrixTransform to transform the view volume by
    // the inverse ModelView matrix.
    osg::MatrixTransform* mt = new osg::MatrixTransform;
    mt->setMatrix( osg::Matrixd::inverse( mv ) );
    mt->addChild( geode );

    return mt;
}

class DrawableDrawWithDepthShadowComparisonOffCallback: 
    public osg::Drawable::DrawCallback
{
public:
    // 
    DrawableDrawWithDepthShadowComparisonOffCallback
        ( osg::Texture2D * texture, unsigned stage = 0 )
            : _texture( texture ), _stage( stage )
    {
    }

    virtual void drawImplementation
        ( osg::RenderInfo & ri,const osg::Drawable* drawable ) const
    {
        if( _texture.valid() ) {
            // make sure proper texture is currently applied
            ri.getState()->applyTextureAttribute( _stage, _texture.get() );

            // Turn off depth comparison mode
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, 
                             GL_NONE );
        }

        drawable->drawImplementation(ri);

        if( _texture.valid() ) {
            // Turn it back on
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, 
                             GL_COMPARE_R_TO_TEXTURE_ARB );
        }
    }

    osg::ref_ptr< osg::Texture2D > _texture;
    unsigned                       _stage;
};


osg::Node* createScene(osg::ArgumentParser& arguments, osgViewer::Viewer* 
viewer = 0)
{
        osg::Group* group = new osg::Group;
        osg::Group* scene = new osg::Group;
        scene->addChild(group);

        osg::MatrixTransform* mx = 0;
        osg::MatrixTransform* mx2 = 0;
        osg::Geometry* scenegeometry = 0;

        osg::Geode* geode = new osg::Geode;
        group->addChild(geode);

        // "TERRAIN"
        {
                mx2 = new osg::MatrixTransform;
                mx2->setMatrix(osg::Matrix::scale(osg::Vec3(35,35,35)));
                group->addChild(mx2);

                osg::Geode* geode = new osg::Geode;
                mx2->addChild(geode);

                scenegeometry = new osg::Geometry;
                geode->addDrawable(scenegeometry);

                osg::Vec3Array* vxs = new osg::Vec3Array;
                vxs->push_back( osg::Vec3(-0.5,-0.5,0) );
                vxs->push_back( osg::Vec3(0.5,-0.5,0) );
                vxs->push_back( osg::Vec3(0.5,0.5,0) );
                vxs->push_back( osg::Vec3(-0.5,0.5,0) );
                scenegeometry->setVertexArray( vxs );

                osg::Vec2Array* uvs = new osg::Vec2Array;
                uvs->push_back( osg::Vec2(0,0) );
                uvs->push_back( osg::Vec2(1,0) );
                uvs->push_back( osg::Vec2(1,1) );
                uvs->push_back( osg::Vec2(0,1) );
                scenegeometry->setTexCoordArray(0,uvs);

                for (unsigned int i=0; i<10; ++i)
                {
                        double pos = -0.5+(0.1*i);
                        double w = 0.05;
                        vxs->push_back( osg::Vec3(pos,0.0,-0.1) );
                        vxs->push_back( osg::Vec3(pos+w,0.0,-0.1) );
                        vxs->push_back( osg::Vec3(pos+w,0.0,0.1) );
                        vxs->push_back( osg::Vec3(pos,0.0,0.1) );
                
                        uvs->push_back( osg::Vec2(0,0) );
                        uvs->push_back( osg::Vec2(1,0) );
                        uvs->push_back( osg::Vec2(1,1) );
                        uvs->push_back( osg::Vec2(0,1) );
                }
                

                osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
                if (image)
                {
                        osg::Texture2D* texture = new osg::Texture2D;
                        texture->setImage(image);
                        
scenegeometry->getOrCreateStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
                }

                scenegeometry->addPrimitiveSet( new 
osg::DrawArrays(osg::PrimitiveSet::QUADS,0,vxs->size()) );

                osg::Material* mt = new osg::Material;
                
mt->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.3,0.3,0.3,1));
                
mt->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.9,0.5,0.5,1));
                
mt->setSpecular(osg::Material::FRONT_AND_BACK,osg::Vec4(0.6,0.6,0.6,1));
                mt->setShininess(osg::Material::FRONT_AND_BACK,60);
                
scenegeometry->getOrCreateStateSet()->setAttributeAndModes(mt,osg::StateAttribute::ON);
                
        }

        // "LIGHT SOURCE"
        {
                for (unsigned int i=1; i<=1; ++i)
                {
                        osg::LightSource* light = new osg::LightSource;

                        light->getLight()->setLightNum(i);
                        light->getLight()->setAmbient(osg::Vec4(0,0,0,1));
                        light->getLight()->setDiffuse(osg::Vec4(0,10,0,1));
                        light->getLight()->setSpecular(osg::Vec4(1,1,1,1));
                        light->getLight()->setConstantAttenuation(0.01);
                        light->getLight()->setSpotCutoff(20);
                        
light->setStateSetModes(*group->getOrCreateStateSet(),osg::StateAttribute::ON);
                        light->getLight()->setDirection(osg::Vec3(0,1,0));
                        light->getLight()->setPosition(osg::Vec4(0,0,0,1));
                        mx = new osg::MatrixTransform;
                        
mx->setMatrix(createTransformMatrix(15-i*2.5,-4,3,0,-45,0));
                        mx->addChild(light);

                        osg::Geode* geode = new osg::Geode;
                        mx->addChild(geode);

                        float radius = 0.2f;
                        osg::TessellationHints* hints = new 
osg::TessellationHints;
                        hints->setDetailRatio(0.5f);
                    geode->addDrawable(new osg::ShapeDrawable(new 
osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),radius),hints));

                        group->addChild(mx);
                }
        }
        // SCENE LIGHTING
        {
                const char* microshaderVertSource = 
            "uniform mat4 osg_ViewMatrixInverse; // Automatically updated by 
OSG\n"
                        "varying vec3 normal, eyeVec;\n"
                        "varying vec3 lightDirs[8];\n"
                        "varying vec4 projShadow;\n"
                        " uniform mat4 LightModelViewProjectionMatrix;\n"
                        "\n"
                        "void main()\n"
                        "{      \n"
                        "       gl_TexCoord[0] = gl_MultiTexCoord0;\n"
                        "       normal = gl_NormalMatrix * gl_Normal;\n"
                        "       \n"
                        "       vec3 vVertex = vec3(gl_ModelViewMatrix * 
gl_Vertex);\n"
                        "       lightDirs[0] = 
vec3(gl_LightSource[0].position.xyz - vVertex);\n"
                        "       lightDirs[1] = 
vec3(gl_LightSource[1].position.xyz - vVertex);\n"
                        "       lightDirs[2] = 
vec3(gl_LightSource[2].position.xyz - vVertex);\n"
                        "       lightDirs[3] = 
vec3(gl_LightSource[3].position.xyz - vVertex);\n"
                        "       lightDirs[4] = 
vec3(gl_LightSource[4].position.xyz - vVertex);\n"
                        "       lightDirs[5] = 
vec3(gl_LightSource[5].position.xyz - vVertex);\n"
                        "       lightDirs[6] = 
vec3(gl_LightSource[6].position.xyz - vVertex);\n"
                        "       lightDirs[7] = 
vec3(gl_LightSource[7].position.xyz - vVertex);\n"
                        "       eyeVec = -vVertex;\n"
            "   // We need vertex in world spaces \n"
            "   // ie something like: glVertex * gl_ModelMatrix \n"
            "   // but there is no such thing like gl_ModelMatrix in GL \n"
            "   // but we could get it from view space by multiplication by 
inverted viewMatrix \n"
            "   // gl_Vertex * gl_ModelViewMatrix * osg_ViewMatrixInverse \n"
            "   vec4 worldSpaceVertex = osg_ViewMatrixInverse * vec4( vVertex, 
1.0 ); \n"
                        "       projShadow = LightModelViewProjectionMatrix * 
worldSpaceVertex;\n"
                        "\n"
                        "       gl_Position = ftransform();             \n"
                        "}\n";

                const char* microshaderFragSource =
                        "uniform sampler2D color_texture;\n"
                        "uniform sampler2DShadow shadow_texture;\n"
                        "varying vec4 projShadow;\n"
                        "\n"
                        "uniform bool fogActive;\n"
                        "\n"
                        "const int NumEnabledLights = 1; \n"
                        "\n"
                        "varying vec3 normal, eyeVec;\n"
                        "varying vec3 lightDirs[8];\n"
                        "\n"
                        "const float cos_outer_cone_angle = 0.8; // 36 
degrees\n"
                        "\n"
                        "void main (void)\n"
                        "{\n"
                        "vec4 combined_color = vec4(0.0);\n"
                        "for (int i = 1; i < 1+NumEnabledLights; i++)\n" 
                        "{ \n" 
                        "       vec4 final_color =\n"
                        "       (gl_FrontLightModelProduct.sceneColor * 
gl_FrontMaterial.ambient) +\n"
                        "       (gl_LightSource[i].ambient * 
gl_FrontMaterial.ambient);\n"
                        "\n"
                        "       float distSqr = 
dot(lightDirs[i],lightDirs[i]);\n"
                        "       float invRadius = 
gl_LightSource[i].constantAttenuation;\n"
                        "       float att = clamp(1.0-invRadius * 
sqrt(distSqr), 0.0, 1.0);\n"
                        "       vec3 L = lightDirs[i] * inversesqrt(distSqr);\n"
                        "       vec3 D = 
normalize(gl_LightSource[i].spotDirection);\n"
                        "\n"
                        "       float cos_cur_angle = dot(-L, D);\n"
                        "\n"
                        "       float cos_inner_cone_angle = 
gl_LightSource[i].spotCosCutoff;\n"
                        "\n"
                        "       float cos_inner_minus_outer_angle = \n"
                        "                 cos_inner_cone_angle - 
cos_outer_cone_angle;\n"
                        "       \n"
                        "       float spot = 0.0;\n"
                        "       spot = clamp((cos_cur_angle - 
cos_outer_cone_angle) / \n"
                        "                  cos_inner_minus_outer_angle, 0.0, 
1.0);\n"
                        "\n"
                        "       vec3 N = normalize(normal);\n"
                        "\n"
                        "       float lambertTerm = max( dot(N,L), 0.0);\n"
                        "       if(lambertTerm > 0.0)\n"
                        "       {\n"
                        "               final_color += 
gl_LightSource[i].diffuse *\n"
                        "                       gl_FrontMaterial.diffuse *\n"
                        "                       lambertTerm * spot * att;\n"
                        "\n"
                        "               vec3 E = normalize(eyeVec);\n"
                        "               vec3 R = reflect(-L, N);\n"
                        "\n"
                        "               float specular = pow( max(dot(R, E), 
0.0),\n"
                        "                       gl_FrontMaterial.shininess );\n"
                        "\n"
                        "               final_color += 
gl_LightSource[i].specular *\n"
                        "                       gl_FrontMaterial.specular *\n"
                        "                       specular * spot * att;\n"
                        "       }\n"
                        "       vec4 clr = final_color * shadow2DProj( 
shadow_texture, projShadow ).r;\n" 
                        "       combined_color += clr;\n"
                        "}\n"
                        "       {\n"
                        "               vec4 final_color = \n"
                        "               (gl_FrontLightModelProduct.sceneColor * 
gl_FrontMaterial.ambient) + \n"
                        "               (gl_LightSource[0].ambient * 
gl_FrontMaterial.ambient);\n"
                        "\n"                                                    
                        "               vec3 N = normalize(normal);\n"
                        "               vec3 L = normalize(lightDirs[0]);\n"
                        "\n"
                        "               float lambertTerm = dot(N,L);\n"
                        "\n"
                        "               if(lambertTerm > 0.0)\n"
                        "               {\n"
                        "                       final_color += 
gl_LightSource[0].diffuse * \n"
                        "                              gl_FrontMaterial.diffuse 
* \n"
                        "                                          lambertTerm; 
\n"
                        "\n"
                        "                       vec3 E = normalize(eyeVec);\n"
                        "                       vec3 R = reflect(-L, N);\n"
                        "                       float specular = pow( 
max(dot(R, E), 0.0), \n"
                        "                                
gl_FrontMaterial.shininess );\n"
                        "                       final_color += 
gl_LightSource[0].specular * \n"
                        "                              
gl_FrontMaterial.specular * \n"
                        "                                          specular;    
\n"
                        "               }\n"
                        "               combined_color += final_color;\n"
                        "       }\n"
                        "       vec4 preFogColor = texture2D(color_texture, 
gl_TexCoord[0].st) * combined_color;\n"
                        "       if (fogActive)\n"
                        "       {\n"
                        "               const float LOG2 = 1.442695;\n"
                        "               float z = gl_FragCoord.z / 
gl_FragCoord.w;\n"
                        "               float fogFactor = exp2( -gl_Fog.density 
* \n"
                        "                       gl_Fog.density * \n"
                        "                       z * \n"
                        "                       z * \n"
                        "                       LOG2 );\n"
                        "               fogFactor = clamp(fogFactor, 0.0, 
1.0);\n"
                        "               gl_FragColor = mix(gl_Fog.color, 
preFogColor, fogFactor );"
                        "       }\n"
                        "       else gl_FragColor = preFogColor;\n"
//            "   gl_FragColor = ( projShadow / projShadow.w ); \n"
                        "}\n";
                

                osg::Program* program = new osg::Program;
        program->setName( "microshader" );
                program->addShader( new osg::Shader( osg::Shader::VERTEX, 
microshaderVertSource ) );
        program->addShader( new osg::Shader( osg::Shader::FRAGMENT, 
microshaderFragSource ) );
        group->getOrCreateStateSet()->setAttributeAndModes( program, 
osg::StateAttribute::ON );
                group->getOrCreateStateSet()->addUniform( new 
osg::Uniform("fogActive",false) );
                group->getOrCreateStateSet()->addUniform( new 
osg::Uniform("color_texture",0) );
                group->getOrCreateStateSet()->addUniform( new 
osg::Uniform("shadow_texture",1) );

        }
        // HUD
        {
                osg::Camera* camera = new osg::Camera;
                scene->addChild(camera);        

                double width = 1280;
                double height = 1024;

                
camera->setProjectionMatrix(osg::Matrix::ortho2D(0,width,0,height));
                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
                camera->setViewMatrix(osg::Matrix::identity());
                camera->setClearMask(GL_DEPTH_BUFFER_BIT);
                camera->setRenderOrder(osg::Camera::POST_RENDER);
                camera->setAllowEventFocus(false);

                osg::Geode* geode = new osg::Geode;
                camera->addChild(geode);
                
camera->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF|osg::StateAttribute::OVERRIDE|osg::StateAttribute::PROTECTED);

                double offset = 50;
                double wf = 512;
                double hf = 512;
                osg::Geometry *geometry = 
osg::createTexturedQuadGeometry(osg::Vec3(offset,2*offset,-0.1),osg::Vec3(wf,0,0),osg::Vec3(0,hf,0));
                geode->addDrawable(geometry);

                osg::Shader* shader = new osg::Shader( osg::Shader::FRAGMENT,
#if 0
                        "uniform sampler2D texture; \n"
                        " \n"
                        "void main(void) \n"
                        "{ \n"
                        "   float value = texture2D(texture, gl_TexCoord[0].st 
).r; \n"
                        "   gl_FragColor = vec4( value, value, value, 0.8 ); \n"
                        "} \n"
#else
                        "uniform sampler2D texture;                             
                 \n"
                        "                                                       
                 \n"
                        "void main(void)                                        
                 \n"
                        "{                                                      
                 \n"
                        "    float f = texture2D( texture, gl_TexCoord[0].st 
).r;                \n"
                        "                                                       
                                                                                
         \n"
                        "                                                       
                 \n"
                        "    f = 256.0 * f;                                     
                 \n"
                        "    float fC = floor( f ) / 256.0;                     
                 \n" 
                        "                                                       
                 \n"
                        "    f = 256.0 * fract( f );                            
                 \n"
                        "    float fS = floor( f ) / 256.0;                     
                 \n"  
                        "                                                       
                 \n"
                        "    f = 256.0 * fract( f );                            
                 \n"
                        "    float fH = floor( f ) / 256.0;                     
                 \n"
                        "                                                       
                 \n"
                        "    fS *= 0.5;                                         
                 \n"
                        "    fH = ( fH  * 0.34 + 0.66 ) * ( 1.0 - fS );         
                 \n"
                        "                                                       
                 \n"
                        "    vec3 rgb = vec3( ( fC > 0.5 ? ( 1.0 - fC ) : fC ), 
                 \n"
                        "                     abs( fC - 0.333333 ),             
                 \n"
                        "                     abs( fC - 0.666667 ) );           
                 \n"
                        "                                                       
                 \n"   
                        "    rgb = min( vec3( 1.0, 1.0, 1.0 ), 3.0 * rgb );     
                 \n"
                        "                                                       
                 \n"
                        "    float fMax = max( max( rgb.r, rgb.g ), rgb.b );    
                 \n"
                        "    fMax = 1.0 / fMax;                                 
                 \n"  
                        "                                                       
                 \n"
                        "    vec3 color = fMax * rgb;                           
                 \n"
                        "                                                       
                 \n"
                        "    gl_FragColor =  vec4( fS + fH * color, 1 ) * 
gl_Color;              \n"
                        "}                                                      
                 \n"  
#endif
                ); 
                osg::Program* program = new osg::Program;
                program->addShader( shader );
                geometry->getOrCreateStateSet()->setAttribute( program );
                geometry->getOrCreateStateSet()->addUniform( new osg::Uniform( 
"texture" , 0 ) );

                osg::Texture2D* dbgDepthTexture = new osg::Texture2D;
                dbgDepthTexture->setTextureSize(512, 512);
                dbgDepthTexture->setInternalFormat(GL_DEPTH_COMPONENT);
                
dbgDepthTexture->setShadowTextureMode(osg::Texture2D::LUMINANCE);
                dbgDepthTexture->setShadowComparison(true);
                dbgDepthTexture->setShadowCompareFunc(osg::Texture::LEQUAL);
                dbgDepthTexture->setWrap(osg::Texture::WRAP_S, 
osg::Texture::CLAMP_TO_EDGE);
                dbgDepthTexture->setWrap(osg::Texture::WRAP_T, 
osg::Texture::CLAMP_TO_EDGE);
                dbgDepthTexture->setWrap(osg::Texture::WRAP_R, 
osg::Texture::CLAMP_TO_EDGE);
                
dbgDepthTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
                
dbgDepthTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
                
geometry->getOrCreateStateSet()->setTextureAttributeAndModes(0,dbgDepthTexture,osg::StateAttribute::ON);

                
scenegeometry->getOrCreateStateSet()->setTextureAttributeAndModes(1,dbgDepthTexture,osg::StateAttribute::ON);

                geometry->setDrawCallback( new 
DrawableDrawWithDepthShadowComparisonOffCallback(dbgDepthTexture) );

                // LIGHT CAMERA
                {
                        osg::Camera* camera = new osg::Camera;
                        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
                        camera->setProjectionMatrixAsPerspective(45, 1, 0.001, 
10 );
                        camera->setViewport(0,0,512,512);
                        
camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
                        camera->setClearColor(osg::Vec4(1.f,1.f,1.f,1.0f));
                        camera->setClearMask(GL_DEPTH_BUFFER_BIT);
                        
camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
                        camera->addChild(mx2);
                        camera->setRenderOrder(osg::Camera::PRE_RENDER);
                        
camera->attach(osg::Camera::DEPTH_BUFFER,dbgDepthTexture);
                        camera->setCullingActive(true);

                        {
                                osg::Matrixd mxd = mx->getMatrix();
                                osg::Quat q = mxd.getRotate();
                                osg::Vec3 t = mxd.getTrans();

                                osg::Quat fq;
                                
fq.makeRotate(osg::Vec3(0,0,-1),osg::Vec3(0,1,0));

                                osg::Matrixd mR;
                                mR.makeRotate(q);
                                osg::Matrixd mT;
                                mT.makeTranslate(t);
                                osg::Matrixd mF;
                                mF.makeRotate(fq);

                                osg::Matrixd m;
                                m = mF * mR * mT;

                                camera->setViewMatrix(osg::Matrixd::inverse(m));
                        }

                        osg::Matrixd lmvpm =
                                camera->getViewMatrix() * 
camera->getProjectionMatrix() * 
                osg::Matrix::translate( 1,1,1 ) * osg::Matrix::scale( 0.5, 0.5, 
0.5 );
                        group->getOrCreateStateSet()->addUniform( new 
osg::Uniform("LightModelViewProjectionMatrix",lmvpm) );
            

                        scene->addChild(camera);

                        scene->addChild( makeFrustumFromCamera(camera) );
                }
        }

        return scene;
}
#endif

void setupViewer(osgViewer::Viewer* viewer, osg::ArgumentParser& arguments)
{
        // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = 
new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new 
osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new 
osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new 
osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new 
osgGA::TerrainManipulator() );

        viewer->setCameraManipulator( keyswitchManipulator.get() );
    }

        // add the state manipulator
    viewer->addEventHandler( new 
osgGA::StateSetManipulator(viewer->getCamera()->getOrCreateStateSet()) );
    
    // add the thread model handler
    viewer->addEventHandler(new osgViewer::ThreadingHandler);

    // add the window size toggle handler
    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
        
    // add the stats handler
    viewer->addEventHandler(new osgViewer::StatsHandler);

    // add the help handler
    viewer->addEventHandler(new 
osgViewer::HelpHandler(arguments.getApplicationUsage()));

    // add the record camera path handler
    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);

    // add the LOD Scale handler
    viewer->addEventHandler(new osgViewer::LODScaleHandler);

    // add the screen capture handler
    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
}

int main(int argc, char** argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+"
 is the standard OpenSceneGraph example which loads and visualises 3d models.");
    
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+"
 [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("--image 
<filename>","Load an image and render it on a quad");
    arguments.getApplicationUsage()->addCommandLineOption("--dem 
<filename>","Load an image/DEM and render it on a HeightField");
    arguments.getApplicationUsage()->addCommandLineOption("--login <url> 
<username> <password>","Provide authentication information for http file 
access.");

        osg::ref_ptr<osgViewer::Viewer> viewer = new 
osgViewer::Viewer(arguments);
        viewer->getLight()->setAmbient(osg::Vec4(0.2,0.2,0.2,1));
        viewer->getLight()->setDiffuse(osg::Vec4(0.7,0.5,0.5,1));

    unsigned int helpType = 0;
    if ((helpType = arguments.readHelpType()))
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }
    
    // report any errors if they have occurred when parsing the program 
arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }
    
#if 0
    if (arguments.argc()<=1)
    {
        
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }
#endif

    std::string url, username, password;
    while(arguments.read("--login",url, username, password))
    {
        if (!osgDB::Registry::instance()->getAuthenticationMap())
        {
            osgDB::Registry::instance()->setAuthenticationMap(new 
osgDB::AuthenticationMap);
            
osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails(
                url,
                new osgDB::AuthenticationDetails(username, password)
            );
        }
    }


        setupViewer(viewer.get(),arguments);

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
    if (!loadedModel) 
    {
                loadedModel = createScene(arguments,viewer.get());
                
//arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        //std::cout << arguments.getApplicationName() <<": No data loaded" << 
std::endl;
        //return 1;
    }

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

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


    // optimize the scene graph, remove redundant nodes and state etc.
#if 0
    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get());

        osgUtil::SmoothingVisitor sv;
        loadedModel->accept(sv);
#endif

    viewer->setSceneData( loadedModel.get() );

    viewer->realize();

        while (!viewer->done())
        {
                viewer->frame();
        }

        viewer = 0;

    return 0;

}
_______________________________________________
osg-users mailing list
[email protected]
http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org

Reply via email to