root/OpenSceneGraph/trunk/examples/osgprerendercubemap/osgprerendercubemap.cpp @ 5381

Revision 5381, 13.8 kB (checked in by robert, 8 years ago)

Added viewer.cleanup_frame() to all examples.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgProducer/Viewer>
2
3#include <osg/Projection>
4#include <osg/Geometry>
5#include <osg/Texture>
6#include <osg/TexGen>
7#include <osg/Geode>
8#include <osg/ShapeDrawable>
9#include <osg/PolygonOffset>
10#include <osg/CullFace>
11#include <osg/TextureCubeMap>
12#include <osg/TexMat>
13#include <osg/MatrixTransform>
14#include <osg/Light>
15#include <osg/LightSource>
16#include <osg/PolygonOffset>
17#include <osg/CullFace>
18#include <osg/Material>
19#include <osg/PositionAttitudeTransform>
20
21#include <osg/CameraNode>
22#include <osg/TexGenNode>
23
24using namespace osg;
25
26
27ref_ptr<Group> _create_scene()
28{
29  ref_ptr<Group> scene = new Group;
30  ref_ptr<Geode> geode_1 = new Geode;
31  scene->addChild(geode_1.get());
32
33  ref_ptr<Geode> geode_2 = new Geode;
34  ref_ptr<MatrixTransform> transform_2 = new MatrixTransform;
35  transform_2->addChild(geode_2.get());
36  transform_2->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(45.0f)));
37  scene->addChild(transform_2.get());
38
39  ref_ptr<Geode> geode_3 = new Geode;
40  ref_ptr<MatrixTransform> transform_3 = new MatrixTransform;
41  transform_3->addChild(geode_3.get());
42  transform_3->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(-22.5f)));
43  scene->addChild(transform_3.get());
44
45  const float radius = 0.8f;
46  const float height = 1.0f;
47  ref_ptr<TessellationHints> hints = new TessellationHints;
48  hints->setDetailRatio(2.0f);
49  ref_ptr<ShapeDrawable> shape;
50
51  shape = new ShapeDrawable(new Box(Vec3(0.0f, -2.0f, 0.0f), 10, 0.1f, 10), hints.get());
52  shape->setColor(Vec4(0.5f, 0.5f, 0.7f, 1.0f));
53  geode_1->addDrawable(shape.get());
54
55
56  shape = new ShapeDrawable(new Sphere(Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
57  shape->setColor(Vec4(0.6f, 0.8f, 0.8f, 1.0f));
58  geode_2->addDrawable(shape.get());
59
60  shape = new ShapeDrawable(new Box(Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
61  shape->setColor(Vec4(0.4f, 0.9f, 0.3f, 1.0f));
62  geode_2->addDrawable(shape.get());
63
64  shape = new ShapeDrawable(new Cone(Vec3(0.0f, 0.0f, -3.0f), radius, height), hints.get());
65  shape->setColor(Vec4(0.2f, 0.5f, 0.7f, 1.0f));
66  geode_2->addDrawable(shape.get());
67
68  shape = new ShapeDrawable(new Cylinder(Vec3(0.0f, 0.0f, 3.0f), radius, height), hints.get());
69  shape->setColor(Vec4(1.0f, 0.3f, 0.3f, 1.0f));
70  geode_2->addDrawable(shape.get());
71
72  shape = new ShapeDrawable(new Box(Vec3(0.0f, 3.0f, 0.0f), 2, 0.1f, 2), hints.get());
73  shape->setColor(Vec4(0.8f, 0.8f, 0.4f, 1.0f));
74  geode_3->addDrawable(shape.get());
75
76  // material
77  ref_ptr<Material> matirial = new Material;
78  matirial->setColorMode(Material::DIFFUSE);
79  matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1));
80  matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1));
81  matirial->setShininess(Material::FRONT_AND_BACK, 64.0f);
82  scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON);
83
84  return scene;
85}
86
87osg::NodePath createReflector()
88{
89  osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform;
90  pat->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
91  pat->setAttitude(osg::Quat(osg::inDegrees(0.0f),osg::Vec3(0.0f,0.0f,1.0f)));
92 
93  Geode* geode_1 = new Geode;
94  pat->addChild(geode_1);
95
96  const float radius = 0.8f;
97  ref_ptr<TessellationHints> hints = new TessellationHints;
98  hints->setDetailRatio(2.0f);
99  ShapeDrawable* shape = new ShapeDrawable(new Sphere(Vec3(0.0f, 0.0f, 0.0f), radius * 1.5f), hints.get());
100  shape->setColor(Vec4(0.8f, 0.8f, 0.8f, 1.0f));
101  geode_1->addDrawable(shape);
102 
103  osg::NodePath nodeList;
104  nodeList.push_back(pat);
105  nodeList.push_back(geode_1);
106 
107  return nodeList;
108}
109
110class UpdateCameraAndTexGenCallback : public osg::NodeCallback
111{
112    public:
113   
114        typedef std::vector< osg::ref_ptr<osg::CameraNode> >  CameraList;
115
116        UpdateCameraAndTexGenCallback(osg::NodePath& reflectorNodePath, CameraList& cameraNodes):
117            _reflectorNodePath(reflectorNodePath),
118            _cameraNodes(cameraNodes)
119        {
120        }
121       
122        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
123        {
124            // first update subgraph to make sure objects are all moved into postion
125            traverse(node,nv);
126
127            // compute the position of the center of the reflector subgraph
128            osg::Matrixd worldToLocal = osg::computeWorldToLocal(_reflectorNodePath);
129            osg::BoundingSphere bs = _reflectorNodePath.back()->getBound();
130            osg::Vec3 position = bs.center();
131
132            typedef std::pair<osg::Vec3, osg::Vec3> ImageData;
133            const ImageData id[] =
134            {
135                ImageData( osg::Vec3( 1,  0,  0), osg::Vec3( 0, -1,  0) ), // +X
136                ImageData( osg::Vec3(-1,  0,  0), osg::Vec3( 0, -1,  0) ), // -X
137                ImageData( osg::Vec3( 0,  1,  0), osg::Vec3( 0,  0,  1) ), // +Y
138                ImageData( osg::Vec3( 0, -1,  0), osg::Vec3( 0,  0, -1) ), // -Y
139                ImageData( osg::Vec3( 0,  0,  1), osg::Vec3( 0, -1,  0) ), // +Z
140                ImageData( osg::Vec3( 0,  0, -1), osg::Vec3( 0, -1,  0) )  // -Z
141            };
142
143            for(unsigned int i=0;
144                i<6 && i<_cameraNodes.size();
145                ++i)
146            {
147                osg::Matrix localOffset;
148                localOffset.makeLookAt(position,position+id[i].first,id[i].second);
149               
150                osg::Matrix viewMatrix = worldToLocal*localOffset;
151           
152                _cameraNodes[i]->setReferenceFrame(osg::CameraNode::ABSOLUTE_RF);
153                _cameraNodes[i]->setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0);
154                _cameraNodes[i]->setViewMatrix(viewMatrix);
155            }
156        }
157       
158    protected:
159   
160        virtual ~UpdateCameraAndTexGenCallback() {}
161       
162        osg::NodePath               _reflectorNodePath;       
163        CameraList                  _cameraNodes;
164};
165
166class TexMatCullCallback : public osg::NodeCallback
167{
168    public:
169   
170        TexMatCullCallback(osg::TexMat* texmat):
171            _texmat(texmat)
172        {
173        }
174       
175        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
176        {
177            // first update subgraph to make sure objects are all moved into postion
178            traverse(node,nv);
179           
180            osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv);
181            if (cv)
182            {
183                osg::Quat quat = cv->getModelViewMatrix().getRotate();
184                _texmat->setMatrix(osg::Matrix::rotate(quat.inverse()));
185            }
186        }
187       
188    protected:
189   
190        osg::ref_ptr<TexMat>    _texmat;
191};
192
193
194osg::Group* createShadowedScene(osg::Node* reflectedSubgraph, osg::NodePath reflectorNodePath, unsigned int unit, const osg::Vec4& clearColor, unsigned tex_width, unsigned tex_height, osg::CameraNode::RenderTargetImplementation renderImplementation)
195{
196
197    osg::Group* group = new osg::Group;
198   
199    osg::TextureCubeMap* texture = new osg::TextureCubeMap;
200    texture->setTextureSize(tex_width, tex_height);
201
202    texture->setInternalFormat(GL_RGB);
203    texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
204    texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
205    texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
206    texture->setFilter(osg::TextureCubeMap::MIN_FILTER,osg::TextureCubeMap::LINEAR);
207    texture->setFilter(osg::TextureCubeMap::MAG_FILTER,osg::TextureCubeMap::LINEAR);
208   
209    // set up the render to texture cameras.
210    UpdateCameraAndTexGenCallback::CameraList cameraNodes;
211    for(unsigned int i=0; i<6; ++i)
212    {
213        // create the camera
214        osg::CameraNode* camera = new osg::CameraNode;
215
216        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
217        camera->setClearColor(clearColor);
218
219        // set viewport
220        camera->setViewport(0,0,tex_width,tex_height);
221
222        // set the camera to render before the main camera.
223        camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
224
225        // tell the camera to use OpenGL frame buffer object where supported.
226        camera->setRenderTargetImplementation(renderImplementation);
227
228        // attach the texture and use it as the color buffer.
229        camera->attach(osg::CameraNode::COLOR_BUFFER, texture, 0, i);
230
231        // add subgraph to render
232        camera->addChild(reflectedSubgraph);
233       
234        group->addChild(camera);
235       
236        cameraNodes.push_back(camera);
237    }
238   
239    // create the texgen node to project the tex coords onto the subgraph
240    osg::TexGenNode* texgenNode = new osg::TexGenNode;
241    texgenNode->getTexGen()->setMode(osg::TexGen::REFLECTION_MAP);
242    texgenNode->setTextureUnit(unit);
243    group->addChild(texgenNode);
244
245    // set the reflected subgraph so that it uses the texture and tex gen settings.   
246    {
247        osg::Node* reflectorNode = reflectorNodePath.front();
248        group->addChild(reflectorNode);
249               
250        osg::StateSet* stateset = reflectorNode->getOrCreateStateSet();
251        stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON);
252        stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
253        stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
254        stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
255        stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
256
257        osg::TexMat* texmat = new osg::TexMat;
258        stateset->setTextureAttributeAndModes(unit,texmat,osg::StateAttribute::ON);
259       
260        reflectorNode->setCullCallback(new TexMatCullCallback(texmat));
261    }
262   
263    // add the reflector scene to draw just as normal
264    group->addChild(reflectedSubgraph);
265   
266    // set an update callback to keep moving the camera and tex gen in the right direction.
267    group->setUpdateCallback(new UpdateCameraAndTexGenCallback(reflectorNodePath, cameraNodes));
268
269    return group;
270}
271
272
273int main(int argc, char** argv)
274{
275    // use an ArgumentParser object to manage the program arguments.
276    ArgumentParser arguments(&argc, argv);
277
278    // set up the usage document, in case we need to print out how to use this program.
279    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class");
280    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
281    arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
282    arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
283    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
284    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
285    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
286    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture");
287    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture");
288
289    // construct the viewer.
290    osgProducer::Viewer viewer(arguments);
291
292    // set up the value with sensible default event handlers.
293    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
294
295    // get details on keyboard and mouse bindings used by the viewer.
296    viewer.getUsage(*arguments. getApplicationUsage());
297
298    // if user request help write it out to cout.
299    if (arguments.read("-h") || arguments.read("--help"))
300    {
301        arguments.getApplicationUsage()->write(std::cout);
302        return 1;
303    }
304   
305    unsigned tex_width = 512;
306    unsigned tex_height = 512;
307    while (arguments.read("--width", tex_width)) {}
308    while (arguments.read("--height", tex_height)) {}
309
310    osg::CameraNode::RenderTargetImplementation renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT;
311   
312    while (arguments.read("--fbo")) { renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; }
313    while (arguments.read("--pbuffer")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER; }
314    while (arguments.read("--fb")) { renderImplementation = osg::CameraNode::FRAME_BUFFER; }
315    while (arguments.read("--window")) { renderImplementation = osg::CameraNode::SEPERATE_WINDOW; }
316   
317
318    // any option left unread are converted into errors to write out later.
319    arguments.reportRemainingOptionsAsUnrecognized();
320
321    // report any errors if they have occured when parsing the program aguments.
322    if (arguments.errors())
323    {
324      arguments.writeErrorMessages(std::cout);
325      return 1;
326    }
327
328    ref_ptr<MatrixTransform> scene = new MatrixTransform;
329    scene->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(125.0),1.0,0.0,0.0));
330
331    ref_ptr<Group> reflectedSubgraph = _create_scene();   
332    if (!reflectedSubgraph.valid()) return 1;
333
334    ref_ptr<Group> reflectedScene = createShadowedScene(reflectedSubgraph.get(), createReflector(), 0, viewer.getClearColor(),
335                                                        tex_width, tex_height, renderImplementation);
336
337    scene->addChild(reflectedScene.get());
338
339    viewer.setSceneData(scene.get());
340
341    // create the windows and run the threads.
342    viewer.realize();
343
344    while (!viewer.done())
345    {
346      // wait for all cull and draw threads to complete.
347      viewer.sync();
348
349      // update the scene by traversing it with the the update visitor which will
350      // call all node update callbacks and animations.
351      viewer.update();
352         
353      // fire off the cull and draw traversals of the scene.
354      viewer.frame();
355    }
356   
357    // wait for all cull and draw threads to complete.
358    viewer.sync();
359
360    // run a clean up frame to delete all OpenGL objects.
361    viewer.cleanup_frame();
362
363    // wait for all the clean up frame to complete.
364    viewer.sync();
365
366    return 0;
367}
Note: See TracBrowser for help on using the browser.