root/OpenSceneGraph/trunk/examples/osgshadow/osgshadow.cpp @ 6952

Revision 6952, 24.8 kB (checked in by robert, 7 years ago)

Removed ParallelSplitShadowMap? as its currently a non op.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgshadow.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#include <osg/ArgumentParser>
20#include <osg/ComputeBoundsVisitor>
21#include <osg/Texture2D>
22#include <osg/ShapeDrawable>
23#include <osg/MatrixTransform>
24#include <osg/Geometry>
25
26#include <osgGA/TrackballManipulator>
27#include <osgGA/FlightManipulator>
28#include <osgGA/DriveManipulator>
29#include <osgGA/KeySwitchMatrixManipulator>
30#include <osgGA/AnimationPathManipulator>
31#include <osgGA/TerrainManipulator>
32#include <osgGA/AnimationPathManipulator>
33#include <osgGA/StateSetManipulator>
34
35#include <osgViewer/Viewer>
36#include <osgViewer/ViewerEventHandlers>
37
38#include <osgShadow/ShadowedScene>
39#include <osgShadow/ShadowVolume>
40#include <osgShadow/ShadowTexture>
41#include <osgShadow/ShadowMap>
42
43#include <osgDB/ReadFile>
44#include <osgDB/WriteFile>
45
46#include <iostream>
47
48// for the grid data..
49#include "../osghangglide/terrain_coords.h"
50
51const int ReceivesShadowTraversalMask = 0x1;
52const int CastsShadowTraversalMask = 0x2;
53 
54namespace ModelOne
55{
56
57    enum Faces
58    {
59        FRONT_FACE = 1,
60        BACK_FACE = 2,
61        LEFT_FACE = 4,
62        RIGHT_FACE = 8,
63        TOP_FACE = 16,
64        BOTTOM_FACE = 32       
65    };
66
67    osg::Node* createCube(unsigned int mask)
68    {
69        osg::Geode* geode = new osg::Geode;
70
71        osg::Geometry* geometry = new osg::Geometry;
72        geode->addDrawable(geometry);
73
74        osg::Vec3Array* vertices = new osg::Vec3Array;
75        geometry->setVertexArray(vertices);
76
77        osg::Vec3Array* normals = new osg::Vec3Array;
78        geometry->setNormalArray(normals);
79        geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
80
81        osg::Vec4Array* colours = new osg::Vec4Array;
82        geometry->setColorArray(colours);
83        geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
84        colours->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
85
86
87        osg::Vec3 origin(0.0f,0.0f,0.0f);
88        osg::Vec3 dx(2.0f,0.0f,0.0f);
89        osg::Vec3 dy(0.0f,1.0f,0.0f);
90        osg::Vec3 dz(0.0f,0.0f,1.0f);
91
92        osg::Vec3 px(1.0f,0.0,0.0f);
93        osg::Vec3 nx(-1.0f,0.0,0.0f);
94        osg::Vec3 py(0.0f,1.0f,0.0f);
95        osg::Vec3 ny(0.0f,-1.0f,0.0f);
96        osg::Vec3 pz(0.0f,0.0f,1.0f);
97        osg::Vec3 nz(0.0f,0.0f,-1.0f);
98
99        if (mask & FRONT_FACE)
100        {
101            // front face   
102            vertices->push_back(origin);
103            vertices->push_back(origin+dx);
104            vertices->push_back(origin+dx+dz);
105            vertices->push_back(origin+dz);
106            normals->push_back(ny);
107            normals->push_back(ny);
108            normals->push_back(ny);
109            normals->push_back(ny);
110        }
111
112        if (mask & BACK_FACE)
113        {
114            // back face   
115            vertices->push_back(origin+dy);
116            vertices->push_back(origin+dy+dz);
117            vertices->push_back(origin+dy+dx+dz);
118            vertices->push_back(origin+dy+dx);
119            normals->push_back(py);
120            normals->push_back(py);
121            normals->push_back(py);
122            normals->push_back(py);
123        }
124
125        if (mask & LEFT_FACE)
126        {
127            // left face   
128            vertices->push_back(origin+dy);
129            vertices->push_back(origin);
130            vertices->push_back(origin+dz);
131            vertices->push_back(origin+dy+dz);
132            normals->push_back(nx);
133            normals->push_back(nx);
134            normals->push_back(nx);
135            normals->push_back(nx);
136        }
137
138        if (mask & RIGHT_FACE)
139        {
140            // right face   
141            vertices->push_back(origin+dx+dy);
142            vertices->push_back(origin+dx+dy+dz);
143            vertices->push_back(origin+dx+dz);
144            vertices->push_back(origin+dx);
145            normals->push_back(px);
146            normals->push_back(px);
147            normals->push_back(px);
148            normals->push_back(px);
149        }
150
151        if (mask & TOP_FACE)
152        {
153            // top face   
154            vertices->push_back(origin+dz);
155            vertices->push_back(origin+dz+dx);
156            vertices->push_back(origin+dz+dx+dy);
157            vertices->push_back(origin+dz+dy);
158            normals->push_back(pz);
159            normals->push_back(pz);
160            normals->push_back(pz);
161            normals->push_back(pz);
162        }
163
164        if (mask & BOTTOM_FACE)
165        {
166            // bottom face   
167            vertices->push_back(origin);
168            vertices->push_back(origin+dy);
169            vertices->push_back(origin+dx+dy);
170            vertices->push_back(origin+dx);
171            normals->push_back(nz);
172            normals->push_back(nz);
173            normals->push_back(nz);
174            normals->push_back(nz);
175        }
176
177        geometry->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, vertices->size()));
178
179        return geode;
180    }
181
182    class SwitchHandler : public osgGA::GUIEventHandler
183    {
184    public:
185
186        SwitchHandler():
187            _childNum(0) {}
188
189        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& /*aa*/, osg::Object* object, osg::NodeVisitor* /*nv*/)
190        {
191            osg::Switch* sw = dynamic_cast<osg::Switch*>(object);
192            if (!sw) return false;
193
194            if (ea.getHandled()) return false;
195
196            switch(ea.getEventType())
197            {
198                case(osgGA::GUIEventAdapter::KEYDOWN):
199                {
200                    if (ea.getKey()=='n')
201                    {
202                        ++_childNum;
203                        if (_childNum >= sw->getNumChildren()) _childNum = 0;
204
205                        sw->setSingleChildOn(_childNum);
206                        return true;
207                    }               
208                    break;
209                }
210                default:
211                    break;
212            }
213            return false;
214        }
215
216    protected:
217
218        virtual ~SwitchHandler() {}
219        unsigned int    _childNum;
220
221    };
222
223
224    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
225    {
226        osg::Switch* sw = new osg::Switch;
227        sw->setEventCallback(new ModelOne::SwitchHandler);
228
229        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE), true);
230        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE), false);
231        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE), false);
232        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE), false);
233        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE), false);
234        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE | ModelOne::BOTTOM_FACE), false);
235       
236        return sw;   
237    }
238}
239
240namespace ModelTwo
241{
242    osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
243    {
244        // set up the animation path
245        osg::AnimationPath* animationPath = new osg::AnimationPath;
246        animationPath->setLoopMode(osg::AnimationPath::LOOP);
247
248        int numSamples = 40;
249        float yaw = 0.0f;
250        float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
251        float roll = osg::inDegrees(30.0f);
252
253        double time=0.0f;
254        double time_delta = looptime/(double)numSamples;
255        for(int i=0;i<numSamples;++i)
256        {
257            osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
258            osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
259
260            animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
261
262            yaw += yaw_delta;
263            time += time_delta;
264
265        }
266        return animationPath;   
267    }
268
269    osg::Node* createBase(const osg::Vec3& center,float radius)
270    {
271
272        osg::Geode* geode = new osg::Geode;
273
274        // set up the texture of the base.
275        osg::StateSet* stateset = new osg::StateSet();
276        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
277        if (image)
278        {
279            osg::Texture2D* texture = new osg::Texture2D;
280            texture->setImage(image);
281            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
282        }
283
284        geode->setStateSet( stateset );
285
286
287        osg::HeightField* grid = new osg::HeightField;
288        grid->allocate(38,39);
289        grid->setOrigin(center+osg::Vec3(-radius,-radius,0.0f));
290        grid->setXInterval(radius*2.0f/(float)(38-1));
291        grid->setYInterval(radius*2.0f/(float)(39-1));
292
293        float minHeight = FLT_MAX;
294        float maxHeight = -FLT_MAX;
295
296
297        unsigned int r;
298        for(r=0;r<39;++r)
299        {
300            for(unsigned int c=0;c<38;++c)
301            {
302                float h = vertex[r+c*39][2];
303                if (h>maxHeight) maxHeight=h;
304                if (h<minHeight) minHeight=h;
305            }
306        }
307
308        float hieghtScale = radius*0.5f/(maxHeight-minHeight);
309        float hieghtOffset = -(minHeight+maxHeight)*0.5f;
310
311        for(r=0;r<39;++r)
312        {
313            for(unsigned int c=0;c<38;++c)
314            {
315                float h = vertex[r+c*39][2];
316                grid->setHeight(c,r,(h+hieghtOffset)*hieghtScale);
317            }
318        }
319
320        geode->addDrawable(new osg::ShapeDrawable(grid));
321
322        osg::Group* group = new osg::Group;
323        group->addChild(geode);
324
325        return group;
326
327    }
328
329    osg::Node* createMovingModel(const osg::Vec3& center, float radius)
330    {
331        float animationLength = 10.0f;
332
333        osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
334
335        osg::Group* model = new osg::Group;
336
337        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
338        if (cessna)
339        {
340            const osg::BoundingSphere& bs = cessna->getBound();
341
342            float size = radius/bs.radius()*0.3f;
343            osg::MatrixTransform* positioned = new osg::MatrixTransform;
344            positioned->setDataVariance(osg::Object::STATIC);
345            positioned->setMatrix(osg::Matrix::translate(-bs.center())*
346                                  osg::Matrix::scale(size,size,size)*
347                                  osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,2.0f));
348
349            positioned->addChild(cessna);
350
351            osg::MatrixTransform* xform = new osg::MatrixTransform;
352            xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
353            xform->addChild(positioned);
354
355            model->addChild(xform);
356        }
357
358        return model;
359    }
360
361    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
362    {
363        osg::Vec3 center(0.0f,0.0f,0.0f);
364        float radius = 100.0f;
365        osg::Vec3 lightPosition(center+osg::Vec3(0.0f,0.0f,radius));
366
367        // the shadower model
368        osg::Node* shadower = createMovingModel(center,radius*0.5f);
369        shadower->setNodeMask(CastsShadowTraversalMask);
370
371        // the shadowed model
372        osg::Node* shadowed = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.25),radius);
373        shadowed->setNodeMask(ReceivesShadowTraversalMask);
374       
375        osg::Group* group = new osg::Group;
376
377        group->addChild(shadowed);
378        group->addChild(shadower);
379       
380        return group;
381    }
382}
383
384namespace ModelThree
385{
386    osg::Group* createModel(osg::ArgumentParser& arguments)
387    {
388        osg::Group* scene = new osg::Group;
389
390        osg::ref_ptr<osg::Geode> geode_1 = new osg::Geode;
391        scene->addChild(geode_1.get());
392
393        osg::ref_ptr<osg::Geode> geode_2 = new osg::Geode;
394        osg::ref_ptr<osg::MatrixTransform> transform_2 = new osg::MatrixTransform;
395        transform_2->addChild(geode_2.get());
396        transform_2->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(45.0f)));
397        scene->addChild(transform_2.get());
398
399        osg::ref_ptr<osg::Geode> geode_3 = new osg::Geode;
400        osg::ref_ptr<osg::MatrixTransform> transform_3 = new osg::MatrixTransform;
401        transform_3->addChild(geode_3.get());
402        transform_3->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(-22.5f)));
403        scene->addChild(transform_3.get());
404
405        const float radius = 0.8f;
406        const float height = 1.0f;
407        osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints;
408        hints->setDetailRatio(2.0f);
409        osg::ref_ptr<osg::ShapeDrawable> shape;
410
411        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -2.0f), 10, 10.0f, 0.1f), hints.get());
412        shape->setColor(osg::Vec4(0.5f, 0.5f, 0.7f, 1.0f));
413        geode_1->addDrawable(shape.get());
414
415        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f, 0.0f, 0.0f), radius * 2), hints.get());
416        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.8f, 1.0f));
417        geode_1->addDrawable(shape.get());
418
419        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
420        shape->setColor(osg::Vec4(0.6f, 0.8f, 0.8f, 1.0f));
421        geode_2->addDrawable(shape.get());
422
423        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
424        shape->setColor(osg::Vec4(0.4f, 0.9f, 0.3f, 1.0f));
425        geode_2->addDrawable(shape.get());
426
427        shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, -3.0f, 0.0f), radius, height), hints.get());
428        shape->setColor(osg::Vec4(0.2f, 0.5f, 0.7f, 1.0f));
429        geode_2->addDrawable(shape.get());
430
431        shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 3.0f, 0.0f), radius, height), hints.get());
432        shape->setColor(osg::Vec4(1.0f, 0.3f, 0.3f, 1.0f));
433        geode_2->addDrawable(shape.get());
434
435        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, 3.0f), 2.0f, 2.0f, 0.1f), hints.get());
436        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.4f, 1.0f));
437        geode_3->addDrawable(shape.get());
438
439        // material
440        osg::ref_ptr<osg::Material> matirial = new osg::Material;
441        matirial->setColorMode(osg::Material::DIFFUSE);
442        matirial->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
443        matirial->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
444        matirial->setShininess(osg::Material::FRONT_AND_BACK, 64.0f);
445        scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), osg::StateAttribute::ON);
446
447        bool withBaseTexture = true;
448        while(arguments.read("--with-base-texture")) { withBaseTexture = true; }
449        while(arguments.read("--no-base-texture")) { withBaseTexture = false; }
450
451        if (withBaseTexture)
452        {
453            scene->getOrCreateStateSet()->setTextureAttributeAndModes( 0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")), osg::StateAttribute::ON);
454        }
455
456        return scene;
457    }
458   
459}
460
461
462osg::Node* createTestModel(osg::ArgumentParser& arguments)
463{
464    if (arguments.read("-1"))
465    {
466        return ModelOne::createModel(arguments);
467    }
468    else if (arguments.read("-2"))
469    {
470        return ModelTwo::createModel(arguments);
471    }
472    else /*if (arguments.read("-3"))*/
473    {
474        return ModelThree::createModel(arguments);
475    }
476   
477}
478
479int main(int argc, char** argv)
480{
481    // use an ArgumentParser object to manage the program arguments.
482    osg::ArgumentParser arguments(&argc, argv);
483
484    // set up the usage document, in case we need to print out how to use this program.
485    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class");
486    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
487    arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
488    arguments.getApplicationUsage()->addCommandLineOption("--positionalLight", "Use a positional light.");
489    arguments.getApplicationUsage()->addCommandLineOption("--directionalLight", "Use a direction light.");
490    arguments.getApplicationUsage()->addCommandLineOption("--noUpdate", "Disable the updating the of light source.");
491    arguments.getApplicationUsage()->addCommandLineOption("--base", "Add a base geometry to test shadows.");
492    arguments.getApplicationUsage()->addCommandLineOption("--sv", "Select ShadowVolume implementation.");
493    arguments.getApplicationUsage()->addCommandLineOption("--sm", "Select ShadowMap implementation.");
494    arguments.getApplicationUsage()->addCommandLineOption("--sm", "Select ShadowMap implementation.");
495//    arguments.getApplicationUsage()->addCommandLineOption("--pssm", "Select ParallelSplitShadowMap implementation.");
496    arguments.getApplicationUsage()->addCommandLineOption("-1", "Use test model one.");
497    arguments.getApplicationUsage()->addCommandLineOption("-2", "Use test model two.");
498    arguments.getApplicationUsage()->addCommandLineOption("-3", "Use test model three.");
499    arguments.getApplicationUsage()->addCommandLineOption("--two-sided", "Use two-sided stencil extension for shadow volumes.");
500    arguments.getApplicationUsage()->addCommandLineOption("--two-pass", "Use two-pass stencil for shadow volumes.");
501
502
503    // construct the viewer.
504    osgViewer::Viewer viewer;
505
506    // if user request help write it out to cout.
507    if (arguments.read("-h") || arguments.read("--help"))
508    {
509        arguments.getApplicationUsage()->write(std::cout);
510        return 1;
511    }
512
513    // default to single threaded during dev work.
514    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
515   
516    while (arguments.read("--SingleThreaded")) viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
517    while (arguments.read("--CullDrawThreadPerContext")) viewer.setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext);
518    while (arguments.read("--DrawThreadPerContext")) viewer.setThreadingModel(osgViewer::Viewer::DrawThreadPerContext);
519    while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) viewer.setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext);
520
521
522    bool postionalLight = true;
523    while (arguments.read("--positionalLight")) postionalLight = true;
524    while (arguments.read("--directionalLight")) postionalLight = false;
525
526    bool updateLightPosition = true;
527    while (arguments.read("--noUpdate")) updateLightPosition = false;
528
529
530    int screenNum = -1;
531    while (arguments.read("--screen", screenNum)) viewer.setUpViewOnSingleScreen(screenNum);
532
533    // set up the camera manipulators.
534    {
535        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
536
537        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
538        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
539        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
540        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
541
542        std::string pathfile;
543        char keyForAnimationPath = '5';
544        while (arguments.read("-p",pathfile))
545        {
546            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
547            if (apm || !apm->valid())
548            {
549                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
550                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
551                keyswitchManipulator->selectMatrixManipulator(num);
552                ++keyForAnimationPath;
553            }
554        }
555
556        viewer.setCameraManipulator( keyswitchManipulator.get() );
557    }
558
559    // add the state manipulator
560    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
561
562    // add stats
563    viewer.addEventHandler( new osgViewer::StatsHandler() );
564
565    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
566    if (model.valid())
567    {
568        model->setNodeMask(CastsShadowTraversalMask | ReceivesShadowTraversalMask);
569    }
570    else
571    {
572        model = createTestModel(arguments);
573    }
574
575    // get the bounds of the model.   
576    osg::ComputeBoundsVisitor cbbv;
577    model->accept(cbbv);
578    osg::BoundingBox bb = cbbv.getBoundingBox();
579
580    osg::Vec4 lightpos;
581   
582    if (postionalLight)
583    {
584        lightpos.set(bb.center().x(), bb.center().y(), bb.zMax() + bb.radius()  ,1.0f);
585    }
586    else
587    {
588        lightpos.set(0.5f,0.25f,0.8f,0.0f);
589    }
590
591
592    osg::ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene;
593   
594    shadowedScene->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask);
595    shadowedScene->setCastsShadowTraversalMask(CastsShadowTraversalMask);
596   
597   
598    if (arguments.read("--sv"))
599    {
600        // hint to tell viewer to request stencil buffer when setting up windows
601        osg::DisplaySettings::instance()->setMinimumNumStencilBits(8);
602
603        osg::ref_ptr<osgShadow::ShadowVolume> sv = new osgShadow::ShadowVolume;
604        sv->setDynamicShadowVolumes(updateLightPosition);
605        while (arguments.read("--two-sided")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_SIDED);
606        while (arguments.read("--two-pass")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_PASS);
607
608        shadowedScene->setShadowTechnique(sv.get());
609    }
610    else if (arguments.read("--st"))
611    {
612        osg::ref_ptr<osgShadow::ShadowTexture> st = new osgShadow::ShadowTexture;
613        shadowedScene->setShadowTechnique(st.get());
614    }
615#if 0   
616    else if (arguments.read("--pssm"))
617    {
618        osg::ref_ptr<osgShadow::ParallelSplitShadowMap> pssm = new osgShadow::ParallelSplitShadowMap;
619        shadowedScene->setShadowTechnique(pssm.get());
620    }
621#endif   
622    else /* if (arguments.read("--sm")) */
623    {
624        osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap;
625        shadowedScene->setShadowTechnique(sm.get());
626    }
627
628    if ( arguments.read("--base"))
629    {
630
631        osg::Geode* geode = new osg::Geode;
632       
633        osg::Vec3 widthVec(bb.radius(), 0.0f, 0.0f);
634        osg::Vec3 depthVec(0.0f, bb.radius(), 0.0f);
635        osg::Vec3 centerBase( (bb.xMin()+bb.xMax())*0.5f, (bb.yMin()+bb.yMax())*0.5f, bb.zMin()-bb.radius()*0.1f );
636       
637        geode->addDrawable( osg::createTexturedQuadGeometry( centerBase-widthVec*1.5f-depthVec*1.5f,
638                                                             widthVec*3.0f, depthVec*3.0f) );
639                                                             
640        geode->setNodeMask(shadowedScene->getReceivesShadowTraversalMask());
641       
642        geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")));
643
644        shadowedScene->addChild(geode);
645    }
646
647    osg::ref_ptr<osg::LightSource> ls = new osg::LightSource;
648    ls->getLight()->setPosition(lightpos);
649    if ( arguments.read("--coloured-light"))
650    {
651        ls->getLight()->setAmbient(osg::Vec4(1.0,0.0,0.0,1.0));
652        ls->getLight()->setDiffuse(osg::Vec4(0.0,1.0,0.0,1.0));
653    }
654    else
655    {
656        ls->getLight()->setAmbient(osg::Vec4(0.2,0.2,0.2,1.0));
657        ls->getLight()->setDiffuse(osg::Vec4(0.8,0.8,0.8,1.0));
658    }
659   
660    shadowedScene->addChild(model.get());
661    shadowedScene->addChild(ls.get());
662   
663    viewer.setSceneData(shadowedScene.get());
664   
665    // create the windows and run the threads.
666    viewer.realize();
667
668    // osgDB::writeNodeFile(*group,"test.osg");
669
670    while (!viewer.done())
671    {
672        if (updateLightPosition)
673        {
674            float t = viewer.getFrameStamp()->getSimulationTime();
675            if (postionalLight)
676            {
677                lightpos.set(bb.center().x()+sinf(t)*bb.radius(), bb.center().y() + cosf(t)*bb.radius(), bb.zMax() + bb.radius()  ,1.0f);
678            }
679            else
680            {
681                lightpos.set(sinf(t),cosf(t),1.0f,0.0f);
682            }
683            ls->getLight()->setPosition(lightpos);
684        }
685
686        viewer.frame();
687    }
688   
689    return 0;
690}
Note: See TracBrowser for help on using the browser.