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

Revision 12189, 38.2 kB (checked in by robert, 3 years ago)

From Wojciech Lewandowski, intial cut at new TrapezoidalShadowMap? ShadowTechnique?

  • 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#include <osgShadow/SoftShadowMap>
43#include <osgShadow/ParallelSplitShadowMap>
44#include <osgShadow/LightSpacePerspectiveShadowMap>
45#include <osgShadow/TrapezoidalShadowMap>
46#include <osgShadow/StandardShadowMap>
47
48#include <osgDB/ReadFile>
49#include <osgDB/WriteFile>
50
51#include <iostream>
52
53
54// for the grid data..
55#include "terrain_coords.h"
56// for the model number four - island scene
57#include "IslandScene.h"
58
59
60class ChangeFOVHandler : public osgGA::GUIEventHandler
61{
62public:
63    ChangeFOVHandler(osg::Camera* camera)
64        : _camera(camera)
65    {
66        double fovy, aspectRatio, zNear, zFar;
67        _camera->getProjectionMatrix().getPerspective(fovy, aspectRatio, zNear, zFar);
68        std::cout << "FOV is " << fovy << std::endl;
69    }
70
71    /** Deprecated, Handle events, return true if handled, false otherwise. */
72    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
73    {
74        if (ea.getEventType() == osgGA::GUIEventAdapter::KEYUP)
75        {
76            if (ea.getKey() == '-' || ea.getKey() == '=' || ea.getKey() == '0')
77            {
78                double fovy, aspectRatio, zNear, zFar;
79                _camera->getProjectionMatrix().getPerspective(fovy, aspectRatio, zNear, zFar);
80
81                if (ea.getKey() == '-')
82                {
83                    fovy -= 5.0;
84                }
85
86                if (ea.getKey() == '=')
87                {
88                    fovy += 5.0;
89                }
90
91                if (ea.getKey() == '0')
92                {
93                    fovy = 45.0;
94                }
95
96                std::cout << "Setting FOV to " << fovy << std::endl;
97                _camera->getProjectionMatrix().makePerspective(fovy, aspectRatio, zNear, zFar);
98
99                return true;
100            }
101        }
102
103        return false;
104    }
105
106    osg::ref_ptr<osg::Camera> _camera;
107};
108
109
110class DumpShadowVolumesHandler : public osgGA::GUIEventHandler
111{
112public:
113    DumpShadowVolumesHandler(  )
114    {
115        set( false );
116    }
117
118    bool get() { return _value; }
119    void set( bool value ) { _value = value; }
120
121    /** Deprecated, Handle events, return true if handled, false otherwise. */
122    virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
123    {
124        if (ea.getEventType() == osgGA::GUIEventAdapter::KEYUP)
125        {
126            if (ea.getKey() == 'D' )
127            {
128                set( true );
129                return true;
130            }
131        }
132
133        return false;
134    }
135
136    bool  _value;
137};
138
139
140static int ReceivesShadowTraversalMask = 0x1;
141static int CastsShadowTraversalMask = 0x2;
142
143namespace ModelOne
144{
145
146    enum Faces
147    {
148        FRONT_FACE = 1,
149        BACK_FACE = 2,
150        LEFT_FACE = 4,
151        RIGHT_FACE = 8,
152        TOP_FACE = 16,
153        BOTTOM_FACE = 32
154    };
155
156    osg::Node* createCube(unsigned int mask)
157    {
158        osg::Geode* geode = new osg::Geode;
159
160        osg::Geometry* geometry = new osg::Geometry;
161        geode->addDrawable(geometry);
162
163        osg::Vec3Array* vertices = new osg::Vec3Array;
164        geometry->setVertexArray(vertices);
165
166        osg::Vec3Array* normals = new osg::Vec3Array;
167        geometry->setNormalArray(normals);
168        geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
169
170        osg::Vec4Array* colours = new osg::Vec4Array;
171        geometry->setColorArray(colours);
172        geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
173        colours->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
174
175
176        osg::Vec3 origin(0.0f,0.0f,0.0f);
177        osg::Vec3 dx(2.0f,0.0f,0.0f);
178        osg::Vec3 dy(0.0f,1.0f,0.0f);
179        osg::Vec3 dz(0.0f,0.0f,1.0f);
180
181        osg::Vec3 px(1.0f,0.0,0.0f);
182        osg::Vec3 nx(-1.0f,0.0,0.0f);
183        osg::Vec3 py(0.0f,1.0f,0.0f);
184        osg::Vec3 ny(0.0f,-1.0f,0.0f);
185        osg::Vec3 pz(0.0f,0.0f,1.0f);
186        osg::Vec3 nz(0.0f,0.0f,-1.0f);
187
188        if (mask & FRONT_FACE)
189        {
190            // front face
191            vertices->push_back(origin);
192            vertices->push_back(origin+dx);
193            vertices->push_back(origin+dx+dz);
194            vertices->push_back(origin+dz);
195            normals->push_back(ny);
196            normals->push_back(ny);
197            normals->push_back(ny);
198            normals->push_back(ny);
199        }
200
201        if (mask & BACK_FACE)
202        {
203            // back face
204            vertices->push_back(origin+dy);
205            vertices->push_back(origin+dy+dz);
206            vertices->push_back(origin+dy+dx+dz);
207            vertices->push_back(origin+dy+dx);
208            normals->push_back(py);
209            normals->push_back(py);
210            normals->push_back(py);
211            normals->push_back(py);
212        }
213
214        if (mask & LEFT_FACE)
215        {
216            // left face
217            vertices->push_back(origin+dy);
218            vertices->push_back(origin);
219            vertices->push_back(origin+dz);
220            vertices->push_back(origin+dy+dz);
221            normals->push_back(nx);
222            normals->push_back(nx);
223            normals->push_back(nx);
224            normals->push_back(nx);
225        }
226
227        if (mask & RIGHT_FACE)
228        {
229            // right face
230            vertices->push_back(origin+dx+dy);
231            vertices->push_back(origin+dx+dy+dz);
232            vertices->push_back(origin+dx+dz);
233            vertices->push_back(origin+dx);
234            normals->push_back(px);
235            normals->push_back(px);
236            normals->push_back(px);
237            normals->push_back(px);
238        }
239
240        if (mask & TOP_FACE)
241        {
242            // top face
243            vertices->push_back(origin+dz);
244            vertices->push_back(origin+dz+dx);
245            vertices->push_back(origin+dz+dx+dy);
246            vertices->push_back(origin+dz+dy);
247            normals->push_back(pz);
248            normals->push_back(pz);
249            normals->push_back(pz);
250            normals->push_back(pz);
251        }
252
253        if (mask & BOTTOM_FACE)
254        {
255            // bottom face
256            vertices->push_back(origin);
257            vertices->push_back(origin+dy);
258            vertices->push_back(origin+dx+dy);
259            vertices->push_back(origin+dx);
260            normals->push_back(nz);
261            normals->push_back(nz);
262            normals->push_back(nz);
263            normals->push_back(nz);
264        }
265
266        geometry->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, vertices->size()));
267
268        return geode;
269    }
270
271    class SwitchHandler : public osgGA::GUIEventHandler
272    {
273    public:
274
275        SwitchHandler():
276            _childNum(0) {}
277
278        virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& /*aa*/, osg::Object* object, osg::NodeVisitor* /*nv*/)
279        {
280            osg::Switch* sw = dynamic_cast<osg::Switch*>(object);
281            if (!sw) return false;
282
283            if (ea.getHandled()) return false;
284
285            switch(ea.getEventType())
286            {
287                case(osgGA::GUIEventAdapter::KEYDOWN):
288                {
289                    if (ea.getKey()=='n')
290                    {
291                        ++_childNum;
292                        if (_childNum >= sw->getNumChildren()) _childNum = 0;
293
294                        sw->setSingleChildOn(_childNum);
295                        return true;
296                    }
297                    break;
298                }
299                default:
300                    break;
301            }
302            return false;
303        }
304
305    protected:
306
307        virtual ~SwitchHandler() {}
308        unsigned int    _childNum;
309
310    };
311
312
313    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
314    {
315        osg::Switch* sw = new osg::Switch;
316        sw->setEventCallback(new ModelOne::SwitchHandler);
317
318        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE), true);
319        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE), false);
320        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE), false);
321        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE), false);
322        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE), false);
323        sw->addChild(ModelOne::createCube(ModelOne::FRONT_FACE | ModelOne::BACK_FACE | ModelOne::LEFT_FACE | ModelOne::RIGHT_FACE | ModelOne::TOP_FACE | ModelOne::BOTTOM_FACE), false);
324
325        return sw;
326    }
327}
328
329namespace ModelTwo
330{
331    osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
332    {
333        // set up the animation path
334        osg::AnimationPath* animationPath = new osg::AnimationPath;
335        animationPath->setLoopMode(osg::AnimationPath::LOOP);
336
337        int numSamples = 40;
338        float yaw = 0.0f;
339        float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
340        float roll = osg::inDegrees(30.0f);
341
342        double time=0.0f;
343        double time_delta = looptime/(double)numSamples;
344        for(int i=0;i<numSamples;++i)
345        {
346            osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
347            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)));
348
349            animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
350
351            yaw += yaw_delta;
352            time += time_delta;
353
354        }
355        return animationPath;
356    }
357
358    osg::Node* createBase(const osg::Vec3& center,float radius)
359    {
360
361        osg::Geode* geode = new osg::Geode;
362
363        // set up the texture of the base.
364        osg::StateSet* stateset = new osg::StateSet();
365        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
366        if (image)
367        {
368            osg::Texture2D* texture = new osg::Texture2D;
369            texture->setImage(image);
370            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
371        }
372
373        geode->setStateSet( stateset );
374
375
376        osg::HeightField* grid = new osg::HeightField;
377        grid->allocate(38,39);
378        grid->setOrigin(center+osg::Vec3(-radius,-radius,0.0f));
379        grid->setXInterval(radius*2.0f/(float)(38-1));
380        grid->setYInterval(radius*2.0f/(float)(39-1));
381
382        float minHeight = FLT_MAX;
383        float maxHeight = -FLT_MAX;
384
385
386        unsigned int r;
387        for(r=0;r<39;++r)
388        {
389            for(unsigned int c=0;c<38;++c)
390            {
391                float h = vertex[r+c*39][2];
392                if (h>maxHeight) maxHeight=h;
393                if (h<minHeight) minHeight=h;
394            }
395        }
396
397        float hieghtScale = radius*0.5f/(maxHeight-minHeight);
398        float hieghtOffset = -(minHeight+maxHeight)*0.5f;
399
400        for(r=0;r<39;++r)
401        {
402            for(unsigned int c=0;c<38;++c)
403            {
404                float h = vertex[r+c*39][2];
405                grid->setHeight(c,r,(h+hieghtOffset)*hieghtScale);
406            }
407        }
408
409        geode->addDrawable(new osg::ShapeDrawable(grid));
410
411        osg::Group* group = new osg::Group;
412        group->addChild(geode);
413
414        return group;
415
416    }
417
418    osg::Node* createMovingModel(const osg::Vec3& center, float radius)
419    {
420        float animationLength = 10.0f;
421
422        osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
423
424        osg::Group* model = new osg::Group;
425
426        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
427        if (cessna)
428        {
429            const osg::BoundingSphere& bs = cessna->getBound();
430
431            float size = radius/bs.radius()*0.3f;
432            osg::MatrixTransform* positioned = new osg::MatrixTransform;
433            positioned->setDataVariance(osg::Object::STATIC);
434            positioned->setMatrix(osg::Matrix::translate(-bs.center())*
435                                  osg::Matrix::scale(size,size,size)*
436                                  osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,2.0f));
437
438            positioned->addChild(cessna);
439
440            osg::MatrixTransform* xform = new osg::MatrixTransform;
441            xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
442            xform->addChild(positioned);
443
444            model->addChild(xform);
445        }
446
447        return model;
448    }
449
450    osg::Node* createModel(osg::ArgumentParser& /*arguments*/)
451    {
452        osg::Vec3 center(0.0f,0.0f,0.0f);
453        float radius = 100.0f;
454        osg::Vec3 lightPosition(center+osg::Vec3(0.0f,0.0f,radius));
455
456        // the shadower model
457        osg::Node* shadower = createMovingModel(center,radius*0.5f);
458        shadower->setNodeMask(CastsShadowTraversalMask);
459
460        // the shadowed model
461        osg::Node* shadowed = createBase(center-osg::Vec3(0.0f,0.0f,radius*0.25),radius);
462        shadowed->setNodeMask(ReceivesShadowTraversalMask);
463
464        osg::Group* group = new osg::Group;
465
466        group->addChild(shadowed);
467        group->addChild(shadower);
468
469        return group;
470    }
471}
472
473namespace ModelThree
474{
475    osg::Group* createModel(osg::ArgumentParser& arguments)
476    {
477        osg::Group* scene = new osg::Group;
478
479        osg::ref_ptr<osg::Geode> geode_1 = new osg::Geode;
480        scene->addChild(geode_1.get());
481
482        osg::ref_ptr<osg::Geode> geode_2 = new osg::Geode;
483        osg::ref_ptr<osg::MatrixTransform> transform_2 = new osg::MatrixTransform;
484        transform_2->addChild(geode_2.get());
485//        transform_2->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(45.0f)));
486        scene->addChild(transform_2.get());
487
488        osg::ref_ptr<osg::Geode> geode_3 = new osg::Geode;
489        osg::ref_ptr<osg::MatrixTransform> transform_3 = new osg::MatrixTransform;
490        transform_3->addChild(geode_3.get());
491//        transform_3->setUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(0, 0, 0), osg::Z_AXIS, osg::inDegrees(-22.5f)));
492        scene->addChild(transform_3.get());
493
494        const float radius = 0.8f;
495        const float height = 1.0f;
496        osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints;
497        hints->setDetailRatio(2.0f);
498        osg::ref_ptr<osg::ShapeDrawable> shape;
499
500        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -2.0f), 10, 10.0f, 0.1f), hints.get());
501        shape->setColor(osg::Vec4(0.5f, 0.5f, 0.7f, 1.0f));
502        geode_1->addDrawable(shape.get());
503
504        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f, 0.0f, 0.0f), radius * 2), hints.get());
505        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.8f, 1.0f));
506        geode_1->addDrawable(shape.get());
507
508        shape = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
509        shape->setColor(osg::Vec4(0.6f, 0.8f, 0.8f, 1.0f));
510        geode_2->addDrawable(shape.get());
511
512        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
513        shape->setColor(osg::Vec4(0.4f, 0.9f, 0.3f, 1.0f));
514        geode_2->addDrawable(shape.get());
515
516        shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, -3.0f, 0.0f), radius, height), hints.get());
517        shape->setColor(osg::Vec4(0.2f, 0.5f, 0.7f, 1.0f));
518        geode_2->addDrawable(shape.get());
519
520        shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 3.0f, 0.0f), radius, height), hints.get());
521        shape->setColor(osg::Vec4(1.0f, 0.3f, 0.3f, 1.0f));
522        geode_2->addDrawable(shape.get());
523
524        shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, 3.0f), 2.0f, 2.0f, 0.1f), hints.get());
525        shape->setColor(osg::Vec4(0.8f, 0.8f, 0.4f, 1.0f));
526        geode_3->addDrawable(shape.get());
527
528        // material
529        osg::ref_ptr<osg::Material> matirial = new osg::Material;
530        matirial->setColorMode(osg::Material::DIFFUSE);
531        matirial->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
532        matirial->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
533        matirial->setShininess(osg::Material::FRONT_AND_BACK, 64.0f);
534        scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), osg::StateAttribute::ON);
535
536        bool withBaseTexture = true;
537        while(arguments.read("--with-base-texture")) { withBaseTexture = true; }
538        while(arguments.read("--no-base-texture")) { withBaseTexture = false; }
539
540        if (withBaseTexture)
541        {
542            scene->getOrCreateStateSet()->setTextureAttributeAndModes( 0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")), osg::StateAttribute::ON);
543        }
544
545        return scene;
546    }
547
548}
549
550
551osg::Node* createTestModel(osg::ArgumentParser& arguments)
552{
553    if (arguments.read("-1"))
554    {
555        return ModelOne::createModel(arguments);
556    }
557    else if (arguments.read("-2"))
558    {
559        return ModelTwo::createModel(arguments);
560    }
561    else if (arguments.read("-4"))
562    {
563        return ModelFour::createModel(arguments);
564    }
565    else /*if (arguments.read("-3"))*/
566    {
567        return ModelThree::createModel(arguments);
568    }
569
570}
571
572int main(int argc, char** argv)
573{
574    // use an ArgumentParser object to manage the program arguments.
575    osg::ArgumentParser arguments(&argc, argv);
576
577    // set up the usage document, in case we need to print out how to use this program.
578    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class");
579    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
580    arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
581    arguments.getApplicationUsage()->addCommandLineOption("--positionalLight", "Use a positional light.");
582    arguments.getApplicationUsage()->addCommandLineOption("--directionalLight", "Use a direction light.");
583    arguments.getApplicationUsage()->addCommandLineOption("--noUpdate", "Disable the updating the of light source.");
584
585    arguments.getApplicationUsage()->addCommandLineOption("--castsShadowMask", "Override default castsShadowMask (default - 0x2)");
586    arguments.getApplicationUsage()->addCommandLineOption("--receivesShadowMask", "Override default receivesShadowMask (default - 0x1)");
587
588    arguments.getApplicationUsage()->addCommandLineOption("--base", "Add a base geometry to test shadows.");
589    arguments.getApplicationUsage()->addCommandLineOption("--sv", "Select ShadowVolume implementation.");
590    arguments.getApplicationUsage()->addCommandLineOption("--ssm", "Select SoftShadowMap implementation.");
591    arguments.getApplicationUsage()->addCommandLineOption("--sm", "Select ShadowMap implementation.");
592
593    arguments.getApplicationUsage()->addCommandLineOption("--pssm", "Select ParallelSplitShadowMap implementation.");//ADEGLI
594    arguments.getApplicationUsage()->addCommandLineOption("--mapcount", "ParallelSplitShadowMap texture count.");//ADEGLI
595    arguments.getApplicationUsage()->addCommandLineOption("--mapres", "ParallelSplitShadowMap texture resolution.");//ADEGLI
596    arguments.getApplicationUsage()->addCommandLineOption("--debug-color", "ParallelSplitShadowMap display debugging color (only the first 3 maps are color r=0,g=1,b=2.");//ADEGLI
597    arguments.getApplicationUsage()->addCommandLineOption("--minNearSplit", "ParallelSplitShadowMap shadow map near offset.");//ADEGLI
598    arguments.getApplicationUsage()->addCommandLineOption("--maxFarDist", "ParallelSplitShadowMap max far distance to shadow.");//ADEGLI
599    arguments.getApplicationUsage()->addCommandLineOption("--moveVCamFactor", "ParallelSplitShadowMap move the virtual frustum behind the real camera, (also back ground object can cast shadow).");//ADEGLI
600    arguments.getApplicationUsage()->addCommandLineOption("--PolyOffset-Factor", "ParallelSplitShadowMap set PolygonOffset factor.");//ADEGLI
601    arguments.getApplicationUsage()->addCommandLineOption("--PolyOffset-Unit", "ParallelSplitShadowMap set PolygonOffset unit.");//ADEGLI
602
603    arguments.getApplicationUsage()->addCommandLineOption("--lispsm", "Select LightSpacePerspectiveShadowMap implementation.");
604    arguments.getApplicationUsage()->addCommandLineOption("--tsm", "Select TrapezoidalShadowMap implementation.");
605    arguments.getApplicationUsage()->addCommandLineOption("--msm", "Select MinimalShadowMap implementation.");
606    arguments.getApplicationUsage()->addCommandLineOption("--ViewBounds", "MSM, LiSPSM & TSM optimize shadow for view frustum (weakest option)");
607    arguments.getApplicationUsage()->addCommandLineOption("--CullBounds", "MSM, LiSPSM & TSM optimize shadow for bounds of culled objects in view frustum (better option).");
608    arguments.getApplicationUsage()->addCommandLineOption("--DrawBounds", "MSM, LiSPSM & TSM optimize shadow for bounds of predrawn pixels in view frustum (best & default).");
609    arguments.getApplicationUsage()->addCommandLineOption("--mapres", "MSM, LiSPSM & TSM texture resolution.");
610    arguments.getApplicationUsage()->addCommandLineOption("--maxFarDist", "MSM, LiSPSM & TSM max far distance to shadow.");
611    arguments.getApplicationUsage()->addCommandLineOption("--moveVCamFactor", "MSM, LiSPSM & TSM move the virtual frustum behind the real camera, (also back ground object can cast shadow).");
612    arguments.getApplicationUsage()->addCommandLineOption("--minLightMargin", "MSM, LiSPSM t& TSM the same as --moveVCamFactor.");
613
614    arguments.getApplicationUsage()->addCommandLineOption("-1", "Use test model one.");
615    arguments.getApplicationUsage()->addCommandLineOption("-2", "Use test model two.");
616    arguments.getApplicationUsage()->addCommandLineOption("-3", "Use test model three (default).");
617    arguments.getApplicationUsage()->addCommandLineOption("-4", "Use test model four - island scene.");
618    arguments.getApplicationUsage()->addCommandLineOption("--two-sided", "Use two-sided stencil extension for shadow volumes.");
619    arguments.getApplicationUsage()->addCommandLineOption("--two-pass", "Use two-pass stencil for shadow volumes.");
620
621    // construct the viewer.
622    osgViewer::Viewer viewer(arguments);
623
624    // if user request help write it out to cout.
625    if (arguments.read("-h") || arguments.read("--help"))
626    {
627        arguments.getApplicationUsage()->write(std::cout);
628        return 1;
629    }
630   
631    float fov = 0.0;
632    while (arguments.read("--fov",fov)) {}
633
634    osg::Vec4 lightpos(0.0,0.0,1,0.0);
635    while (arguments.read("--positionalLight")) { lightpos.set(0.5,0.5,1.5,1.0); }
636    while (arguments.read("--directionalLight")) { lightpos.set(0.0,0.0,1,0.0); }
637
638    while ( arguments.read("--light-pos", lightpos.x(), lightpos.y(), lightpos.z(), lightpos.w())) {}
639    while ( arguments.read("--light-pos", lightpos.x(), lightpos.y(), lightpos.z())) { lightpos.w()=1.0; }
640    while ( arguments.read("--light-dir", lightpos.x(), lightpos.y(), lightpos.z())) { lightpos.w()=0.0; }
641
642
643    while (arguments.read("--castsShadowMask", CastsShadowTraversalMask ));
644    while (arguments.read("--receivesShadowMask", ReceivesShadowTraversalMask ));
645
646    bool updateLightPosition = true;
647    while (arguments.read("--noUpdate")) updateLightPosition = false;
648
649    // set up the camera manipulators.
650    {
651        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
652
653        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
654        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
655        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
656        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
657
658        std::string pathfile;
659        char keyForAnimationPath = '5';
660        while (arguments.read("-p",pathfile))
661        {
662            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
663            if (apm || !apm->valid())
664            {
665                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
666                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
667                keyswitchManipulator->selectMatrixManipulator(num);
668                ++keyForAnimationPath;
669            }
670        }
671
672        viewer.setCameraManipulator( keyswitchManipulator.get() );
673    }
674
675    // add the state manipulator
676    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
677
678    // add stats
679    viewer.addEventHandler( new osgViewer::StatsHandler() );
680
681    // add the record camera path handler
682    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);
683
684    // add the window size toggle handler
685    viewer.addEventHandler(new osgViewer::WindowSizeHandler);
686
687    // add the threading handler
688    viewer.addEventHandler( new osgViewer::ThreadingHandler() );
689
690    osg::ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene;
691
692    shadowedScene->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask);
693    shadowedScene->setCastsShadowTraversalMask(CastsShadowTraversalMask);
694
695    osg::ref_ptr<osgShadow::MinimalShadowMap> msm = NULL;
696    if (arguments.read("--sv"))
697    {
698        // hint to tell viewer to request stencil buffer when setting up windows
699        osg::DisplaySettings::instance()->setMinimumNumStencilBits(8);
700
701        osg::ref_ptr<osgShadow::ShadowVolume> sv = new osgShadow::ShadowVolume;
702        sv->setDynamicShadowVolumes(updateLightPosition);
703        while (arguments.read("--two-sided")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_SIDED);
704        while (arguments.read("--two-pass")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_PASS);
705
706        shadowedScene->setShadowTechnique(sv.get());
707    }
708    else if (arguments.read("--st"))
709    {
710        osg::ref_ptr<osgShadow::ShadowTexture> st = new osgShadow::ShadowTexture;
711        shadowedScene->setShadowTechnique(st.get());
712    }
713    else if (arguments.read("--stsm"))
714    {
715        osg::ref_ptr<osgShadow::StandardShadowMap> st = new osgShadow::StandardShadowMap;
716        shadowedScene->setShadowTechnique(st.get());
717    }
718    else if (arguments.read("--pssm"))
719    {
720        int mapcount = 3;
721        while (arguments.read("--mapcount", mapcount));
722        osg::ref_ptr<osgShadow::ParallelSplitShadowMap> pssm = new osgShadow::ParallelSplitShadowMap(NULL,mapcount);
723
724        int mapres = 1024;
725        while (arguments.read("--mapres", mapres))
726            pssm->setTextureResolution(mapres);
727
728        while (arguments.read("--debug-color")) { pssm->setDebugColorOn(); }
729
730
731        int minNearSplit=0;
732        while (arguments.read("--minNearSplit", minNearSplit))
733            if ( minNearSplit > 0 ) {
734                pssm->setMinNearDistanceForSplits(minNearSplit);
735                std::cout << "ParallelSplitShadowMap : setMinNearDistanceForSplits(" << minNearSplit <<")" << std::endl;
736            }
737
738        int maxfardist = 0;
739        while (arguments.read("--maxFarDist", maxfardist))
740            if ( maxfardist > 0 ) {
741                pssm->setMaxFarDistance(maxfardist);
742                std::cout << "ParallelSplitShadowMap : setMaxFarDistance(" << maxfardist<<")" << std::endl;
743            }
744
745        int moveVCamFactor = 0;
746        while (arguments.read("--moveVCamFactor", moveVCamFactor))
747            if ( maxfardist > 0 ) {
748                pssm->setMoveVCamBehindRCamFactor(moveVCamFactor);
749                std::cout << "ParallelSplitShadowMap : setMoveVCamBehindRCamFactor(" << moveVCamFactor<<")" << std::endl;
750            }
751
752
753       
754        double polyoffsetfactor = pssm->getPolygonOffset().x();
755        double polyoffsetunit   = pssm->getPolygonOffset().y();
756        while (arguments.read("--PolyOffset-Factor", polyoffsetfactor));
757        while (arguments.read("--PolyOffset-Unit", polyoffsetunit));
758        pssm->setPolygonOffset(osg::Vec2(polyoffsetfactor,polyoffsetunit));
759
760        shadowedScene->setShadowTechnique(pssm.get());
761    }
762    else if (arguments.read("--ssm"))
763    {
764        osg::ref_ptr<osgShadow::SoftShadowMap> sm = new osgShadow::SoftShadowMap;
765        shadowedScene->setShadowTechnique(sm.get());
766    }
767    else if ( arguments.read("--lispsm") )
768    {
769        if( arguments.read( "--ViewBounds" ) )
770            msm = new osgShadow::LightSpacePerspectiveShadowMapVB;
771        else if( arguments.read( "--CullBounds" ) )
772            msm = new osgShadow::LightSpacePerspectiveShadowMapCB;
773        else // if( arguments.read( "--DrawBounds" ) ) // default
774            msm = new osgShadow::LightSpacePerspectiveShadowMapDB;
775    }
776    else if( arguments.read("--tsm") )
777    {
778       if( arguments.read( "--ViewBounds" ) )
779            msm = new osgShadow::TrapezoidalShadowMapVB;
780       else if( arguments.read( "--CullBounds" ) )
781            msm = new osgShadow::TrapezoidalShadowMapCB;
782       else // if( arguments.read( "--DrawBounds" ) )
783            msm = new osgShadow::TrapezoidalShadowMapDB;
784    }
785    else if( arguments.read("--msm") )
786    {
787       if( arguments.read( "--ViewBounds" ) )
788            msm = new osgShadow::MinimalShadowMap;
789       else if( arguments.read( "--CullBounds" ) )
790            msm = new osgShadow::MinimalCullBoundsShadowMap;
791       else // if( arguments.read( "--DrawBounds" ) ) // default
792            msm = new osgShadow::MinimalDrawBoundsShadowMap;
793    }
794    else /* if (arguments.read("--sm")) */
795    {
796        osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap;
797        shadowedScene->setShadowTechnique(sm.get());
798
799        int mapres = 1024;
800        while (arguments.read("--mapres", mapres))
801            sm->setTextureSize(osg::Vec2s(mapres,mapres));
802    }
803
804    if( msm )// Set common MSM & TSM & LISPSM arguments
805    {
806        shadowedScene->setShadowTechnique( msm.get() );
807        while( arguments.read("--debugHUD") )           
808            msm->setDebugDraw( true );
809
810        float minLightMargin = 10.f;
811        float maxFarPlane = 0;
812        unsigned int texSize = 1024;
813        unsigned int baseTexUnit = 0;
814        unsigned int shadowTexUnit = 1;
815
816        while ( arguments.read("--moveVCamFactor", minLightMargin ) );
817        while ( arguments.read("--minLightMargin", minLightMargin ) );
818        while ( arguments.read("--maxFarDist", maxFarPlane ) );
819        while ( arguments.read("--mapres", texSize ));
820        while ( arguments.read("--baseTextureUnit", baseTexUnit) );
821        while ( arguments.read("--shadowTextureUnit", shadowTexUnit) );
822
823        msm->setMinLightMargin( minLightMargin );
824        msm->setMaxFarPlane( maxFarPlane );
825        msm->setTextureSize( osg::Vec2s( texSize, texSize ) );
826        msm->setShadowTextureCoordIndex( shadowTexUnit );
827        msm->setShadowTextureUnit( shadowTexUnit );
828        msm->setBaseTextureCoordIndex( baseTexUnit );
829        msm->setBaseTextureUnit( baseTexUnit );
830    }
831
832    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
833    if (model.valid())
834    {
835        model->setNodeMask(CastsShadowTraversalMask | ReceivesShadowTraversalMask);
836    }
837    else
838    {
839        model = createTestModel(arguments);
840    }
841
842    // get the bounds of the model.
843    osg::ComputeBoundsVisitor cbbv;
844    model->accept(cbbv);
845    osg::BoundingBox bb = cbbv.getBoundingBox();
846
847    if (lightpos.w()==1.0)
848    {
849        lightpos.x() = bb.xMin()+(bb.xMax()-bb.xMin())*lightpos.x();
850        lightpos.y() = bb.yMin()+(bb.yMax()-bb.yMin())*lightpos.y();
851        lightpos.z() = bb.zMin()+(bb.zMax()-bb.zMin())*lightpos.z();
852    }
853     
854    if ( arguments.read("--base"))
855    {
856
857        osg::Geode* geode = new osg::Geode;
858
859        osg::Vec3 widthVec(bb.radius(), 0.0f, 0.0f);
860        osg::Vec3 depthVec(0.0f, bb.radius(), 0.0f);
861        osg::Vec3 centerBase( (bb.xMin()+bb.xMax())*0.5f, (bb.yMin()+bb.yMax())*0.5f, bb.zMin()-bb.radius()*0.1f );
862
863        geode->addDrawable( osg::createTexturedQuadGeometry( centerBase-widthVec*1.5f-depthVec*1.5f,
864                                                             widthVec*3.0f, depthVec*3.0f) );
865
866        geode->setNodeMask(shadowedScene->getReceivesShadowTraversalMask());
867
868        geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb")));
869
870        shadowedScene->addChild(geode);
871    }
872
873    osg::ref_ptr<osg::LightSource> ls = new osg::LightSource;
874    ls->getLight()->setPosition(lightpos);
875
876    bool spotlight = false;
877    if (arguments.read("--spotLight"))
878    {
879        spotlight = true;
880
881        osg::Vec3 center = bb.center();
882        osg::Vec3 lightdir = center - osg::Vec3(lightpos.x(), lightpos.y(), lightpos.z());
883        lightdir.normalize();
884        ls->getLight()->setDirection(lightdir);
885        ls->getLight()->setSpotCutoff(25.0f);
886
887        //set the LightSource, only for checking, there is only 1 light in the scene
888        osgShadow::ShadowMap* shadowMap = dynamic_cast<osgShadow::ShadowMap*>(shadowedScene->getShadowTechnique());
889        if( shadowMap ) shadowMap->setLight(ls.get());
890    }
891
892    if ( arguments.read("--coloured-light"))
893    {
894        ls->getLight()->setAmbient(osg::Vec4(1.0,0.0,0.0,1.0));
895        ls->getLight()->setDiffuse(osg::Vec4(0.0,1.0,0.0,1.0));
896    }
897    else
898    {
899        ls->getLight()->setAmbient(osg::Vec4(0.2,0.2,0.2,1.0));
900        ls->getLight()->setDiffuse(osg::Vec4(0.8,0.8,0.8,1.0));
901    }
902
903    shadowedScene->addChild(model.get());
904    shadowedScene->addChild(ls.get());
905
906    viewer.setSceneData(shadowedScene.get());
907
908    osg::ref_ptr< DumpShadowVolumesHandler > dumpShadowVolumes = new DumpShadowVolumesHandler;
909
910    viewer.addEventHandler(new ChangeFOVHandler(viewer.getCamera()));
911    viewer.addEventHandler( dumpShadowVolumes.get() );
912
913    // create the windows and run the threads.
914    viewer.realize();
915   
916    if (fov!=0.0)
917    {
918        double fovy, aspectRatio, zNear, zFar;
919        viewer.getCamera()->getProjectionMatrix().getPerspective(fovy, aspectRatio, zNear, zFar);
920
921        std::cout << "Setting FOV to " << fov << std::endl;
922        viewer.getCamera()->getProjectionMatrix().makePerspective(fov, aspectRatio, zNear, zFar);
923    }
924
925    // it is done after viewer.realize() so that the windows are already initialized
926    if ( arguments.read("--debugHUD"))
927    {
928        osgViewer::Viewer::Windows windows;
929        viewer.getWindows(windows);
930
931        if (windows.empty()) return 1;
932
933        osgShadow::ShadowMap* sm = dynamic_cast<osgShadow::ShadowMap*>(shadowedScene->getShadowTechnique());
934        if( sm ) {
935            osg::ref_ptr<osg::Camera> hudCamera = sm->makeDebugHUD();
936
937            // set up cameras to rendering on the first window available.
938            hudCamera->setGraphicsContext(windows[0]);
939            hudCamera->setViewport(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height);
940
941            viewer.addSlave(hudCamera.get(), false);
942        }
943    }
944
945
946    // osgDB::writeNodeFile(*group,"test.osg");
947 
948    while (!viewer.done())
949    {
950        {
951            osgShadow::MinimalShadowMap * msm = dynamic_cast<osgShadow::MinimalShadowMap*>( shadowedScene->getShadowTechnique() );
952   
953            if( msm ) {
954
955                // If scene decorated by CoordinateSystemNode try to find localToWorld
956                // and set modellingSpaceToWorld matrix to optimize scene bounds computation
957
958                osg::NodePath np = viewer.getCoordinateSystemNodePath();
959                if( !np.empty() ) {
960                    osg::CoordinateSystemNode * csn =
961                        dynamic_cast<osg::CoordinateSystemNode *>( np.back() );
962
963                    if( csn ) {
964                        osg::Vec3d pos =
965                            viewer.getCameraManipulator()->getMatrix().getTrans();
966
967                        msm->setModellingSpaceToWorldTransform
968                            ( csn->computeLocalCoordinateFrame( pos ) );
969                    }
970                }
971            }       
972        }
973
974        if (updateLightPosition)
975        {
976            float t = viewer.getFrameStamp()->getSimulationTime();
977
978            if (lightpos.w()==1.0)
979            {
980                lightpos.set(bb.center().x()+sinf(t)*bb.radius(), bb.center().y() + cosf(t)*bb.radius(), bb.zMax() + bb.radius()*3.0f  ,1.0f);
981            }
982            else
983            {
984                lightpos.set(sinf(t),cosf(t),1.0f,0.0f);
985            }
986            ls->getLight()->setPosition(lightpos);
987
988            osg::Vec3f lightDir(-lightpos.x(),-lightpos.y(),-lightpos.z());
989            if(spotlight)
990                lightDir =  osg::Vec3(bb.center().x()+sinf(t)*bb.radius()/2.0, bb.center().y() + cosf(t)*bb.radius()/2.0, bb.center().z())
991                - osg::Vec3(lightpos.x(), lightpos.y(), lightpos.z()) ;
992            lightDir.normalize();
993            ls->getLight()->setDirection(lightDir);
994        }
995
996        if( dumpShadowVolumes->get() )
997        {
998            dumpShadowVolumes->set( false );
999
1000            static int dumpFileNo = 0;
1001            dumpFileNo ++;
1002            char filename[256];
1003            std::sprintf( filename, "shadowDump%d.osg", dumpFileNo );
1004           
1005            osgShadow::MinimalShadowMap * msm = dynamic_cast<osgShadow::MinimalShadowMap*>( shadowedScene->getShadowTechnique() );
1006
1007            if( msm ) msm->setDebugDump( filename );           
1008        }
1009
1010        viewer.frame();
1011    }
1012
1013    return 0;
1014}
Note: See TracBrowser for help on using the browser.