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

Revision 3773, 8.3 kB (checked in by robert, 9 years ago)

From Rainer Oder, with additions from Robert. osgslice example which
generates a 3d volume from a source geometry model.

  • 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 <Producer/RenderSurface>
7#include <osg/Timer>
8#include <osgUtil/SceneView>
9#include <osgDB/ReadFile>
10#include <osgDB/WriteFile>
11
12#include <osgProducer/Viewer>
13
14#include <sstream>
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    // create the window to draw to.
113    osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface;
114    renderSurface->setWindowName("osgsimple");
115    renderSurface->setWindowRectangle(100,100,numberSlices,numberSlices);
116    renderSurface->useBorder(true);
117
118    // make sure we have a alpha channel in the colour buffer, to enable
119    // alpha on read back.
120    Producer::VisualChooser* rs_vc = renderSurface->getVisualChooser();
121    if (!rs_vc)
122    {
123        rs_vc = new Producer::VisualChooser;
124        rs_vc->setSimpleConfiguration();
125        renderSurface->setVisualChooser(rs_vc);
126    }
127    rs_vc->setAlphaSize(8);
128
129    // create the graphics context.
130    renderSurface->realize();
131   
132    // create the view of the scene.
133    osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
134    sceneView->setDefaults();
135    sceneView->setSceneData(loadedModel.get());
136
137    // initialize the view to look at the center of the scene graph
138    osg::Matrix viewMatrix;
139    // distance from viewport to object's center is set to be 2x bs.radius()
140    viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
141   
142    // turn off autocompution of near and far clipping planes
143    sceneView->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR);
144
145    // set the clear color of the background to make sure that the alpha is 0.0.
146    sceneView->setClearColor(osg::Vec4(0.0f,0.0f,0.0f,0.0f));
147
148    // record the timer tick at the start of rendering.     
149    osg::Timer_t start_tick = osg::Timer::instance()->tick();
150   
151    std::cout << "radius: " << bs.radius() << std::endl;
152   
153    unsigned int frameNum = 0;
154    double tmpNear, tmpFar;
155    std::string baseImageName("shot_");
156    std::string tmpImageName;
157   
158    osg::Image* tmpImage = new osg::Image;
159   
160    // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
161    for( unsigned int i = 0 ; i < sp->_sliceNumber && renderSurface->isRealized() ; ++i )
162    {
163        // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
164        osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp;
165        frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick()));
166        frameStamp->setFrameNumber(frameNum++);
167       
168        // pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
169        sceneView->setFrameStamp(frameStamp.get());
170       
171        // update the viewport dimensions, incase the window has been resized.
172        sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight());
173       
174       
175        // set the view
176        sceneView->setViewMatrix(viewMatrix);
177       
178        // set Projection Matrix
179        tmpNear = sp->_nearPlane+i*sp->_sliceDelta;
180        tmpFar = sp->_farPlane+(i*sp->_sliceDelta)+sp->_nearFarOffset;
181        sceneView->setProjectionMatrixAsOrtho(-(bs.radius()+bs.radius()/2), bs.radius()+bs.radius()/2,-bs.radius(), bs.radius(), tmpNear, tmpFar);
182
183        // do the update traversal the scene graph - such as updating animations
184        sceneView->update();
185       
186        // do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
187        sceneView->cull();
188       
189        // draw the rendering bins.
190        sceneView->draw();
191               
192        // Swap Buffers
193        renderSurface->swapBuffers();
194       
195        std::cout << "before readPixels: _r = " << sp->_image->r() << std::endl;
196       
197        tmpImage->readPixels(sceneView->getViewport()->x(),sceneView->getViewport()->y(),sceneView->getViewport()->width(),sceneView->getViewport()->height(),GL_RGBA,GL_UNSIGNED_BYTE);
198       
199//        std::cout << "vor copySubImage: _r = " << sp->_image->r() << std::endl;
200        sp->_image->copySubImage( 0, 0, i, tmpImage );
201
202        /*
203        std::ostringstream o;
204        o << baseImageName << i << ".rgba";
205        tmpImageName = o.str();
206        osgDB::writeImageFile( *(sp->_image), tmpImageName );
207        std::cout << "Wrote image to file: " << tmpImageName << std::endl;
208        */
209    }
210    osgDB::writeImageFile( *(sp->_image), outputName);
211
212    return 0;
213}
Note: See TracBrowser for help on using the browser.