root/OpenSceneGraph/trunk/examples/osgtexture3D/osgtexture3D.cpp @ 1815

Revision 1815, 10.3 kB (checked in by robert, 12 years ago)

Added the usage report to the examples for when no arguments are passed
to the examples.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/Node>
2#include <osg/Geometry>
3#include <osg/Notify>
4#include <osg/Texture3D>
5#include <osg/TexGen>
6#include <osg/Geode>
7
8#include <osgDB/Registry>
9#include <osgDB/ReadFile>
10
11#include <osgProducer/Viewer>
12
13
14//
15// A simple demo demonstrating different texturing modes,
16// including using of texture extensions.
17//
18
19
20typedef std::vector< osg::ref_ptr<osg::Image> > ImageList;
21
22
23class ConstructStateCallback : public osgProducer::OsgCameraGroup::RealizeCallback
24{
25    public:
26        ConstructStateCallback(osg::Node* node):_node(node),_initialized(false) {}
27       
28        osg::StateSet* constructState()
29        {
30       
31            // read 4 2d images
32            osg::ref_ptr<osg::Image> image_0 = osgDB::readImageFile("Images/lz.rgb");
33            osg::ref_ptr<osg::Image> image_1 = osgDB::readImageFile("Images/reflect.rgb");
34            osg::ref_ptr<osg::Image> image_2 = osgDB::readImageFile("Images/tank.rgb");
35            osg::ref_ptr<osg::Image> image_3 = osgDB::readImageFile("Images/skymap.jpg");
36
37            if (!image_0 || !image_1 || !image_2 || !image_3)
38            {
39                std::cout << "Warning: could not open files."<<std::endl;
40                return new osg::StateSet;
41            }
42
43            if (image_0->getPixelFormat()!=image_1->getPixelFormat() || image_0->getPixelFormat()!=image_2->getPixelFormat() || image_0->getPixelFormat()!=image_3->getPixelFormat())
44            {
45                std::cout << "Warning: image pixel formats not compatible."<<std::endl;
46                return new osg::StateSet;
47            }
48
49            // get max 3D texture size
50            GLint textureSize = osg::Texture3D::getExtensions(0,true)->maxTexture3DSize();
51            if (textureSize > 256)
52                textureSize = 256;
53
54            // scale them all to the same size.
55            image_0->scaleImage(textureSize,textureSize,1);
56            image_1->scaleImage(textureSize,textureSize,1);
57            image_2->scaleImage(textureSize,textureSize,1);
58            image_3->scaleImage(textureSize,textureSize,1);
59
60
61            // then allocated a 3d image to use for texturing.
62            osg::Image* image_3d = new osg::Image;
63            image_3d->allocateImage(textureSize,textureSize,4,
64                                    image_0->getPixelFormat(),image_0->getDataType());
65
66            // copy the 2d images into the 3d image.
67            image_3d->copySubImage(0,0,0,image_0.get());
68            image_3d->copySubImage(0,0,1,image_1.get());
69            image_3d->copySubImage(0,0,2,image_2.get());
70            image_3d->copySubImage(0,0,3,image_3.get());
71
72            image_3d->setInternalTextureFormat(image_0->getInternalTextureFormat());       
73
74            // set up the 3d texture itself,
75            // note, well set the filtering up so that mip mapping is disabled,
76            // gluBuild3DMipsmaps doesn't do a very good job of handled the
77            // inbalanced dimensions of the 256x256x4 texture.
78            osg::Texture3D* texture3D = new osg::Texture3D;
79            texture3D->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR);
80            texture3D->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR);
81            texture3D->setWrap(osg::Texture3D::WRAP_R,osg::Texture3D::REPEAT);
82            texture3D->setImage(image_3d);
83
84
85            // create a texgen to generate a R texture coordinate, the geometry
86            // itself will supply the S & T texture coordinates.
87            // in the animateStateSet callback well alter this R value to
88            // move the texture through the 3d texture, 3d texture filtering
89            // will do the blending for us.
90            osg::TexGen* texgen = new osg::TexGen;
91            texgen->setMode(osg::TexGen::OBJECT_LINEAR);
92            texgen->setPlane(osg::TexGen::R, osg::Vec4(0.0f,0.0f,0.0f,0.2f));
93
94            // create the StateSet to store the texture data
95            osg::StateSet* stateset = new osg::StateSet;
96            stateset->setTextureMode(0,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
97            stateset->setTextureAttribute(0,texgen);
98            stateset->setTextureAttributeAndModes(0,texture3D,osg::StateAttribute::ON);
99
100            return stateset;
101        }
102
103        virtual void operator()( osgProducer::OsgCameraGroup&, osgProducer::OsgSceneHandler& sh, const Producer::RenderSurface& )
104        {
105            if (!_initialized)
106            {
107                // only initialize state once, only need for cases where multiple graphics contexts are
108                // if which case this callback can get called multiple times.
109                _initialized = true;
110
111                if (_node) _node->setStateSet(constructState());
112            }           
113            // now safe to con
114            sh.init();
115           
116        }
117       
118       
119        osg::Node*  _node;
120        bool        _initialized;
121       
122};
123
124class UpdateStateCallback : public osg::NodeCallback
125{
126    public:
127        UpdateStateCallback() {}
128       
129        void animateState(osg::StateSet* stateset)
130        {
131            // here we simply get any existing texgen, and then increment its
132            // plane, pushing the R coordinate through the texture.
133            osg::StateAttribute* attribute = stateset->getTextureAttribute(0,osg::StateAttribute::TEXGEN);
134            osg::TexGen* texgen = dynamic_cast<osg::TexGen*>(attribute);
135            if (texgen)
136            {
137                texgen->getPlane(osg::TexGen::R)[3] += 0.001f;
138            }
139
140        }
141
142        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
143        {
144
145            osg::StateSet* stateset = node->getStateSet();
146            if (stateset)
147            {
148                // we have an exisitng stateset, so lets animate it.
149                animateState(stateset);
150            }
151
152            // note, callback is repsonsible for scenegraph traversal so
153            // should always include call the traverse(node,nv) to ensure
154            // that the rest of cullbacks and the scene graph are traversed.
155            traverse(node,nv);
156        }     
157};
158
159/** create 2,2 square with center at 0,0,0 and aligned along the XZ plan */
160osg::Drawable* createSquare(float textureCoordMax=1.0f)
161{
162    // set up the Geometry.
163    osg::Geometry* geom = new osg::Geometry;
164
165    osg::Vec3Array* coords = new osg::Vec3Array(4);
166    (*coords)[0].set(-1.0f,0.0f,1.0f);
167    (*coords)[1].set(-1.0f,0.0f,-1.0f);
168    (*coords)[2].set(1.0f,0.0f,-1.0f);
169    (*coords)[3].set(1.0f,0.0f,1.0f);
170    geom->setVertexArray(coords);
171
172    osg::Vec3Array* norms = new osg::Vec3Array(1);
173    (*norms)[0].set(0.0f,-1.0f,0.0f);
174    geom->setNormalArray(norms);
175    geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
176
177    osg::Vec2Array* tcoords = new osg::Vec2Array(4);
178    (*tcoords)[0].set(0.0f,textureCoordMax);
179    (*tcoords)[1].set(0.0f,0.0f);
180    (*tcoords)[2].set(textureCoordMax,0.0f);
181    (*tcoords)[3].set(textureCoordMax,textureCoordMax);
182    geom->setTexCoordArray(0,tcoords);
183   
184    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
185
186    return geom;
187}
188
189osg::Node* createModel()
190{
191
192    // create the geometry of the model, just a simple 2d quad right now.   
193    osg::Geode* geode = new osg::Geode;
194    geode->addDrawable(createSquare());
195
196    // normally we'd create the stateset's to contain all the textures
197    // etc here, but, the above technique uses osg::Image::scaleImage and
198    // osg::Image::copySubImage() which are implemented with OpenGL utility
199    // library, which unfortunately can't be used until we have a valid
200    // OpenGL context, and at this point in initilialization we don't have
201    // a valid OpenGL context, so we have to delay creation of state until
202    // there is a valid OpenGL context.  I'll manage this by using an
203    // app callback which will create the state during the first traversal.
204    // A bit hacky, and my plan is to reimplement the osg::scaleImage and
205    // osg::Image::copySubImage() without using GLU which will get round
206    // this current limitation.
207    geode->setUpdateCallback(new UpdateStateCallback());
208   
209    return geode;
210
211}
212
213
214int main( int argc, char **argv )
215{
216
217    // use an ArgumentParser object to manage the program arguments.
218    osg::ArgumentParser arguments(&argc,argv);
219   
220    // set up the usage document, in case we need to print out how to use this program.
221    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
222    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
223   
224
225    // construct the viewer.
226    osgProducer::Viewer viewer(arguments);
227
228    // set up the value with sensible default event handlers.
229    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
230
231    // get details on keyboard and mouse bindings used by the viewer.
232    viewer.getUsage(*arguments.getApplicationUsage());
233
234    // if user request help write it out to cout.
235    if (arguments.read("-h") || arguments.read("--help"))
236    {
237        arguments.getApplicationUsage()->write(std::cout);
238        return 1;
239    }
240
241    // any option left unread are converted into errors to write out later.
242    arguments.reportRemainingOptionsAsUnrecognized();
243
244    // report any errors if they have occured when parsing the program aguments.
245    if (arguments.errors())
246    {
247        arguments.writeErrorMessages(std::cout);
248        return 1;
249    }
250   
251    // create a model from the images.
252    osg::Node* rootNode = createModel();
253
254    if (rootNode)
255    {
256
257        // set the scene to render
258        viewer.setSceneData(rootNode);
259       
260        // the construct state uses gl commands to resize images so we are forced
261        // to only call it once a valid graphics context has been established,
262        // for that we use a realize callback.
263        viewer.setRealizeCallback(new ConstructStateCallback(rootNode));
264
265        // create the windows and run the threads.
266        viewer.realize(Producer::CameraGroup::ThreadPerCamera);
267
268        while( !viewer.done() )
269        {
270            // wait for all cull and draw threads to complete.
271            viewer.sync();
272
273            // update the scene by traversing it with the the update visitor which will
274            // call all node update callbacks and animations.
275            viewer.update();
276
277            // fire off the cull and draw traversals of the scene.
278            viewer.frame();
279
280        }
281       
282
283        // wait for all cull and draw threads to complete before exit.
284        viewer.sync();
285    }   
286   
287    return 0;
288}
Note: See TracBrowser for help on using the browser.