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

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

Added a realize callback to the OsgCameraGroup?.

Move osgtexture3D across to using the new realize callback for creating its textures.

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