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

Revision 12174, 35.9 kB (checked in by robert, 4 years ago)

Added --fov and --light-pos and --light-dir command line parameters

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