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

Revision 6168, 12.8 kB (checked in by robert, 7 years ago)

Reduced the RTT texture size to 256x256 to make setup quicker

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