source: experimental/distortionNG/extViewer.cpp @ 342

Last change on this file since 342 was 342, checked in by Torben Dannhauer, 12 years ago

first draft of the complete distortion framework.

File size: 14.6 KB
Line 
1#include "extViewer.h"
2#include "distortionNG.h"
3
4#include <osg/PolygonOffset>
5#include <osg/Texture2D>
6#include <osg/TextureRectangle>
7#include <osg/TexMat>
8#include <osg/ComputeBoundsVisitor>
9#include <osg/Vec2>
10
11#include <osgDB/ReadFile>
12#include <osgDB/FileUtils>
13
14#include <osgUtil/SmoothingVisitor>
15
16extViewer::extViewer() : Viewer()
17{
18}
19
20extViewer::extViewer(osg::ArgumentParser& arguments) : Viewer(arguments)
21{
22        // Add help for command-line options read here
23    arguments.getApplicationUsage()->addCommandLineOption("--distort","load distortion file and set up geometrical distortion for viewer. This includes blending");
24    arguments.getApplicationUsage()->addCommandLineOption("--blend","Set up viewer vor simple blending CullDrawThreadPerContext threading model for viewer.");
25}
26
27extViewer::extViewer(const osgViewer::Viewer& viewer, const osg::CopyOp& copyop) : Viewer(viewer, copyop)
28{
29
30}
31
32extViewer::~extViewer()
33{
34
35}
36
37//static osg::Texture2D* loadTexture( const std::string& fileName )
38//{
39//    std::string foundFileName = osgDB::findDataFile(fileName);
40//    if (foundFileName.length() != 0 )
41//    {
42//        // load distortion map texture file
43//        osg::Image* image = osgDB::readImageFile(foundFileName);
44//        if (image)
45//        {
46//                      osg::Texture2D* texture = new osg::Texture2D;
47//            texture->setImage(image);
48//                      texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
49//                      texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
50//                      texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
51//                      texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
52//            return texture;
53//        }
54//    }
55//
56//    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
57//
58//    return NULL;
59//}
60
61//static osg::TextureRectangle* loadTextureRect( const std::string& fileName )
62//{
63//    std::string foundFileName = osgDB::findDataFile(fileName);
64//    if (foundFileName.length() != 0 )
65//    {
66//        // load distortion map texture file
67//        osg::Image* image = osgDB::readImageFile(foundFileName);
68//        if (image)
69//        {
70//                      osg::TextureRectangle* texture = new osg::TextureRectangle;
71//            texture->setImage(image);
72//            texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR);
73//            texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR);
74//            texture->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP_TO_EDGE);
75//            texture->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP_TO_EDGE);
76//            return texture;
77//        }
78//    }
79//
80//    OSG_NOTIFY(osg::WARN) << "File \"" << fileName << "\" not found." << std::endl;
81//
82//    return NULL;
83//}
84
85static osg::Geometry* createMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, unsigned int columns, unsigned int rows, osg::Image* intensityMap, bool applyIntensityMapAsColours, const osg::Matrix& projectorMatrix)
86{
87        // Create Quad to render on
88        osg::ref_ptr<osg::Geometry> geom = new osg::Geometry;
89
90        geom->setUseDisplayList( false );
91
92        osg::Vec3 xAxis(widthVector);
93    float width = widthVector.length();
94    xAxis /= width;
95
96    osg::Vec3 yAxis(heightVector);
97    float height = heightVector.length();
98    yAxis /= height;
99
100        osg::Vec3 dx = xAxis*(width/((float)(columns-1)));
101    osg::Vec3 dy = yAxis*(height/((float)(rows-1)));
102
103
104        // Create vertices and coordinates
105        osg::Vec3Array* vertices = new osg::Vec3Array;
106    osg::Vec2Array* texcoords0 = new osg::Vec2Array;
107    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
108    osg::Vec4Array* colors = new osg::Vec4Array;
109
110        geom->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
111
112        for ( unsigned int row=0; row<rows; row++ )
113        {
114                for ( unsigned int col=0; col<columns; col++ )
115                {
116                        // Create coordinates of the mesh node (geometry).
117                        vertices->push_back( origin+dy*row+dx*col );
118
119                        // Create tex coordinates
120                        osg::Vec2 texcoord = osg::Vec2((float)col/(float)(columns-1), (float)row/(float)(rows-1));
121
122                        // Set Coordinates for RTT-Texture (scene rendering)
123                        texcoords0->push_back( texcoord );
124
125                        // Set Color of the mesh node
126                        if (intensityMap && applyIntensityMapAsColours)
127                        {
128                                colors->push_back(intensityMap->getColor(texcoord));
129                        }
130                        else
131                        {
132                                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
133                        }
134
135                        // Set coordinates for second texcoords array (if applyIntensityMapAsColours==true)
136                        if (texcoords1) 
137                                texcoords1->push_back( texcoord );
138                }
139        }
140
141        // Pass the created vertex array to the points geometry object.
142        geom->setUseVertexBufferObjects( true );
143        geom->setVertexArray(vertices);
144
145        geom->setColorArray(colors);
146    geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
147
148    geom->setTexCoordArray(0,texcoords0);
149    if (texcoords1)
150                geom->setTexCoordArray(1,texcoords1);
151
152        // Quads grid
153        for ( unsigned int row=0; row<rows-1; row++ )   // each strip consists of two affected vertex rows, so we need only row-1 strips.
154        {
155                osg::ref_ptr<osg::DrawElementsUInt> de = new osg::DrawElementsUInt(GL_QUAD_STRIP, columns*2);   // columns*2 = number of involved vertices for this strip.
156                for ( unsigned int col=0; col<columns; col++ )
157                {
158                        (*de)[col*2 + 0] = row*columns + col;
159                        (*de)[col*2 + 1] = (row+1)*columns + col;
160                }
161                geom->addPrimitiveSet( de.get() );
162        }
163
164        //// Triangle grid
165        //for ( unsigned int row=0; row<rows-1; row++ ) // each strip consists of two affected vertex rows, so we need only row-1 strips.
166        //{
167        //      osg::ref_ptr<osg::DrawElementsUInt> de = new osg::DrawElementsUInt(osg::PrimitiveSet::TRIANGLE_STRIP, columns * 2 );   
168        //      for ( unsigned int col=0; col<columns; col++ )
169        //      {
170        //              (*de)[col*2 + 0] = row*columns + col;
171        //              (*de)[col*2 + 1] = (row+1)*columns + col;
172        //      }
173        //      geom->addPrimitiveSet( de.get() );
174        //}
175
176        return geom.release();
177}
178
179void extViewer::setUpViewForManualDistortion(unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
180{
181        OSG_INFO<<"View::setUpViewForManualDistortion(sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
182
183    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
184    if (!wsi)
185    {
186        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
187        return;
188    }
189
190        osg::GraphicsContext::ScreenIdentifier si;
191    si.readDISPLAY();
192
193    // displayNum has not been set so reset it to 0.
194    if (si.displayNum<0) si.displayNum = 0;
195
196    si.screenNum = screenNum;
197
198    unsigned int width, height;
199    wsi->getScreenResolution(si, width, height);
200
201        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
202    traits->hostName = si.hostName;
203    traits->displayNum = si.displayNum;
204    traits->screenNum = si.screenNum;
205    traits->x = 0;
206    traits->y = 0;
207    traits->width = width;
208    traits->height = height;
209    traits->windowDecoration = false;
210    traits->doubleBuffer = true;
211    traits->sharedContext = 0;
212
213        bool applyIntensityMapAsColours = false;
214
215        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
216    if (!gc)
217    {
218        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
219        return;
220    }
221
222        // Set up projection Matrix as it is done in View::setUpViewOnSingleScreen(
223        double fovy, aspectRatio, zNear, zFar;
224        _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
225
226        double newAspectRatio = double(traits->width) / double(traits->height);
227        double aspectRatioChange = newAspectRatio / aspectRatio;
228        if (aspectRatioChange != 1.0)
229        {
230                _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
231        }
232
233
234    int tex_width = width;
235    int tex_height = height;
236
237    int camera_width = tex_width;
238    int camera_height = tex_height;
239
240    osg::TextureRectangle* sceneTexture = new osg::TextureRectangle;
241
242    sceneTexture->setTextureSize(tex_width, tex_height);
243    sceneTexture->setInternalFormat(GL_RGB);
244    sceneTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
245    sceneTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
246    sceneTexture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
247    sceneTexture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
248
249
250#if 0
251    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
252    GLenum buffer = GL_FRONT;
253#else
254    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
255    GLenum buffer = GL_FRONT;
256#endif
257
258        // Scene camera
259    {
260        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
261        camera->setName("Scene cam");
262        camera->setGraphicsContext(gc.get());
263        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
264        camera->setDrawBuffer(buffer);
265        camera->setReadBuffer(buffer);
266        camera->setAllowEventFocus(false);
267        // tell the camera to use OpenGL frame buffer object where supported.
268        camera->setRenderTargetImplementation(renderTargetImplementation);
269        // attach the texture and use it as the color buffer.
270        camera->attach(osg::Camera::COLOR_BUFFER, sceneTexture);
271
272        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
273    }
274
275    // distortion correction set up.
276    {
277                osg::Geode* geode = new osg::Geode();
278
279                // new we need to add the scene texture to the mesh, we do so by creating a
280        // StateSet to contain the Texture StateAttribute.
281            osg::StateSet* stateset = geode->getOrCreateStateSet();
282        stateset->setTextureAttributeAndModes(0, sceneTexture,osg::StateAttribute::ON);
283        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
284
285                osg::TexMat* texmat = new osg::TexMat;
286            texmat->setScaleByTextureRectangleSize(true);
287        stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
288
289                // If the intensityMap is used but not applyIntensityMapAsColours: Apply intensityMap as intensityMapTexture on unit 1
290                if (!applyIntensityMapAsColours && intensityMap)
291                        setUpIntensityMapBlending(stateset, intensityMap, screenNum, 0, 1);     
292
293                osg::Geometry* distortionMesh = createMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), 20, 20, intensityMap, applyIntensityMapAsColours, projectorMatrix);
294                geode->addDrawable(distortionMesh);
295
296        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
297        camera->setGraphicsContext(gc.get());
298        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
299        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
300        camera->setViewport(new osg::Viewport(0, 0, width, height));
301        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
302        camera->setDrawBuffer(buffer);
303        camera->setReadBuffer(buffer);
304        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
305        camera->setAllowEventFocus(false);
306        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
307        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
308
309        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
310        camera->setViewMatrix(osg::Matrix::identity());
311
312                // selector
313                geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
314                geode->getOrCreateStateSet()->setAttributeAndModes( new osg::PolygonOffset(1.0f, 1.0f) );
315                osg::ref_ptr<distortionHandler> selectorHandler = new distortionHandler( camera, distortionMesh );
316                osg::ref_ptr<osg::Group> root = new osg::Group;
317                root->addChild(geode);
318                osg::Geode* selectorHighlighter = selectorHandler->createVertexHighlighter();
319                selectorHighlighter->setCullingActive(false);   // disable the culling for the selector, otherwise the selector is culled away on the edge.
320                root->addChild(selectorHighlighter);
321                addEventHandler( selectorHandler.get() );
322                camera->addChild(root);
323                // Avoid that the highlighter is culled away
324                osg::CullSettings::CullingMode mode = camera->getCullingMode();
325                camera->setCullingMode( mode & (~osg::CullSettings::SMALL_FEATURE_CULLING) );
326
327
328        camera->setName("Dist Cam");
329
330        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
331    }
332}
333
334void extViewer::setUpIntensityMapBlending(osg::StateSet* stateset, osg::Image* intensityMap, unsigned int screenNum, int rttSceneTextureUnit, int intensityMapTextureUnit)
335{
336        if(stateset == NULL || intensityMap == NULL)
337        {
338                OSG_NOTICE<<"Error, no intensityMap or stateset for intensityMapBlending specified."<<std::endl;
339                return;
340        }
341
342        osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
343    if (!wsi)
344    {
345        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
346        return;
347    }
348
349        osg::GraphicsContext::ScreenIdentifier si;
350    si.readDISPLAY();
351
352    // displayNum has not been set so reset it to 0.
353    if (si.displayNum<0) si.displayNum = 0;
354
355    si.screenNum = screenNum;
356
357    unsigned int width, height;
358    wsi->getScreenResolution(si, width, height);
359
360        // Resize intensityMap if the dimensions are wrong
361        if(intensityMap->s()!=width || intensityMap->t()!=height)
362                intensityMap->scaleImage(width, height, intensityMap->r());
363
364        osg::TextureRectangle* intensityMapTexture = new osg::TextureRectangle(intensityMap);
365        intensityMapTexture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
366        intensityMapTexture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
367        intensityMapTexture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
368        intensityMapTexture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
369
370    stateset->setTextureAttributeAndModes(intensityMapTextureUnit, intensityMapTexture, osg::StateAttribute::ON);
371
372        // create shaders for blending
373        osg::Program* distortProgram = new osg::Program;
374        distortProgram->setName( "intensityMapBlending" );
375        osg::Shader* fShader = osg::Shader::readShaderFile( osg::Shader::FRAGMENT, "shader.frag" ); 
376        fShader->setName("intensityMapFragShader");
377
378        if ( fShader )
379        {
380                distortProgram->addShader( fShader );
381                stateset->addUniform( new osg::Uniform("sceneTexture", rttSceneTextureUnit) );
382                stateset->addUniform( new osg::Uniform("intensityMapTexture", intensityMapTextureUnit) );
383                stateset->setAttributeAndModes(distortProgram, osg::StateAttribute::ON);
384        }
385}
Note: See TracBrowser for help on using the repository browser.