root/OpenSceneGraph/trunk/examples/osgmanipulator/osgmanipulator.cpp @ 13855

Revision 13855, 18.2 kB (checked in by robert, 3 hours ago)

From Claus Steuer, "XCode 6, IOs 8.1 SDK Compile fix : There are some undefined texture formats when compiling osg for IOs 8.1 with XCode 6 and OpenGLES2 enabled."

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgmanipulator.
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 <osgDB/ReadFile>
20#include <osgUtil/Optimizer>
21#include <osgViewer/Viewer>
22#include <osg/CoordinateSystemNode>
23#include <osgText/Text>
24
25#include <osgManipulator/TabBoxDragger>
26#include <osgManipulator/TabBoxTrackballDragger>
27#include <osgManipulator/TabPlaneDragger>
28#include <osgManipulator/TabPlaneTrackballDragger>
29#include <osgManipulator/Scale1DDragger>
30#include <osgManipulator/Scale2DDragger>
31#include <osgManipulator/TrackballDragger>
32#include <osgManipulator/Translate1DDragger>
33#include <osgManipulator/Translate2DDragger>
34#include <osgManipulator/TranslateAxisDragger>
35#include <osgManipulator/TranslatePlaneDragger>
36#include <osgManipulator/RotateCylinderDragger>
37
38#include <osg/ShapeDrawable>
39#include <osg/MatrixTransform>
40#include <osg/Geometry>
41#include <osg/Material>
42#include <osg/io_utils>
43
44#include <iostream>
45
46class PlaneConstraint : public osgManipulator::Constraint
47{
48public:
49        PlaneConstraint() {}
50   
51        virtual bool constrain(osgManipulator::TranslateInLineCommand& command) const
52        {
53            OSG_NOTICE<<"PlaneConstraint TranslateInLineCommand "<<command.getTranslation()<<std::endl;
54            return true;           
55        }
56        virtual bool constrain(osgManipulator::TranslateInPlaneCommand& command) const
57        {
58            //command.setTranslation(osg::Vec3(0.0f,0.0f,0.0f));
59            OSG_NOTICE<<"PlaneConstraint TranslateInPlaneCommand "<<command.getTranslation()<<std::endl;
60            return true;
61        }
62        virtual bool constrain(osgManipulator::Scale1DCommand& command) const
63        {
64            //command.setScale(1.0f);
65            OSG_NOTICE<<"PlaneConstraint Scale1DCommand"<<command.getScale()<<std::endl;
66            return true;           
67        }
68        virtual bool constrain(osgManipulator::Scale2DCommand& command) const
69        {
70            //command.setScale(osg::Vec2d(1.0,1.0));
71            OSG_NOTICE<<"PlaneConstraint Scale2DCommand "<<command.getScale()<<std::endl;
72            return true;
73        }
74        virtual bool constrain(osgManipulator::ScaleUniformCommand& command) const
75        {
76            OSG_NOTICE<<"PlaneConstraint ScaleUniformCommand"<<command.getScale()<<std::endl;
77            return true;           
78        }
79};
80
81
82
83osgManipulator::Dragger* createDragger(const std::string& name)
84{
85    osgManipulator::Dragger* dragger = 0;
86    if ("TabPlaneDragger" == name)
87    {
88        osgManipulator::TabPlaneDragger* d = new osgManipulator::TabPlaneDragger();
89        d->setupDefaultGeometry();
90        d->addConstraint(new PlaneConstraint());
91        dragger = d;
92    }
93    else if ("TabPlaneTrackballDragger" == name)
94    {
95        osgManipulator::TabPlaneTrackballDragger* d = new osgManipulator::TabPlaneTrackballDragger();
96        d->setupDefaultGeometry();
97        dragger = d;
98    }
99    else if ("TabBoxTrackballDragger" == name)
100    {
101        osgManipulator::TabBoxTrackballDragger* d = new osgManipulator::TabBoxTrackballDragger();
102        d->setupDefaultGeometry();
103        dragger = d;
104    }
105    else if ("TrackballDragger" == name)
106    {
107        osgManipulator::TrackballDragger* d = new osgManipulator::TrackballDragger();
108        d->setupDefaultGeometry();
109        d->setAxisLineWidth(5.0f);
110        d->setPickCylinderHeight(0.1f);
111        dragger = d;
112    }
113    else if ("Translate1DDragger" == name)
114    {
115        osgManipulator::Translate1DDragger* d = new osgManipulator::Translate1DDragger();
116        d->setupDefaultGeometry();
117        dragger = d;
118    }
119    else if ("Translate2DDragger" == name)
120    {
121        osgManipulator::Translate2DDragger* d = new osgManipulator::Translate2DDragger();
122        d->setupDefaultGeometry();
123        dragger = d;
124    }
125    else if ("TranslateAxisDragger" == name)
126    {
127        osgManipulator::TranslateAxisDragger* d = new osgManipulator::TranslateAxisDragger();
128        d->setupDefaultGeometry();
129        d->setAxisLineWidth(5.0f);
130        d->setPickCylinderRadius(0.05f);
131        d->setConeHeight(0.2f);
132        dragger = d;
133    }
134    else if ("TranslatePlaneDragger" == name)
135    {
136        osgManipulator::TranslatePlaneDragger* d = new osgManipulator::TranslatePlaneDragger();
137        d->setupDefaultGeometry();
138        dragger = d;
139    }
140    else if ("Scale1DDragger" == name)
141    {
142        osgManipulator::Scale1DDragger* d = new osgManipulator::Scale1DDragger();
143        d->setupDefaultGeometry();
144        dragger = d;
145    }
146    else if ("Scale2DDragger" == name)
147    {
148        osgManipulator::Scale2DDragger* d = new osgManipulator::Scale2DDragger();
149        d->setupDefaultGeometry();
150        dragger = d;
151    }
152    else if ("RotateCylinderDragger" == name)
153    {
154        osgManipulator::RotateCylinderDragger* d = new osgManipulator::RotateCylinderDragger();
155        d->setupDefaultGeometry();
156        dragger = d;
157    }
158    else if ("RotateSphereDragger" == name)
159    {
160        osgManipulator::RotateSphereDragger* d = new osgManipulator::RotateSphereDragger();
161        d->setupDefaultGeometry();
162        dragger = d;
163    }
164    else
165    {
166        osgManipulator::TabBoxDragger* d = new osgManipulator::TabBoxDragger();
167        d->setupDefaultGeometry();
168        dragger = d;
169    }
170
171   
172 
173    return dragger;
174}
175
176// The DraggerContainer node is used to fix the dragger's size on the screen
177class DraggerContainer : public osg::Group
178{
179public:
180    DraggerContainer() : _draggerSize(240.0f), _active(true) {}
181   
182    DraggerContainer( const DraggerContainer& copy, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY )
183    :   osg::Group(copy, copyop),
184        _dragger(copy._dragger), _draggerSize(copy._draggerSize), _active(copy._active)
185    {}
186   
187    META_Node( osgManipulator, DraggerContainer );
188   
189    void setDragger( osgManipulator::Dragger* dragger )
190    {
191        _dragger = dragger;
192        if ( !containsNode(dragger) ) addChild( dragger );
193    }
194   
195    osgManipulator::Dragger* getDragger() { return _dragger.get(); }
196    const osgManipulator::Dragger* getDragger() const { return _dragger.get(); }
197   
198    void setDraggerSize( float size ) { _draggerSize = size; }
199    float getDraggerSize() const { return _draggerSize; }
200   
201    void setActive( bool b ) { _active = b; }
202    bool getActive() const { return _active; }
203   
204    void traverse( osg::NodeVisitor& nv )
205    {
206        if ( _dragger.valid() )
207        {
208            if ( _active && nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR )
209            {
210                osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(&nv);
211               
212                float pixelSize = cv->pixelSize(_dragger->getBound().center(), 0.48f);
213                if ( pixelSize!=_draggerSize )
214                {
215                    float pixelScale = pixelSize>0.0f ? _draggerSize/pixelSize : 1.0f;
216                    osg::Vec3d scaleFactor(pixelScale, pixelScale, pixelScale);
217                   
218                    osg::Vec3 trans = _dragger->getMatrix().getTrans();
219                    _dragger->setMatrix( osg::Matrix::scale(scaleFactor) * osg::Matrix::translate(trans) );
220                }
221            }
222        }
223        osg::Group::traverse(nv);
224    }
225   
226protected:
227    osg::ref_ptr<osgManipulator::Dragger> _dragger;
228    float _draggerSize;
229    bool _active;
230};
231
232osg::Node* addDraggerToScene(osg::Node* scene, const std::string& name, bool fixedSizeInScreen)
233{
234    scene->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
235
236    osg::MatrixTransform* transform = new osg::MatrixTransform;
237    transform->addChild(scene);
238
239    osgManipulator::Dragger* dragger = createDragger(name);
240
241    osg::Group* root = new osg::Group;
242    root->addChild(transform);
243
244    if ( fixedSizeInScreen )
245    {
246        DraggerContainer* draggerContainer = new DraggerContainer;
247        draggerContainer->setDragger( dragger );
248        root->addChild(draggerContainer);
249    }
250    else
251        root->addChild(dragger);
252
253    float scale = scene->getBound().radius() * 1.6;
254    dragger->setMatrix(osg::Matrix::scale(scale, scale, scale) *
255                       osg::Matrix::translate(scene->getBound().center()));
256
257    if (dynamic_cast<osgManipulator::TabPlaneDragger*>(dragger))
258    {
259        dragger->addTransformUpdating(transform, osgManipulator::DraggerTransformCallback::HANDLE_TRANSLATE_IN_LINE);
260    }
261    else
262    {
263        dragger->addTransformUpdating(transform);
264    }
265
266    // we want the dragger to handle it's own events automatically
267    dragger->setHandleEvents(true);
268
269    // if we don't set an activation key or mod mask then any mouse click on
270    // the dragger will activate it, however if do define either of ActivationModKeyMask or
271    // and ActivationKeyEvent then you'll have to press either than mod key or the specified key to
272    // be able to activate the dragger when you mouse click on it.  Please note the follow allows
273    // activation if either the ctrl key or the 'a' key is pressed and held down.
274    dragger->setActivationModKeyMask(osgGA::GUIEventAdapter::MODKEY_CTRL);
275    dragger->setActivationKeyEvent('a');
276
277    return root;
278}
279
280osg::Node* createDemoScene(bool fixedSizeInScreen) {
281 
282    osg::Group* root = new osg::Group;
283
284    osg::ref_ptr<osg::Geode> geode_1 = new osg::Geode;
285    osg::ref_ptr<osg::MatrixTransform> transform_1 = new osg::MatrixTransform;
286
287    osg::ref_ptr<osg::Geode> geode_2 = new osg::Geode;
288    osg::ref_ptr<osg::MatrixTransform> transform_2 = new osg::MatrixTransform;
289
290    osg::ref_ptr<osg::Geode> geode_3 = new osg::Geode;
291    osg::ref_ptr<osg::MatrixTransform> transform_3 = new osg::MatrixTransform;
292
293    osg::ref_ptr<osg::Geode> geode_4 = new osg::Geode;
294    osg::ref_ptr<osg::MatrixTransform> transform_4 = new osg::MatrixTransform;
295
296    osg::ref_ptr<osg::Geode> geode_5 = new osg::Geode;
297    osg::ref_ptr<osg::MatrixTransform> transform_5 = new osg::MatrixTransform;
298
299    osg::ref_ptr<osg::Geode> geode_6 = new osg::Geode;
300    osg::ref_ptr<osg::MatrixTransform> transform_6 = new osg::MatrixTransform;
301
302    osg::ref_ptr<osg::Geode> geode_7 = new osg::Geode;
303    osg::ref_ptr<osg::MatrixTransform> transform_7 = new osg::MatrixTransform;
304
305 
306
307
308
309    const float radius = 0.8f;
310    const float height = 1.0f;
311    osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints;
312    hints->setDetailRatio(2.0f);
313    osg::ref_ptr<osg::ShapeDrawable> shape;
314
315    shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -2.0f), 10, 10.0f, 0.1f), hints.get());
316    shape->setColor(osg::Vec4(0.5f, 0.5f, 0.7f, 1.0f));
317    geode_1->addDrawable(shape.get());
318
319    shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), radius * 2,radius), hints.get());
320    shape->setColor(osg::Vec4(0.8f, 0.8f, 0.8f, 1.0f));
321    geode_2->addDrawable(shape.get());
322
323    shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(-3.0f, 0.0f, 0.0f), radius,radius), hints.get());
324    shape->setColor(osg::Vec4(0.6f, 0.8f, 0.8f, 1.0f));
325    geode_3->addDrawable(shape.get());
326
327    shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(3.0f, 0.0f, 0.0f), 2 * radius,radius), hints.get());
328    shape->setColor(osg::Vec4(0.4f, 0.9f, 0.3f, 1.0f));
329    geode_4->addDrawable(shape.get());
330
331    shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, -3.0f, 0.0f), radius, height), hints.get());
332    shape->setColor(osg::Vec4(0.2f, 0.5f, 0.7f, 1.0f));
333    geode_5->addDrawable(shape.get());
334
335    shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 3.0f, 0.0f), radius, height), hints.get());
336    shape->setColor(osg::Vec4(1.0f, 0.3f, 0.3f, 1.0f));
337    geode_6->addDrawable(shape.get());
338
339    shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, 0.0f, 3.0f), 2.0f, 2.0f), hints.get());
340    shape->setColor(osg::Vec4(0.8f, 0.8f, 0.4f, 1.0f));
341    geode_7->addDrawable(shape.get());
342
343
344
345
346
347
348    // material
349    osg::ref_ptr<osg::Material> matirial = new osg::Material;
350    matirial->setColorMode(osg::Material::DIFFUSE);
351    matirial->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
352    matirial->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
353    matirial->setShininess(osg::Material::FRONT_AND_BACK, 64.0f);
354    root->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), osg::StateAttribute::ON);
355
356    transform_1.get()->addChild(addDraggerToScene(geode_1.get(),"TabBoxDragger",fixedSizeInScreen));
357    transform_2.get()->addChild(addDraggerToScene(geode_2.get(),"TabPlaneDragger",fixedSizeInScreen));
358    transform_3.get()->addChild(addDraggerToScene(geode_3.get(),"TabBoxTrackballDragger",fixedSizeInScreen));
359    transform_4.get()->addChild(addDraggerToScene(geode_4.get(),"TrackballDragger",fixedSizeInScreen));
360    transform_5.get()->addChild(addDraggerToScene(geode_5.get(),"Translate1DDragger",fixedSizeInScreen));
361    transform_6.get()->addChild(addDraggerToScene(geode_6.get(),"Translate2DDragger",fixedSizeInScreen));
362    transform_7.get()->addChild(addDraggerToScene(geode_7.get(),"TranslateAxisDragger",fixedSizeInScreen));
363
364    root->addChild(transform_1.get());
365    root->addChild(transform_2.get());
366    root->addChild(transform_3.get());
367    root->addChild(transform_4.get());
368    root->addChild(transform_5.get());
369    root->addChild(transform_6.get());
370    root->addChild(transform_7.get());
371
372 
373 
374    return root;
375}
376//
377int main( int argc, char **argv )
378{
379
380    // use an ArgumentParser object to manage the program arguments.
381    osg::ArgumentParser arguments(&argc,argv);
382   
383    // set up the usage document, in case we need to print out how to use this program.
384    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
385    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
386    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
387    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
388    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
389    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
390    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
391    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");
392
393    arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation [TabPlaneDragger, TabPlaneTrackballDragger, TrackballDragger, Translate1DDragger, Translate2DDragger, TranslateAxisDragger, TabBoxDragger, TranslatePlaneDragger, Scale1DDragger, Scale2DDragger, RotateCylinderDragger, RotateSphereDragger]");
394    arguments.getApplicationUsage()->addCommandLineOption("--fixedDraggerSize","Fix the size of the dragger geometry in the screen space");
395   
396    bool fixedSizeInScreen = false;
397    while (arguments.read("--fixedDraggerSize")) { fixedSizeInScreen = true; }
398
399    // construct the viewer.
400    osgViewer::Viewer viewer;
401
402    // get details on keyboard and mouse bindings used by the viewer.
403    viewer.getUsage(*arguments.getApplicationUsage());
404
405    // if user request help write it out to cout.
406    bool helpAll = arguments.read("--help-all");
407    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
408                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
409                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
410    if (helpType)
411    {
412        arguments.getApplicationUsage()->write(std::cout, helpType);
413        return 1;
414    }
415
416    // report any errors if they have occurred when parsing the program arguments.
417    if (arguments.errors())
418    {
419        arguments.writeErrorMessages(std::cout);
420        return 1;
421    }
422
423    std::string dragger_name = "TabBoxDragger";
424    arguments.read("--dragger", dragger_name);
425
426    osg::Timer_t start_tick = osg::Timer::instance()->tick();
427
428    // read the scene from the list of file specified command line args.
429    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
430
431    // if no model has been successfully loaded report failure.
432    bool tragger2Scene(true);
433    if (!loadedModel)
434    {
435        //std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
436        //return 1;
437        loadedModel = createDemoScene(fixedSizeInScreen);
438        tragger2Scene=false;
439    }
440
441    // any option left unread are converted into errors to write out later.
442    arguments.reportRemainingOptionsAsUnrecognized();
443
444    // report any errors if they have occurred when parsing the program arguments.
445    if (arguments.errors())
446    {
447        arguments.writeErrorMessages(std::cout);
448    }
449
450    osg::Timer_t end_tick = osg::Timer::instance()->tick();
451
452    std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;
453
454
455    // optimize the scene graph, remove redundant nodes and state etc.
456    osgUtil::Optimizer optimizer;
457    optimizer.optimize(loadedModel.get());
458
459   
460    // pass the loaded scene graph to the viewer.
461    if ( tragger2Scene ) {
462        viewer.setSceneData(addDraggerToScene(loadedModel.get(), dragger_name, fixedSizeInScreen));
463    } else {
464        viewer.setSceneData(loadedModel.get());
465    }
466
467
468    return viewer.run();
469}
Note: See TracBrowser for help on using the browser.