root/OpenSceneGraph/trunk/examples/osgmemorytest/osgmemorytest.cpp @ 9395

Revision 9395, 18.3 kB (checked in by robert, 6 years ago)

Fixed warnings

Line 
1/* OpenSceneGraph example, osganimate.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#include <osg/Notify>
20#include <osg/Timer>
21#include <osg/ArgumentParser>
22#include <osg/Texture1D>
23#include <osg/Texture2D>
24#include <osg/Texture3D>
25#include <osg/Geometry>
26#include <osg/FrameBufferObject>
27
28#include <osgViewer/Version>
29
30#include <stdio.h>
31#include <iostream>
32
33class MemoryTest : public osg::Referenced
34{
35    public:
36};
37
38class GLObject : public osg::Referenced
39{
40    public:
41        virtual void apply(osg::RenderInfo& renderInfo) = 0;
42};
43
44class GLMemoryTest : public MemoryTest
45{
46    public:
47        virtual GLObject* allocate() = 0;
48};
49
50/////////////////////////////////////////////////////////////////////////
51//
52// Context test
53class ContextTest : public MemoryTest
54{
55    public:
56        ContextTest(int width, int height, bool pbuffer):
57            _width(width),
58            _height(height),
59            _pbuffer(pbuffer) {}
60       
61        virtual osg::GraphicsContext* allocate()
62        {
63            osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
64            traits->width = _width;
65            traits->height = _height;
66            traits->windowDecoration = true;
67            traits->pbuffer = _pbuffer;
68           
69            osg::ref_ptr<osg::GraphicsContext> window = osg::GraphicsContext::createGraphicsContext(traits.get());
70            if (window.valid())
71            {
72                if (window->realize())
73                {
74                    return window.release();
75                }
76                else
77                {
78                    if (_pbuffer) throw "Failed to realize PixelBuffer";
79                    else  throw "Failed to realize GraphicsWindow";
80                }
81            }
82            else
83            {
84                std::cerr<<"Error: Unable to create graphis context, problem with running osgViewer-"<<osgViewerGetVersion()<<", cannot create windows/pbuffers."<<std::endl;
85               
86                if (_pbuffer) throw "Failed to create PixelBuffer";
87                else  throw "Failed to create GraphicsWindow";
88            }
89            return 0;
90        }
91       
92
93    protected:
94   
95        int     _width;
96        int     _height;
97        bool    _pbuffer;
98};
99
100////////////////////////////////////////////////////////////////////////
101//
102// Wrap StateAttribute
103class StateAttributeObject : public GLObject
104{
105    public:
106   
107        StateAttributeObject(osg::StateAttribute* sa): _attribute(sa) {}
108       
109        void apply(osg::RenderInfo& renderInfo)
110        {
111            _attribute->apply(*renderInfo.getState());
112           
113            if (renderInfo.getState()->checkGLErrors(_attribute.get()))
114            {
115                throw "OpenGL error";
116            }
117        }
118       
119        osg::ref_ptr<osg::StateAttribute> _attribute;
120};
121
122/////////////////////////////////////////////////////////////////////////
123//
124// Texture test
125class TextureTest : public GLMemoryTest
126{
127    public:
128
129        TextureTest(int width=256, int height=256, int depth=1):
130            _width(width),
131            _height(height),
132            _depth(depth) {}
133       
134        virtual GLObject* allocate()
135        {
136            if (_depth>1)
137            {
138                osg::ref_ptr<osg::Image> image = new osg::Image;
139                image->allocateImage(_width, _height, _depth, GL_RGBA, GL_UNSIGNED_BYTE);
140               
141                osg::ref_ptr<osg::Texture3D> texture = new osg::Texture3D;
142                texture->setImage(image.get());
143                texture->setResizeNonPowerOfTwoHint(false);
144               
145                return new StateAttributeObject(texture.get());
146            }
147            if (_height>1)
148            {
149                osg::ref_ptr<osg::Image> image = new osg::Image;
150                image->allocateImage(_width, _height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
151               
152                osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
153                texture->setImage(image.get());
154                texture->setResizeNonPowerOfTwoHint(false);
155               
156                return new StateAttributeObject(texture.get());
157            }
158            if (_width>1)
159            {
160                osg::ref_ptr<osg::Image> image = new osg::Image;
161                image->allocateImage(_width, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE);
162               
163                osg::ref_ptr<osg::Texture1D> texture = new osg::Texture1D;
164                texture->setImage(image.get());
165                texture->setResizeNonPowerOfTwoHint(false);
166               
167                return new StateAttributeObject(texture.get());
168            }
169            else
170            {
171                throw "Invalid texture size of 0,0,0";
172            }
173            return 0;           
174        }
175       
176
177    protected:
178   
179        int     _width;
180        int     _height;
181        int     _depth;
182};
183
184
185/////////////////////////////////////////////////////////////////////////
186//
187// FrameBufferObject test
188class FboTest : public GLMemoryTest
189{
190    public:
191
192        FboTest(int width=1024, int height=1024, int depth=2):
193            _width(width),
194            _height(height),
195            _depth(depth) {}
196       
197        virtual GLObject* allocate()
198        {
199            osg::ref_ptr<osg::FrameBufferObject> fbo = new osg::FrameBufferObject;
200
201            if (_depth>=1) fbo->setAttachment(osg::Camera::COLOR_BUFFER, osg::FrameBufferAttachment(new osg::RenderBuffer(_width, _height, GL_RGBA)));
202            if (_depth>=2) fbo->setAttachment(osg::Camera::DEPTH_BUFFER, osg::FrameBufferAttachment(new osg::RenderBuffer(_width, _height, GL_DEPTH_COMPONENT24)));
203
204            return new StateAttributeObject(fbo.get());
205        }
206       
207
208    protected:
209   
210        int     _width;
211        int     _height;
212        int     _depth;
213};
214
215
216
217////////////////////////////////////////////////////////////////////////
218//
219// Wrap Drawable
220class DrawableObject : public GLObject
221{
222    public:
223   
224        DrawableObject(osg::Drawable* drawable): _drawable(drawable) {}
225       
226        void apply(osg::RenderInfo& renderInfo)
227        {
228            _drawable->draw(renderInfo);
229           
230            if (renderInfo.getState()->checkGLErrors("Drawable"))
231            {
232                throw "OpenGL error";
233            }
234        }
235       
236        osg::ref_ptr<osg::Drawable> _drawable;
237};
238
239/////////////////////////////////////////////////////////////////////////
240//
241// Geometry test
242class GeometryTest : public GLMemoryTest
243{
244    public:
245   
246        enum GLObjectType
247        {
248            VERTEX_ARRAY,
249            DISPLAY_LIST,
250            VERTEX_BUFFER_OBJECT
251        };
252   
253
254        GeometryTest(GLObjectType type, int width=64, int height=64):
255            _glObjectType(type),
256            _width(width),
257            _height(height) {}
258       
259        virtual GLObject* allocate()
260        {
261            unsigned int numVertices = _width * _height;
262            osg::Vec3Array* vertices = new osg::Vec3Array(numVertices);
263            for(int j=0; j<_height; ++j)
264            {
265                for(int i=0; i<_width; ++i)
266                {
267                    (*vertices)[i+j*_width].set(float(i),float(j),0.0f);
268                }
269            }
270
271            unsigned int numIndices = (_width-1) * (_height-1) * 4;
272            osg::DrawElementsUShort* quads = new osg::DrawElementsUShort(GL_QUADS);
273            quads->reserve(numIndices);
274            for(int j=0; j<_height-1; ++j)
275            {
276                for(int i=0; i<_width-1; ++i)
277                {
278                    quads->push_back(i   + j*_width);
279                    quads->push_back(i+1 + j*_width);
280                    quads->push_back(i+1 + (j+1)*_width);
281                    quads->push_back(i   + (j+1)*_width);
282                }
283            }
284           
285            osg::Geometry* geometry = new osg::Geometry;
286            geometry->setVertexArray(vertices);
287            geometry->addPrimitiveSet(quads);
288           
289            switch(_glObjectType)
290            {
291                case(VERTEX_ARRAY):
292                    geometry->setUseDisplayList(false);
293                    geometry->setUseVertexBufferObjects(false);
294                    break;
295                case(DISPLAY_LIST):
296                    geometry->setUseDisplayList(true);
297                    geometry->setUseVertexBufferObjects(false);
298                    break;
299                case(VERTEX_BUFFER_OBJECT):
300                    geometry->setUseDisplayList(false);
301                    geometry->setUseVertexBufferObjects(true);
302                    break;
303            }
304
305            return new DrawableObject(geometry);
306        }
307       
308
309    protected:
310   
311        GLObjectType    _glObjectType;
312        int             _width;
313        int             _height;
314};
315
316int main( int argc, char **argv )
317{
318    osg::ArgumentParser arguments(&argc,argv);
319   
320    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
321    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" tests OpenGL and Windowing memory scalability..");
322    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","List command line options.");
323    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Create a 512x512 pixel buffer.");
324    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer <width> <height>","Create a pixel buffer of specified dimensions.");
325    arguments.getApplicationUsage()->addCommandLineOption("--window","Create a 512x512 graphics window.");
326    arguments.getApplicationUsage()->addCommandLineOption("--window <width> <height>","Create a graphics window of specified dimensions.");
327    arguments.getApplicationUsage()->addCommandLineOption("--delay <micoseconds>","Set a delay in microseconds before all OpenGL object operations.");
328    arguments.getApplicationUsage()->addCommandLineOption("--texture <width> <height> <depth>","Allocate a 3D texture of specified dimensions.");
329    arguments.getApplicationUsage()->addCommandLineOption("--texture <width> <height>","Allocate a 2D texture of specified dimensions.");
330    arguments.getApplicationUsage()->addCommandLineOption("--texture <width>","Allocate a 1D texture of specified dimensions.");
331    arguments.getApplicationUsage()->addCommandLineOption("--geometry <width> <height>","Allocate a osg::Geometry representing a grid of specified size, using OpenGL Dislay Lists.");
332    arguments.getApplicationUsage()->addCommandLineOption("--geometry-va <width> <height>","Allocate a osg::Geometry representing a grid of specified size, using Vertex Arrays.");
333    arguments.getApplicationUsage()->addCommandLineOption("--geometry-vbo <width> <height>","Allocate a osg::Geometry representing a grid of specified size, using Vertex Buffer Objects.");
334    arguments.getApplicationUsage()->addCommandLineOption("--fbo <width> <height>","Allocate a FrameBufferObject of specified dimensions.");
335    arguments.getApplicationUsage()->addCommandLineOption("-c <num>","Set the number of contexts to create of each type specified.");
336    arguments.getApplicationUsage()->addCommandLineOption("-g <num>","Set the number of GL objects to create of each type specified.");
337
338    if (arguments.read("-h") || arguments.read("--help"))
339    {
340        arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::COMMAND_LINE_OPTION);
341        return 1;
342    }
343
344    if (arguments.argc()<=1)
345    {
346        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
347        return 1;
348    }
349
350
351    typedef std::list< osg::ref_ptr<GLMemoryTest> > GLMemoryTests;
352    typedef std::list< osg::ref_ptr<ContextTest> > ContextTests;
353
354    ContextTests contextTests;
355    GLMemoryTests glMemoryTests;
356   
357    int width, height, depth;
358    while(arguments.read("--pbuffer",width,height)) { contextTests.push_back(new ContextTest(width, height, true)); }
359    while(arguments.read("--pbuffer")) { contextTests.push_back(new ContextTest(512, 512, true)); }
360
361    while(arguments.read("--window",width,height)) { contextTests.push_back(new ContextTest(width, height, false)); }
362    while(arguments.read("--window")) { contextTests.push_back(new ContextTest(512,512, false)); }
363
364    while(arguments.read("--texture",width,height,depth)) { glMemoryTests.push_back(new TextureTest(width,height,depth)); }
365    while(arguments.read("--texture",width,height)) { glMemoryTests.push_back(new TextureTest(width,height,1)); }
366    while(arguments.read("--texture",width)) { glMemoryTests.push_back(new TextureTest(width,1,1)); }
367
368    while(arguments.read("--fbo",width,height,depth)) { glMemoryTests.push_back(new FboTest(width,height,depth)); }
369    while(arguments.read("--fbo",width,height)) { glMemoryTests.push_back(new FboTest(width,height,2)); }
370    while(arguments.read("--fbo")) { glMemoryTests.push_back(new FboTest(1024,1024,2)); }
371
372    while(arguments.read("--geometry",width,height)) { glMemoryTests.push_back(new GeometryTest(GeometryTest::DISPLAY_LIST,width,height)); }
373    while(arguments.read("--geometry")) { glMemoryTests.push_back(new GeometryTest(GeometryTest::DISPLAY_LIST,64,64)); }
374
375    while(arguments.read("--geometry-vbo",width,height)) { glMemoryTests.push_back(new GeometryTest(GeometryTest::VERTEX_BUFFER_OBJECT,width,height)); }
376    while(arguments.read("--geometry-vbo")) { glMemoryTests.push_back(new GeometryTest(GeometryTest::VERTEX_BUFFER_OBJECT,64,64)); }
377
378    while(arguments.read("--geometry-va",width,height)) { glMemoryTests.push_back(new GeometryTest(GeometryTest::VERTEX_ARRAY,width,height)); }
379    while(arguments.read("--geometry-va")) { glMemoryTests.push_back(new GeometryTest(GeometryTest::VERTEX_ARRAY,64,64)); }
380
381    unsigned int sleepTime = 0;
382    while(arguments.read("--delay",sleepTime)) {}
383
384    int maxNumContextIterations = 1;
385    while(arguments.read("-c",maxNumContextIterations)) {}
386
387    int maxNumGLIterations = 1000;
388    while(arguments.read("-g",maxNumGLIterations)) {}
389
390#if 0
391    // any option left unread are converted into errors to write out later.
392    arguments.reportRemainingOptionsAsUnrecognized();
393
394    // report any errors if they have occurred when parsing the program arguments.
395    if (arguments.errors())
396    {
397        arguments.writeErrorMessages(std::cout);
398        return 1;
399    }
400#endif
401   
402    typedef std::list< osg::ref_ptr<osg::GraphicsContext> > Contexts;
403    typedef std::list< osg::ref_ptr<GLObject> > GLObjects;
404    Contexts allocatedContexts;
405    GLObjects glObjects;
406   
407    if (contextTests.empty())
408    {
409        if (glMemoryTests.empty())
410        {
411            std::cout<<"Not tests specified, please specify test using the command line options below."<<std::endl<<std::endl;
412       
413            arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
414            return 1;           
415        }
416        else
417        {
418            contextTests.push_back(new ContextTest(512,512, false));
419        }
420    }
421
422    osg::Timer_t startTick = osg::Timer::instance()->tick();
423
424    // use printf's below as C++'s ostream classes use more memory and are more likely to fail when everything
425    // goes wrong with memory allocations.
426   
427    int numContextIterations = 0;
428    int numGLObjectIterations = 0;
429    int numGLObjectsApplied = 0;
430    try
431    {
432        for(; numGLObjectIterations<maxNumGLIterations; ++numGLObjectIterations)
433        {   
434            for(GLMemoryTests::iterator itr = glMemoryTests.begin();
435                itr != glMemoryTests.end();
436                ++itr)
437            {
438                osg::ref_ptr<GLObject> glObject = (*itr)->allocate();
439                if (glObject.valid()) glObjects.push_back(glObject.get());
440            }
441        }
442       
443        for(;numContextIterations<maxNumContextIterations; ++numContextIterations)
444        {
445            printf("GraphicsContext %i\n",numContextIterations);
446            for(ContextTests::iterator itr = contextTests.begin();
447                itr != contextTests.end();
448                ++itr)
449            {
450                osg::ref_ptr<osg::GraphicsContext> context = (*itr)->allocate();
451                if (context.valid())
452                {
453                    allocatedContexts.push_back(context);
454
455                    context->makeCurrent();
456                   
457                    osg::RenderInfo renderInfo;
458                    renderInfo.setState(context->getState());
459                   
460                    for(GLObjects::iterator gitr = glObjects.begin();
461                        gitr != glObjects.end();
462                        ++gitr)
463                    {
464                        if (sleepTime>0) OpenThreads::Thread::microSleep( sleepTime );
465
466                        printf("%i ",numGLObjectsApplied);fflush(stdout);
467
468                        (*gitr)->apply(renderInfo);
469                        ++numGLObjectsApplied;
470                    }
471                   
472                    context->releaseContext();
473                   
474                    printf("\n\n"); fflush(stdout);
475                }
476            }
477        }
478    }
479    catch(const char* errorString)
480    {
481        printf("\nException caught, contexts completed = %i, gl objects successfully applied = %i, error = %s\n\n",numContextIterations, numGLObjectsApplied, errorString);
482        return 1;
483    }
484    catch(...)
485    {
486        printf("\nException caught, contexts completed = %i, gl objects successfully applied = %i\n\n",numContextIterations, numGLObjectsApplied);
487        return 1;
488    }
489
490    osg::Timer_t endTick = osg::Timer::instance()->tick();
491
492    printf("\nSuccessful completion, contexts created = %i, gl objects applied = %i\n",numContextIterations, numGLObjectsApplied);
493    printf("Duration = %f seconds.\n\n",osg::Timer::instance()->delta_s(startTick, endTick));
494   
495
496    return 0;
497}
Note: See TracBrowser for help on using the browser.