source: osgVisual/src/distortion/visual_distortion.cpp @ 41

Last change on this file since 41 was 31, checked in by Torben Dannhauer, 15 years ago

Adding first version of osgVisual!!

File size: 19.1 KB
Line 
1/* -*-c++-*- osgVisual - Copyright (C) 2009-2010 Torben Dannhauer
2 *
3 * This library is based on OpenSceneGraph, open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * osgVisual requires for some proprietary modules a license from the correspondig manufacturer.
9 * You have to aquire licenses for all used proprietary modules.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * OpenSceneGraph Public License for more details.
15*/
16
17#include <visual_distortion.h>
18
19using namespace osgVisual;
20
21visual_distortion::visual_distortion(osgViewer::Viewer* viewer_, osg::ArgumentParser& arguments_) : viewer(viewer_), arguments(arguments_)
22{
23        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion instantiated." << std::endl;
24
25        initialized = false;
26        distortionEnabled = false;
27        parser = new CameraConfigParser();
28
29        distortedGraph = NULL;
30        cleanGraph = NULL;
31
32        distortMapTexture = NULL;
33        blendMapTexture = NULL;
34}
35
36visual_distortion::~visual_distortion(void)
37{
38        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion destroyed." << std::endl;
39}
40
41bool visual_distortion::processCommandlineparameters()
42{
43        arguments.getApplicationUsage()->addCommandLineOption("-C <channelname>","Setup the channel name, this is the preset for blendmap, distortionmap and camera configuration file.");
44        arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
45    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
46    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
47    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
48    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");
49    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");
50    arguments.getApplicationUsage()->addCommandLineOption("--texture-rectangle","Use osg::TextureRectangle for doing the render to texure to.");
51    arguments.getApplicationUsage()->addCommandLineOption("--distortionmap","Set a distortion map file name.");
52    arguments.getApplicationUsage()->addCommandLineOption("--blendmap","Set a blend map file name.");
53    arguments.getApplicationUsage()->addCommandLineOption("--shaderDistortion","Use OpenGL shader for distortion and blending.");
54        arguments.getApplicationUsage()->addKeyboardMouseBinding("d", "Toggle Distortion.");
55
56        // Read out Distortion CMDLine arguments
57        tex_width = 2048;
58    tex_height = 2048;
59    while (arguments.read("--width", tex_width)) {}
60    while (arguments.read("--height", tex_height)) {}
61
62        renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
63
64    while (arguments.read("--fbo")) { renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT; }
65    while (arguments.read("--pbuffer")) { renderImplementation = osg::Camera::PIXEL_BUFFER; }
66    while (arguments.read("--pbuffer-rtt")) { renderImplementation = osg::Camera::PIXEL_BUFFER_RTT; }
67    while (arguments.read("--fb")) { renderImplementation = osg::Camera::FRAME_BUFFER; }
68    while (arguments.read("--window")) { renderImplementation = osg::Camera::SEPERATE_WINDOW; }
69
70    useTextureRectangle = false;
71    while (arguments.read("--texture-rectangle")) { useTextureRectangle = true; }
72        useShaderDistortion = false;
73    while (arguments.read("--shaderDistortion")) { useShaderDistortion = true; }
74    useHDR = false; 
75    while (arguments.read("--hdr")) { useHDR = true; }
76
77        distortMapFileName = "..\\resources\\distortion\\distort_distDisabled.bmp";
78    while (arguments.read("--distortionmap", distortMapFileName)) { }
79        blendMapFileName = "..\\resources\\distortion\\blend_distDisabled.bmp";
80    while (arguments.read("--blendmap", blendMapFileName)) { }
81
82        std::string pre_cfg("..\\resources\\distortion\\view_");
83        std::string pre_distortion("..\\resources\\distortion\\distort_");
84        std::string pre_blend("..\\resources\\distortion\\blend_");
85        std::string post_cfg(".cfg");
86        std::string post_distortion(".bmp");
87        std::string post_blend(".bmp");
88        std::string channelname;
89        while (arguments.read("-C",channelname))
90        {
91                OSG_NOTIFY(osg::INFO) << "channelname:" << channelname << std::endl;
92                // load channel config
93                parser->parseConfigFile((pre_cfg+channelname+post_cfg).data());
94                // load channel blendmap
95                blendMapFileName = (pre_blend+channelname+post_blend).data();
96                // load channel distortionmap
97                distortMapFileName = (pre_distortion+channelname+post_distortion).data(); 
98                // set channel frustum
99                if( parser->isConfigParsed())
100                        viewer->getCamera()->setProjectionMatrixAsFrustum((parser->getFrustumDataset())[0], (parser->getFrustumDataset())[1], (parser->getFrustumDataset())[2], (parser->getFrustumDataset())[3], (parser->getFrustumDataset())[4], (parser->getFrustumDataset())[5]);
101                else
102                        OSG_NOTIFY(osg::WARN) << "WARNING: Unable to parse Frustum values from '" << pre_cfg<<channelname<<post_cfg << "' -- continue without valid frustum values." << std::endl;
103        }
104
105         // report any errors if they have occurred when parsing the program arguments.
106    if (arguments.errors())
107    {
108        arguments.writeErrorMessages(std::cout);
109                exit(1);
110    }
111        return true;
112}
113
114osg::Group* visual_distortion::initialize(osg::Group* subgraph, const osg::Vec4& clearColor )
115{
116        OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion initialize..." << std::endl;
117
118        // Process Commandline arguments:
119        processCommandlineparameters();
120
121        // Add this node to the scenegraph to get updated during update traversal.
122        subgraph->addChild( this );
123
124        // add the keyboard handler for toggle distortion
125        kBEventHandler = new ToggleDistortionKBEventHandler( this );
126        viewer->addEventHandler( kBEventHandler );
127
128        cleanGraph = subgraph;
129        distortedGraph = createPreRenderSubGraph( subgraph, clearColor );
130
131        // Create and install updateCallback (to get called for copying the main cameras view matrixes to the PRE_RENDER camera)
132        // -- must be called _AFTER_ createPreRenderSubGraph() (necessary because sceneCamera is set by createPreRenderSubGraph())
133        updateCallback = new distortionUpdateCallback( viewer, sceneCamera );
134        this->setUpdateCallback( updateCallback );
135
136        // Note down state flags..
137        initialized = true;
138        distortionEnabled = true;
139
140        distortionEnabled = true;
141        viewer->setSceneData( distortedGraph );
142       
143        return distortedGraph;
144}
145
146void visual_distortion::shutdown()
147{
148        if(initialized)
149        {
150                // Remove this Node from scenegraph
151                cleanGraph->removeChild( this );
152
153                // Remove update callback
154                this->removeUpdateCallback( updateCallback );
155                updateCallback = NULL;
156
157                OSG_NOTIFY (osg::ALWAYS ) << "visual_distortion shutdown complete." << std::endl;
158        }
159}
160
161void visual_distortion::distortionUpdateCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
162{
163        // Copy Main Camera's matrixes to the PRE_RENDER Camera.
164        sceneCamera->setViewMatrix( viewer->getCamera()->getViewMatrix() );
165        sceneCamera->setProjectionMatrix( viewer->getCamera()->getProjectionMatrix() );
166}
167
168void visual_distortion::toggleDistortion()
169{
170        // Toggle
171        //// If not Distorted: enabled distortion
172        if( !distortionEnabled )
173        {
174                distortionEnabled = true;
175                viewer->setSceneData( distortedGraph );
176        }
177        else    // .. otherwise disable distortion
178        {
179                distortionEnabled = false;
180                viewer->setSceneData( cleanGraph );
181        }
182}
183
184
185osg::Group* visual_distortion::createPreRenderSubGraph(osg::Group* subgraph, const osg::Vec4& clearColor )
186{
187    if (!subgraph) return 0;
188
189    // create a group to contain the flag and the pre rendering camera.
190    osg::Group* parent = new osg::Group;
191
192    // texture to render to and to use for rendering of flag.
193    osg::Texture* texture = 0;
194    if (useTextureRectangle)
195    {
196        osg::TextureRectangle* textureRect = new osg::TextureRectangle;
197        textureRect->setTextureSize(tex_width, tex_height);
198        textureRect->setInternalFormat(GL_RGBA);
199        textureRect->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
200        textureRect->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
201       
202        texture = textureRect;
203    }
204    else
205    {
206        osg::Texture2D* texture2D = new osg::Texture2D;
207        texture2D->setTextureSize(tex_width, tex_height);
208        texture2D->setInternalFormat(GL_RGBA);
209        texture2D->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
210        texture2D->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
211       
212        texture = texture2D;
213    } 
214
215    if (useHDR)
216    {
217        texture->setInternalFormat(GL_RGBA16F_ARB);
218        texture->setSourceFormat(GL_RGBA);
219        texture->setSourceType(GL_FLOAT);
220    }
221
222    // load a distortion map texture file
223        if ( osgDB::fileExists( distortMapFileName ) )
224                distortMapTexture = loadTexture(distortMapFileName);
225        else
226        {
227                OSG_NOTIFY(osg::FATAL) << "ERROR: Distortionmap file'" << distortMapFileName << "' not found! Please change the channelname, filename or copy the desired file to the applications root folder!" << std::endl;
228                exit(-1);
229        }
230
231    // load a blend map texture file
232        if ( osgDB::fileExists( blendMapFileName ) )
233                blendMapTexture = loadTexture(blendMapFileName);
234        else
235        {
236                OSG_NOTIFY(osg::FATAL) << "ERROR: Blendmap file'" << blendMapFileName << "' not found! Please change the channelname, filename or copy the desired file to the applications root folder!" << std::endl;
237                exit(-1);
238        }
239
240    // set up the plane to render the rendered view.
241    {
242        // create the quad to visualize.
243        osg::Geometry* polyGeom = new osg::Geometry();
244
245        polyGeom->setSupportsDisplayList(false);
246
247        osg::Vec3 origin(0.0f,0.0f,0.0f);
248        osg::Vec3 xAxis(1.0f,0.0f,0.0f);
249        osg::Vec3 yAxis(0.0f,1.0f,0.0f);
250        osg::Vec3 zAxis(0.0f,0.0f,1.0f);
251        float height = 1024.0f;
252        float width = 1280.0f;
253        int noSteps = 128;
254        if (useShaderDistortion)
255            noSteps = 2;
256
257        osg::Vec3Array* vertices = new osg::Vec3Array;
258        osg::Vec2Array* texcoords = new osg::Vec2Array;
259        osg::Vec2Array* texcoords2 = useShaderDistortion?NULL:(new osg::Vec2Array);
260        osg::Vec4Array* colors = new osg::Vec4Array;
261
262        osg::Vec3 bottom = origin;
263        osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
264        osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
265
266        osg::Vec2 bottom_texcoord(0.0f,0.0f);
267        osg::Vec2 dx_texcoord(1.0f/(float)(noSteps-1),0.0f);
268        osg::Vec2 dy_texcoord(0.0f,1.0f/(float)(noSteps-1));
269
270        osg::Vec3 cursor = bottom;
271        osg::Vec2 texcoord = bottom_texcoord;
272        int i,j;
273        for(i=0;i<noSteps;++i)
274        {
275            osg::Vec3 cursor = bottom+dy*(float)i;
276            osg::Vec2 texcoord = bottom_texcoord+dy_texcoord*(float)i;
277            for(j=0;j<noSteps;++j)
278            {
279                vertices->push_back(cursor);
280                if (distortMapTexture && !useShaderDistortion)
281                {
282                    osg::Vec2 imgcoord = osg::Vec2((distortMapTexture->getImage(0)->s()-1) * texcoord.x(),
283                                                   (distortMapTexture->getImage(0)->t()-1) * texcoord.y());
284                    unsigned char* pPixel = &distortMapTexture->getImage(0)->data()[(int)imgcoord.y()*distortMapTexture->getImage(0)->getRowSizeInBytes()+
285                                                                                    (int)imgcoord.x()*distortMapTexture->getImage(0)->getPixelSizeInBits()/8];
286                    texcoords->push_back(osg::Vec2(((float)pPixel[2] / 255.0f + (pPixel[0] % 16)) / 16.0f,
287                                                   1.0f - ((float)pPixel[1] / 255.0f + (pPixel[0] / 16)) / 16.0f));
288                    texcoords2->push_back(osg::Vec2(texcoord.x(), texcoord.y()));
289                }
290                else
291                    texcoords->push_back(osg::Vec2(texcoord.x(), texcoord.y()));
292                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
293
294                cursor += dx;
295                texcoord += dx_texcoord;
296            }
297        }
298
299        // pass the created vertex array to the points geometry object.
300        polyGeom->setVertexArray(vertices);
301
302        polyGeom->setColorArray(colors);
303        polyGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
304        polyGeom->setTexCoordArray(0,texcoords);
305        if (!useShaderDistortion)
306            polyGeom->setTexCoordArray(2,texcoords2);
307
308        for(i=0;i<noSteps-1;++i)
309        {
310            osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
311            for(j=0;j<noSteps;++j)
312            {
313                elements->push_back(j+(i+1)*noSteps);
314                elements->push_back(j+(i)*noSteps);
315            }
316            polyGeom->addPrimitiveSet(elements);
317        }
318
319        // new we need to add the texture to the Drawable, we do so by creating a
320        // StateSet to contain the Texture StateAttribute.
321        osg::StateSet* stateset = polyGeom->getOrCreateStateSet();
322        stateset->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
323        stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
324        stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
325
326        osg::Geode* geode = new osg::Geode();
327        geode->addDrawable(polyGeom);
328
329        if (useShaderDistortion)
330        {
331            // apply the distortion map texture
332            if (distortMapTexture)
333                geode->getOrCreateStateSet()->setTextureAttributeAndModes(1, distortMapTexture, osg::StateAttribute::ON);
334        }
335
336        // apply the blend map texture
337        if (blendMapTexture)
338            geode->getOrCreateStateSet()->setTextureAttributeAndModes(2, blendMapTexture, osg::StateAttribute::ON);
339
340        // set up the camera to render the textured quad
341        osg::Camera* camera = new osg::Camera;
342
343        // just inherit the main cameras view
344        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
345        camera->setViewMatrix(osg::Matrix::identity());
346        //camera->setProjectionMatrixAsOrtho2D(0,viewer->getCamera()->getViewport()->width(),0,viewer->getCamera()->getViewport()->height());
347                camera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
348
349        // set the camera to render before the main camera.
350        camera->setRenderOrder(osg::Camera::POST_RENDER, 200);
351
352        // only clear the depth buffer
353        camera->setClearMask(0);
354
355        // add subgraph to render
356        camera->addChild(geode);
357
358        if (useShaderDistortion)
359        {
360            // create shaders for distortion
361            osg::StateSet* ss = geode->getOrCreateStateSet();
362
363            osg::Program* distortProgram = new osg::Program;
364            distortProgram->setName( "distortion" );
365            osg::Shader* distortVertObj = new osg::Shader( osg::Shader::VERTEX );
366            osg::Shader* distortFragObj = new osg::Shader( osg::Shader::FRAGMENT );
367
368            if (loadShaderSource( distortVertObj, "shader.vert" ) &&
369                loadShaderSource( distortFragObj, "shader.frag" ) &&
370                distortMapTexture)
371            {
372                distortProgram->addShader( distortFragObj );
373                distortProgram->addShader( distortVertObj );
374                ss->addUniform( new osg::Uniform("textureImage", 0) );
375                ss->addUniform( new osg::Uniform("textureDistort", 1) );
376                ss->addUniform( new osg::Uniform("textureBlend", 2) );
377                ss->setAttributeAndModes(distortProgram, osg::StateAttribute::ON);
378            }
379                        else
380                        {
381                                OSG_NOTIFY(osg::FATAL) << "##################################" << std::endl << "## Unable to activate ShaderDistortion!" << std::endl << "## ABORT" << std::endl << "##################################" << std::endl;
382                                exit(0);
383                        }
384        }
385
386        parent->addChild(camera);
387    }
388
389    // then create the camera node to do the render to texture
390    {   
391        osg::Camera* camera = new osg::Camera;
392
393        // set up the background color and clear mask.
394        camera->setClearColor(clearColor);
395        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
396
397
398        // just inherit the main cameras view
399                /* ABSOLUTE_RF required to make intersections possible.
400                Disadvantage of ABOLUTE_RF : the maincameras view matrix and projection
401                matrix has to copied to the PRE_RENDER camera by our self.
402                Therefore an update callback is installed.
403                */
404                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); 
405        camera->setProjectionMatrix(osg::Matrixd::identity());
406        camera->setViewMatrix(osg::Matrixd::identity());
407
408        // set viewport
409        camera->setViewport(0,0,tex_width,tex_height);
410
411        // set the camera to render before the main camera.
412        camera->setRenderOrder(osg::Camera::PRE_RENDER, 0);
413
414                sceneCamera = camera;
415
416        // tell the camera to use OpenGL frame buffer object where supported.
417        camera->setRenderTargetImplementation(renderImplementation);
418
419        // attach the texture and use it as the color buffer.
420        camera->attach(osg::Camera::COLOR_BUFFER, texture);     // No Multisampling/Antialiasing
421                //camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, 0, false, 4, 4); // 4x Multisampling/Antialiasing
422
423        // add subgraph to render
424        camera->addChild(subgraph);
425
426        parent->addChild(camera);
427    }   
428    return parent;
429}
430
431
432bool visual_distortion::loadShaderSource( osg::Shader* shader, const std::string& fileName )
433{
434    std::string foundFileName = osgDB::findDataFile(fileName);
435    if (foundFileName.length() != 0 )
436    {
437        return shader->loadShaderSourceFromFile( foundFileName.c_str() );
438    }
439
440    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
441
442    return false;
443}
444
445osg::Texture* visual_distortion::loadTexture( const std::string& fileName )
446{
447    std::string foundFileName = osgDB::findDataFile(fileName);
448    if (foundFileName.length() != 0 )
449    {
450        // load distortion map texture file
451        osg::Image* image = osgDB::readImageFile(foundFileName);
452        if (image)
453        {
454                        osg::Texture2D* texture = new osg::Texture2D;
455            texture->setImage(image);
456            texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST);
457            texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::NEAREST);
458            texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP_TO_EDGE);
459            texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP_TO_EDGE);
460            return texture;
461        }
462    }
463
464    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
465
466    return NULL;
467}
Note: See TracBrowser for help on using the repository browser.