]> git.mxchange.org Git - flightgear.git/blob - src/Main/fgviewer.cxx
Get fgviewer working as a part of fgfs
[flightgear.git] / src / Main / fgviewer.cxx
1 #include <iostream>
2 #include <cstdlib>
3
4 #include <osg/ArgumentParser>
5 #include <osg/Fog>
6 #include <osgDB/ReadFile>
7 #include <osgDB/Registry>
8 #include <osgDB/WriteFile>
9 #include <osgViewer/Renderer>
10 #include <osgViewer/Viewer>
11 #include <osgViewer/ViewerEventHandlers>
12 #include <osgGA/KeySwitchMatrixManipulator>
13 #include <osgGA/TrackballManipulator>
14 #include <osgGA/FlightManipulator>
15 #include <osgGA/DriveManipulator>
16 #include <osgGA/TerrainManipulator>
17 #include <osgGA/StateSetManipulator>
18
19 #include <simgear/props/props.hxx>
20 #include <simgear/props/props_io.hxx>
21 #include <simgear/misc/sg_path.hxx>
22 #include <simgear/scene/material/EffectCullVisitor.hxx>
23 #include <simgear/scene/material/matlib.hxx>
24 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
25 #include <simgear/scene/tgdb/userdata.hxx>
26 #include <simgear/scene/tgdb/TileEntry.hxx>
27 #include <simgear/scene/model/ModelRegistry.hxx>
28 #include <simgear/scene/model/modellib.hxx>
29
30 #include <Scenery/scenery.hxx>
31
32 #include "fg_init.hxx"
33 #include "fg_props.hxx"
34 #include "globals.hxx"
35 #include "options.hxx"
36
37 class DummyLoadHelper : public simgear::ModelLoadHelper {
38 public:
39     virtual osg::Node *loadTileModel(const string& modelPath, bool)
40     {
41         try {
42             SGSharedPtr<SGPropertyNode> prop = new SGPropertyNode;
43             return simgear::SGModelLib::loadModel(modelPath, prop);
44         } catch (...) {
45             std::cerr << "Error loading \"" << modelPath << "\"" << std::endl;
46             return 0;
47         }
48     }
49 };
50
51 class GraphDumpHandler : public  osgGA::GUIEventHandler
52 {
53 public:
54     GraphDumpHandler() : _keyDump('d') {}
55     void setKeyDump(int key) { _keyDump = key; }
56     int getKeyDump() const { return _keyDump; }
57     bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
58
59     /** Get the keyboard and mouse usage of this manipulator.*/
60     virtual void getUsage(osg::ApplicationUsage& usage) const;
61 protected:
62     int _keyDump;
63 };
64
65 static void dumpOut(osg::Node* node)
66 {
67     char filename[24];
68     static int count = 1;
69
70     FGRenderer *renderer = globals->get_renderer();
71
72     while (count < 1000) {
73         FILE *fp;
74         snprintf(filename, 24, "fgviewer-%03d.osg", count++);
75         if ( (fp = fopen(filename, "r")) == NULL )
76             break;
77         fclose(fp);
78     }
79
80     if (osgDB::writeNodeFile(*node, filename))
81         std::cerr << "Entire scene graph saved to \"" << filename << "\".\n";
82     else
83         std::cerr << "Failed to save to \"" << filename << "\".\n";
84 }
85
86 bool GraphDumpHandler::handle(const osgGA::GUIEventAdapter& ea,
87                               osgGA::GUIActionAdapter& aa)
88 {
89     osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
90     if (!view)
91         return false;
92     if (ea.getHandled())
93         return false;
94     switch(ea.getEventType()) {
95     case osgGA::GUIEventAdapter::KEYUP:
96         if (ea.getKey() == _keyDump) {
97             dumpOut(view->getScene()->getSceneData());
98             return true;
99         }
100         break;
101     default:
102         return false;
103     }
104 }
105
106 void GraphDumpHandler::getUsage(osg::ApplicationUsage& usage) const
107 {
108     std::ostringstream ostr;
109     ostr << char(_keyDump);
110             usage.addKeyboardMouseBinding(ostr.str(),
111                                           "Dump scene graph to file");
112 }
113
114 int
115 fgviewerMain(int argc, char** argv)
116 {
117
118     sgUserDataInit(0);
119     DummyLoadHelper dummyLoadHelper;
120     simgear::TileEntry::setModelLoadHelper(&dummyLoadHelper);
121
122     // use an ArgumentParser object to manage the program arguments.
123     osg::ArgumentParser arguments(&argc, argv);
124
125     // construct the viewer.
126     osgViewer::Viewer viewer(arguments);
127     osg::Camera* camera = viewer.getCamera();
128     osgViewer::Renderer* renderer
129         = static_cast<osgViewer::Renderer*>(camera->getRenderer());
130     for (int i = 0; i < 2; ++i) {
131         osgUtil::SceneView* sceneView = renderer->getSceneView(i);
132         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
133     }
134     // Shaders expect valid fog
135     osg::StateSet* cameraSS = camera->getOrCreateStateSet();
136     osg::Fog* fog = new osg::Fog;
137     fog->setMode(osg::Fog::EXP2);
138     fog->setColor(osg::Vec4(1.0, 1.0, 1.0, 1.0));
139     fog->setDensity(.0000001);
140     cameraSS->setAttributeAndModes(fog);
141     // ... for some reason, get rid of that FIXME!
142     viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
143
144     // set up the camera manipulators.
145     osgGA::KeySwitchMatrixManipulator* keyswitchManipulator;
146     keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
147
148     osgGA::MatrixManipulator* mm = new osgGA::TrackballManipulator;
149     keyswitchManipulator->addMatrixManipulator('1', "Trackball", mm);
150     mm = new osgGA::FlightManipulator;
151     keyswitchManipulator->addMatrixManipulator('2', "Flight", mm);
152     mm = new osgGA::DriveManipulator;
153     keyswitchManipulator->addMatrixManipulator('3', "Drive", mm);
154     mm = new osgGA::TerrainManipulator;
155     keyswitchManipulator->addMatrixManipulator('4', "Terrain", mm);
156
157     viewer.setCameraManipulator(keyswitchManipulator);
158
159     // Usefull stats
160     viewer.addEventHandler(new osgViewer::HelpHandler);
161     viewer.addEventHandler(new osgViewer::StatsHandler);
162     viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
163     // Same FIXME ...
164     // viewer.addEventHandler(new osgViewer::ThreadingHandler);
165     viewer.addEventHandler(new osgViewer::LODScaleHandler);
166     viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);
167
168     viewer.addEventHandler(new GraphDumpHandler);
169
170     // Extract files to load from arguments now; this way fgInitConfig
171     // won't choke on them.
172     string_list dataFiles;
173     for (int i = arguments.argc() - 1; i >= 0; --i) {
174         if (arguments.isOption(i)) {
175             break;
176         } else {
177             dataFiles.insert(dataFiles.begin(), arguments[i]);
178             arguments.remove(i);
179         }
180     }
181
182     // A subset of full flightgear initialization.
183     // Allocate global data structures.  This needs to happen before
184     // we parse command line options
185
186     globals = new FGGlobals;
187
188     fgInitFGRoot(arguments.argc(), arguments.argv());
189     if ( !fgInitConfig(arguments.argc(), arguments.argv()) ) {
190         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
191         exit(-1);
192     }
193
194     osgDB::FilePathList filePathList
195         = osgDB::Registry::instance()->getDataFilePathList();
196     filePathList.push_back(globals->get_fg_root());
197
198     string_list path_list = globals->get_fg_scenery();
199     for (unsigned i = 0; i < path_list.size(); ++i) {
200         filePathList.push_back(path_list[i]);
201     }
202
203     globals->set_matlib( new SGMaterialLib );
204     simgear::SGModelLib::init(globals->get_fg_root());
205
206     // Initialize the material property subsystem.
207
208     SGPath mpath( globals->get_fg_root() );
209     mpath.append( "materials.xml" );
210     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
211             globals->get_props()) ) {
212         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
213         exit(-1);
214     }
215
216     globals->set_scenery( new FGScenery );
217     globals->get_scenery()->init();
218     globals->get_scenery()->bind();
219
220     // The file path list must be set in the registry.
221     osgDB::Registry::instance()->getDataFilePathList() = filePathList;
222
223     SGReaderWriterBTGOptions* btgOptions = new SGReaderWriterBTGOptions;
224     btgOptions->getDatabasePathList() = filePathList;
225     btgOptions->setMatlib(globals->get_matlib());
226
227     // read the scene from the list of file specified command line args.
228     osg::ref_ptr<osg::Node> loadedModel;
229     loadedModel = osgDB::readNodeFiles(dataFiles, btgOptions);
230
231     // if no model has been successfully loaded report failure.
232     if (!loadedModel.valid()) {
233         std::cerr << arguments.getApplicationName()
234                   << ": No data loaded" << std::endl;
235         return EXIT_FAILURE;
236     }
237
238     // pass the loaded scene graph to the viewer.
239     viewer.setSceneData(loadedModel.get());
240
241     return viewer.run();
242 }