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

Revision 9405, 33.6 kB (checked in by robert, 6 years ago)

Added StandardShadowMap? to list to test cases

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