root/OpenSceneGraph/trunk/examples/osgmultiplerendertargets/osgmultiplerendertargets.cpp @ 8084

Revision 8084, 16.9 kB (checked in by robert, 7 years ago)

Added reference to osgstereomatch example to osgmultiplerendertargets.

Added usage example use OpenSceneGraph-Data/Images examples

Line 
1/* OpenSceneGraph example, osgmultiplerendertargets.
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/GLExtensions>
20#include <osg/Node>
21#include <osg/Geometry>
22#include <osg/Notify>
23#include <osg/MatrixTransform>
24#include <osg/Texture2D>
25#include <osg/TextureRectangle>
26#include <osg/ColorMask>
27#include <osg/Material>
28
29#include <osgGA/TrackballManipulator>
30#include <osgGA/FlightManipulator>
31#include <osgGA/DriveManipulator>
32
33#include <osgViewer/Viewer>
34
35#include <iostream>
36
37//
38// Below is relatively straight forward example of use OpenGL multiple render targets extension
39// to FrameBufferObjects/GLSL shaders.
40//
41// Another, more sophisticated MRT example can be found in the osgstereomatch example.
42//
43
44
45// The callback modifies an input image.
46struct MyCameraPostDrawCallback : public osg::Camera::DrawCallback
47{
48    MyCameraPostDrawCallback(osg::Image* image):
49        _image(image)
50    {
51    }
52
53    virtual void operator () (const osg::Camera& /*camera*/) const
54    {
55        if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_UNSIGNED_BYTE)
56        {
57            // we'll pick out the center 1/2 of the whole image,
58            int column_start = _image->s()/4;
59            int column_end = 3*column_start;
60           
61            int row_start = _image->t()/4;
62            int row_end = 3*row_start;
63       
64            // and then halve their contribution
65            for(int r=row_start; r<row_end; ++r)
66            {
67                unsigned char* data = _image->data(column_start, r);
68                for(int c=column_start; c<column_end; ++c)
69                {
70                    (*data) = (*data)/2; ++data;
71                    (*data) = (*data)/2; ++data;
72                    (*data) = (*data)/2; ++data;
73                    (*data) = 255; ++data;
74                }
75            }
76
77            _image->dirty();
78        }
79        else if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_FLOAT)
80        {
81            // we'll pick out the center 1/2 of the whole image,
82            int column_start = _image->s()/4;
83            int column_end = 3*column_start;
84           
85            int row_start = _image->t()/4;
86            int row_end = 3*row_start;
87           
88            // and then halve their contribution
89            for(int r=row_start; r<row_end; ++r)
90            {
91                float* data = (float*)_image->data(column_start, r);
92                for(int c=column_start; c<column_end; ++c)
93                {
94                    (*data) = (*data)/2.0; ++data;
95                    (*data) = (*data)/2.0; ++data;
96                    (*data) = (*data)/2.0; ++data;
97                    (*data) = 1.0f; ++data;
98                }
99            }
100
101            _image->dirty();
102       
103            //print out the first three values
104            float* data = (float*)_image->data(0, 0);
105            fprintf(stderr,"Float pixel data: r %e g %e b %e\n", data[0], data[1], data[2]);
106        }
107    }
108   
109    osg::Image* _image;
110};
111
112#define NUM_TEXTURES 4
113
114// The quad geometry is used by the render to texture camera to generate multiple textures.
115osg::Group* createRTTQuad(unsigned int tex_width, unsigned int tex_height, bool useHDR)
116{
117    osg::Group *top_group = new osg::Group;
118   
119    osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
120
121    osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
122    // counter-clockwise
123    quad_coords->push_back(osg::Vec3d(0, 0, -1));
124    quad_coords->push_back(osg::Vec3d(1, 0, -1));
125    quad_coords->push_back(osg::Vec3d(1, 1, -1));
126    quad_coords->push_back(osg::Vec3d(0, 1, -1));
127
128    osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
129    quad_tcoords->push_back(osg::Vec2(0, 0));
130    quad_tcoords->push_back(osg::Vec2(tex_width, 0));
131    quad_tcoords->push_back(osg::Vec2(tex_width, tex_height));
132    quad_tcoords->push_back(osg::Vec2(0, tex_height));
133
134    osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
135    osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
136
137    osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
138    quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
139
140    quad_geom->setVertexArray(quad_coords.get());
141    quad_geom->setTexCoordArray(0, quad_tcoords.get());
142    quad_geom->addPrimitiveSet(quad_da.get());
143    quad_geom->setColorArray(quad_colors.get());
144    quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
145   
146    osg::StateSet *stateset = quad_geom->getOrCreateStateSet();
147    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
148
149    stateset->addUniform(new osg::Uniform("width", (int)tex_width));
150
151    // Attach shader, glFragData is used to create data for multiple render targets
152   
153    if (useHDR) {
154        static const char *shaderSource = {
155            "uniform int width;"
156            "void main(void)\n"
157            "{\n"
158            "    gl_FragData[0] = vec4(-1e-12,0,0,1);\n"
159            "    gl_FragData[1] = vec4(0,1e-12,0,1);\n"
160            "    gl_FragData[2] = vec4(0,0,1e-12,1);\n"
161            "    gl_FragData[3] = vec4(0,0,1e-12,1);\n"
162            "}\n"
163        };
164       
165        osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
166        osg::ref_ptr<osg::Program> program = new osg::Program;
167        program->addShader(fshader.get());
168        stateset->setAttributeAndModes(program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
169    } else {
170        static const char *shaderSource = {
171            "uniform int width;"
172            "void main(void)\n"
173            "{\n"
174            "    gl_FragData[0] = vec4(1,0,0,1);\n"
175            "    gl_FragData[1] = vec4(0,1,0,1);\n"
176            "    gl_FragData[2] = vec4(0,0,1,1);\n"
177            "    gl_FragData[3] = vec4(0,0,1,1);\n"
178            "}\n"
179        };
180   
181        osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
182        osg::ref_ptr<osg::Program> program = new osg::Program;
183        program->addShader(fshader.get());
184        stateset->setAttributeAndModes(program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
185    }
186
187    quad_geode->addDrawable(quad_geom.get());
188   
189    top_group->addChild(quad_geode.get());
190
191    return top_group;
192}
193
194// Here a scene consisting of a single quad is created. This scene is viewed by the screen camera.
195// The quad is textured using a shader and the multiple textures generated in the RTT stage.
196osg::Node* createScene(osg::Node* cam_subgraph, unsigned int tex_width, unsigned int tex_height, bool useHDR, bool useImage)
197{
198    if (!cam_subgraph) return 0;
199
200    // create a group to contain the quad and the pre render camera.
201    osg::Group* parent = new osg::Group;
202
203    // textures to render to and to use for texturing of the final quad
204    osg::TextureRectangle* textureRect[NUM_TEXTURES] = {0,0,0,0};
205   
206    for (int i=0;i<NUM_TEXTURES;i++) {
207        textureRect[i] = new osg::TextureRectangle;
208        textureRect[i]->setTextureSize(tex_width, tex_height);
209        textureRect[i]->setInternalFormat(GL_RGBA);
210        textureRect[i]->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
211        textureRect[i]->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
212
213        if (useHDR)
214        {
215            textureRect[i]->setInternalFormat(GL_FLOAT_RGBA32_NV);
216            //textureRect[i]->setInternalFormat(GL_FLOAT_RGBA16_NV);
217            textureRect[i]->setSourceFormat(GL_RGBA);
218            textureRect[i]->setSourceType(GL_FLOAT);
219        }
220    }
221
222    // first create the geometry of the quad
223    {
224        osg::Geometry* polyGeom = new osg::Geometry();
225
226        polyGeom->setSupportsDisplayList(false);
227
228        osg::Vec3Array* vertices = new osg::Vec3Array;
229        osg::Vec2Array* texcoords = new osg::Vec2Array;
230       
231        vertices->push_back(osg::Vec3d(0,0,0));
232        texcoords->push_back(osg::Vec2(0,0));
233
234        vertices->push_back(osg::Vec3d(1,0,0));
235        texcoords->push_back(osg::Vec2(tex_width,0));
236
237        vertices->push_back(osg::Vec3d(1,0,1));
238        texcoords->push_back(osg::Vec2(tex_width,tex_height));
239
240        vertices->push_back(osg::Vec3d(0,0,1));
241        texcoords->push_back(osg::Vec2(0,tex_height));
242
243        polyGeom->setVertexArray(vertices);
244        polyGeom->setTexCoordArray(0,texcoords);
245
246        osg::Vec4Array* colors = new osg::Vec4Array;
247        colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
248        polyGeom->setColorArray(colors);
249        polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
250
251        polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,vertices->size()));
252
253        // now we need to add the textures (generated by RTT) to the Drawable.
254        osg::StateSet* stateset = new osg::StateSet;
255        for (int i=0;i<NUM_TEXTURES;i++){
256            stateset->setTextureAttributeAndModes(i, textureRect[i], osg::StateAttribute::ON);
257        }
258       
259        polyGeom->setStateSet(stateset);
260
261        // Attach a shader to the final quad to combine the input textures.
262        if (useHDR) {
263            static const char *shaderSource = {
264                "uniform sampler2DRect textureID0;\n"
265                "uniform sampler2DRect textureID1;\n"
266                "uniform sampler2DRect textureID2;\n"
267                "uniform sampler2DRect textureID3;\n"
268                "uniform float width;\n"
269                "uniform float height; \n"
270                "void main(void)\n"
271                "{\n"
272                "    gl_FragData[0] = \n"
273                "     vec4(  -1e12 * texture2DRect( textureID0, gl_TexCoord[0].st ).rgb, 1) + \n"
274                "     vec4(   1e12 * texture2DRect( textureID1, gl_TexCoord[0].st ).rgb, 1) + \n"
275                "     vec4(   1e12 * texture2DRect( textureID2, gl_TexCoord[0].st ).rgb, 1) + \n"
276                "     vec4(-0.5e12 * texture2DRect( textureID3, gl_TexCoord[0].st ).rgb, 1);  \n"
277                "}\n"
278            };
279            osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
280            osg::ref_ptr<osg::Program> program = new osg::Program;
281            program->addShader( fshader.get());
282            stateset->setAttributeAndModes( program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
283        } else {
284            static const char *shaderSource = {
285                "uniform sampler2DRect textureID0;\n"
286                "uniform sampler2DRect textureID1;\n"
287                "uniform sampler2DRect textureID2;\n"
288                "uniform sampler2DRect textureID3;\n"
289                "void main(void)\n"
290                "{\n"
291                "    gl_FragData[0] = \n"
292                "          vec4(texture2DRect( textureID0, gl_TexCoord[0].st ).rgb, 1) + \n"
293                "          vec4(texture2DRect( textureID1, gl_TexCoord[0].st ).rgb, 1) + \n"
294                "          vec4(texture2DRect( textureID2, gl_TexCoord[0].st ).rgb, 1) + \n"
295                "     -0.5*vec4(texture2DRect( textureID3, gl_TexCoord[0].st ).rgb, 1);  \n"
296                "}\n"
297            };
298            osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT , shaderSource);
299            osg::ref_ptr<osg::Program> program = new osg::Program;
300            program->addShader( fshader.get());
301            stateset->setAttributeAndModes( program.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
302           
303        }
304
305        stateset->addUniform(new osg::Uniform("textureID0", 0));
306        stateset->addUniform(new osg::Uniform("textureID1", 1));
307        stateset->addUniform(new osg::Uniform("textureID2", 2));
308        stateset->addUniform(new osg::Uniform("textureID3", 3));
309       
310        //stateset->setDataVariance(osg::Object::DYNAMIC);
311       
312        osg::Geode* geode = new osg::Geode();
313        geode->addDrawable(polyGeom);
314       
315        parent->addChild(geode);
316    }
317
318    // now create the camera to do the multiple render to texture
319    {   
320        osg::Camera* camera = new osg::Camera;
321
322        // set up the background color and clear mask.
323        camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
324        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
325
326        // the camera is going to look at our input quad
327        camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
328        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
329        camera->setViewMatrix(osg::Matrix::identity());
330
331        // set viewport
332        camera->setViewport(0, 0, tex_width, tex_height);
333
334        // set the camera to render before the main camera.
335        camera->setRenderOrder(osg::Camera::PRE_RENDER);
336
337        // tell the camera to use OpenGL frame buffer objects
338        camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
339
340        // attach the textures to use
341        for (int i=0; i<NUM_TEXTURES; i++) {
342            camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+i), textureRect[i]);
343        }
344     
345        // we can also read back any of the targets as an image, modify this image and push it back
346        if (useImage) {
347            // which texture to get the image from
348            const int tex_to_get = 0;
349           
350            osg::Image* image = new osg::Image;
351            if (useHDR) {
352                image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_FLOAT);
353            } else {
354                image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
355            }
356
357            // attach the image so its copied on each frame.
358            camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0 + tex_to_get), image);
359
360            camera->setPostDrawCallback(new MyCameraPostDrawCallback(image));
361           
362            // push back the image to the texture
363            textureRect[tex_to_get]->setImage(0, image);
364        }
365
366        // add the subgraph to render
367        camera->addChild(cam_subgraph);
368
369        parent->addChild(camera);
370    }   
371
372    return parent;
373}
374
375int main( int argc, char **argv )
376{
377    // use an ArgumentParser object to manage the program arguments.
378    osg::ArgumentParser arguments(&argc,argv);
379
380    // set up the usage document, in case we need to print out how to use this program.
381    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " demonstrates the use of multiple render targets (MRT) using frame buffer objects. A render to texture camera is used to render to four textures using a single shader. The four textures are then combined to texture the viewed geometry.");
382    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ...");
383    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information.");
384    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");
385    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");
386    arguments.getApplicationUsage()->addCommandLineOption("--image","Render one of the targets to an image, then apply a post draw callback to modify it, and use this image to update a texture.");
387    arguments.getApplicationUsage()->addCommandLineOption("--hdr","Use high dynamic range. Create floating point textures to render to.");
388
389    // construct the viewer.
390    osgViewer::Viewer viewer(arguments);
391
392    // if user request help write it out to cout.
393    if (arguments.read("-h") || arguments.read("--help"))
394    {
395        arguments.getApplicationUsage()->write(std::cout);
396        return 1;
397    }
398
399    unsigned tex_width = 512;
400    unsigned tex_height = 512;
401    while (arguments.read("--width", tex_width)) {}
402    while (arguments.read("--height", tex_height)) {}
403
404    bool useHDR = false;
405    while (arguments.read("--hdr")) { useHDR = true; }
406
407    bool useImage = false;
408    while (arguments.read("--image")) { useImage = true; }
409
410    osg::Group* subGraph = createRTTQuad(tex_width, tex_height, useHDR);
411
412    osg::Group* rootNode = new osg::Group();
413    rootNode->addChild(createScene(subGraph, tex_width, tex_height, useHDR, useImage));
414
415    // add model to the viewer.
416    viewer.setSceneData( rootNode );
417
418    return viewer.run();
419}
Note: See TracBrowser for help on using the browser.