root/OpenSceneGraph/trunk/examples/osgslice/osgslice.cpp @ 5959

Revision 5959, 8.2 kB (checked in by robert, 8 years ago)

Ported follow examples to osgViewer:

osgshape
osgsimplifier
osgsimulation
osgslice
osgspacewarp
osgspheresegment
osgspotlight
osgstereoimage

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
2//
3// Simple example of use of Producer::RenderSurface to create an OpenGL
4// graphics window, and OSG for rendering.
5
6#include <osg/Timer>
7#include <osg/GraphicsContext>
8#include <osg/ApplicationUsage>
9#include <osgUtil/SceneView>
10#include <osgDB/ReadFile>
11#include <osgDB/WriteFile>
12
13#include <sstream>
14#include <iostream>
15
16#define MIN_NEARFAROFFSET 0.1
17
18class SliceProcessor
19{
20    public:
21
22        SliceProcessor() : _sliceNumber(128), _sliceDelta(0.1), _nearPlane(0.0), _farPlane(MIN_NEARFAROFFSET)
23        {
24            //
25        }
26        SliceProcessor( const double& objectRadius, unsigned int numberSlices) : _sliceNumber(numberSlices)
27        {
28            _sliceDelta = (objectRadius*2) / _sliceNumber;
29            _nearPlane = objectRadius;                          // note: distance from viewpoint is going to be set 2x radius
30            _farPlane = _nearPlane+MIN_NEARFAROFFSET;
31            _image = new osg::Image;
32            if( _sliceDelta > MIN_NEARFAROFFSET )
33            {
34                _nearFarOffset = MIN_NEARFAROFFSET;
35            }
36            else
37            {
38                _nearFarOffset = _sliceDelta;
39            }
40            _image->allocateImage( _sliceNumber, _sliceNumber,_sliceNumber, GL_RGBA, GL_UNSIGNED_BYTE );
41           
42        }
43        // needs 3D-Texture object
44        osg::Image* _image;
45        unsigned int _sliceNumber;
46        double _sliceDelta;
47        double _nearPlane;
48        double _farPlane;
49        double _nearFarOffset;
50       
51    // needs function to do rendering and slicing
52};
53
54int main( int argc, char **argv )
55{
56        // use an ArgumentParser object to manage the program arguments.
57    osg::ArgumentParser arguments(&argc,argv);
58
59    // set up the usage document, in case we need to print out how to use this program.
60    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes.");
61    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
62    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
63    arguments.getApplicationUsage()->addCommandLineOption("-o <filename>","Object to be loaded");
64   
65    if( arguments.read( "-h" ) || arguments.read( "--help" ) )
66    {
67        std::cout << "Argumentlist:" << std::endl;
68        std::cout << "\t-o <filename> sets object to be loaded and sliced" << std::endl;
69        std::cout << "\t--slices <unsigned int> sets number of slices through the object" << std::endl;
70        std::cout << "\t--near <double> sets start for near clipping plane" << std::endl;
71        std::cout << "\t--far <double> sets start for far clipping plane" << std::endl;
72       
73        return 1;
74    }
75   
76    std::string outputName("volume_tex.dds");
77    while( arguments.read( "-o", outputName ) ) { }
78
79
80    unsigned int numberSlices = 128;
81    while( arguments.read( "--slices", numberSlices) ) { }
82
83    double nearClip=0.0f;
84    double farClip=0.0f;
85    while( arguments.read( "--near",nearClip ) ) { }
86    while( arguments.read( "--far", farClip) ) { }
87
88   
89    // load the scene.
90    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles( arguments );
91    if (!loadedModel)
92    {
93        std::cout << "No data loaded." << std::endl;
94        return 1;
95    }
96
97    const osg::BoundingSphere& bs = loadedModel->getBound();
98    SliceProcessor* sp = new SliceProcessor( (double)bs.radius(), numberSlices );
99    if (nearClip!=0.0) sp->_nearPlane = nearClip;
100    if (farClip!=0.0) sp->_farPlane = farClip;
101
102    // any option left unread are converted into errors to write out later.
103    arguments.reportRemainingOptionsAsUnrecognized();
104
105    // report any errors if they have occured when parsing the program aguments.
106    if (arguments.errors())
107    {
108        arguments.writeErrorMessages(std::cout);
109        return 1;
110    }
111   
112
113
114    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
115    traits->x = 100;
116    traits->y = 100;
117    traits->width = numberSlices;
118    traits->height = numberSlices;
119    traits->alpha = 8;
120    traits->windowDecoration = true;
121    traits->doubleBuffer = true;
122    traits->sharedContext = 0;
123    traits->pbuffer = false;
124
125    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
126    if (!gc || !gc->valid())
127    {
128        osg::notify(osg::NOTICE)<<"Error: unable to create graphics window"<<std::endl;
129        return 1;
130    }
131   
132    gc->realize();
133    gc->makeCurrent();
134
135    // create the view of the scene.
136    osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
137    sceneView->setDefaults();
138    sceneView->setSceneData(loadedModel.get());
139
140    // initialize the view to look at the center of the scene graph
141    osg::Matrix viewMatrix;
142    // distance from viewport to object's center is set to be 2x bs.radius()
143    viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
144   
145    // turn off autocompution of near and far clipping planes
146    sceneView->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR);
147
148    // set the clear color of the background to make sure that the alpha is 0.0.
149    sceneView->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
150
151    // record the timer tick at the start of rendering.     
152    osg::Timer_t start_tick = osg::Timer::instance()->tick();
153   
154    std::cout << "radius: " << bs.radius() << std::endl;
155   
156    unsigned int frameNum = 0;
157    double tmpNear, tmpFar;
158    std::string baseImageName("shot_");
159    std::string tmpImageName;
160   
161    osg::Image* tmpImage = new osg::Image;
162   
163    // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
164    for( unsigned int i = 0 ; i < sp->_sliceNumber && gc->isRealized() ; ++i )
165    {
166        // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
167        osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp;
168        frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
169        frameStamp->setFrameNumber(frameNum++);
170       
171        // pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
172        sceneView->setFrameStamp(frameStamp.get());
173       
174        // update the viewport dimensions, incase the window has been resized.
175        sceneView->setViewport(0,0,traits->width,traits->height);
176       
177       
178        // set the view
179        sceneView->setViewMatrix(viewMatrix);
180       
181        // set Projection Matrix
182        tmpNear = sp->_nearPlane+i*sp->_sliceDelta;
183        tmpFar = sp->_farPlane+(i*sp->_sliceDelta)+sp->_nearFarOffset;
184        sceneView->setProjectionMatrixAsOrtho(-(bs.radius()+bs.radius()/2), bs.radius()+bs.radius()/2,-bs.radius(), bs.radius(), tmpNear, tmpFar);
185
186        // do the update traversal the scene graph - such as updating animations
187        sceneView->update();
188       
189        // do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
190        sceneView->cull();
191       
192        // draw the rendering bins.
193        sceneView->draw();
194               
195        // Swap Buffers
196        gc->swapBuffers();
197       
198        std::cout << "before readPixels: _r = " << sp->_image->r() << std::endl;
199       
200        tmpImage->readPixels(sceneView->getViewport()->x(),sceneView->getViewport()->y(),sceneView->getViewport()->width(),sceneView->getViewport()->height(),GL_RGBA,GL_UNSIGNED_BYTE);
201       
202//        std::cout << "vor copySubImage: _r = " << sp->_image->r() << std::endl;
203        sp->_image->copySubImage( 0, 0, i, tmpImage );
204
205        /*
206        std::ostringstream o;
207        o << baseImageName << i << ".rgba";
208        tmpImageName = o.str();
209        osgDB::writeImageFile( *(sp->_image), tmpImageName );
210        std::cout << "Wrote image to file: " << tmpImageName << std::endl;
211        */
212    }
213    osgDB::writeImageFile( *(sp->_image), outputName);
214
215    return 0;
216}
Note: See TracBrowser for help on using the browser.