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

Revision 4553, 13.2 kB (checked in by robert, 9 years ago)

Fixed typo of CameraNode::setRenderTargetImplementation(..)

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