Debian Codegraph @

src/Model/modelmgr.cxx

raw symbols SCIP
1 /*
2 * SPDX-FileName: modelmgr.cxx
3 * SPDX-FileComment: manage a collection of 3D models
4 * SPDX-FileCopyrightText: Written by David Megginson, started 2002.
5 * SPDX-License-Identifier: This file is in the Public Domain, and comes with no warranty.
6 */
7
8 #ifdef _MSC_VER
9 # pragma warning( disable: 4355 )
10 #endif
11
12 #ifdef HAVE_CONFIG_H
13 # include <config.h>
14 #endif
15
16 #include <simgear/compiler.h>
17
18 #include <algorithm>
19 #include <functional>
20 #include <vector>
21 #include <cstring>
22
23 #include <simgear/scene/model/placement.hxx>
24 #include <simgear/scene/model/modellib.hxx>
25 #include <simgear/structure/exception.hxx>
26
27 #include <Main/fg_props.hxx>
28 #include <Scenery/scenery.hxx>
29 #include <Scenery/marker.hxx>
30
31 #include <osg/ProxyNode>
32 #include <osgText/String>
33
34 #include "modelmgr.hxx"
35
36 using namespace simgear;
37
38 namespace {
39
40 class CheckInstanceModelLoadedVisitor : public osg::NodeVisitor
41 {
42 public:
43 CheckInstanceModelLoadedVisitor() :
44 osg::NodeVisitor(osg::NodeVisitor::NODE_VISITOR, osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
45 {}
46
47 ~CheckInstanceModelLoadedVisitor() = default;
48
49 void apply(osg::Node& node) override
50 {
51 if (!_loaded)
52 return;
53 traverse(node);
54 }
55
56 void apply(osg::ProxyNode& node) override
57 {
58 if (!_loaded)
59 return;
60
61 for (unsigned i = 0; i < node.getNumFileNames(); ++i) {
62 if (node.getFileName(i).empty())
63 continue;
64
65 // Check if this is already loaded.
66 if (i < node.getNumChildren() && node.getChild(i))
67 continue;
68
69 _loaded=false;
70 return;
71 }
72 traverse(node);
73 }
74
75 bool isLoaded() const
76 {
77 return _loaded;
78 }
79
80 private:
81 bool _loaded = true;
82 };
83
84 } // of anonymous namespace
85
86 FGModelMgr::FGModelMgr ()
87 {
88 }
89
90 FGModelMgr::~FGModelMgr ()
91 {
92 }
93
94 void
95 FGModelMgr::init ()
96 {
97 std::vector<SGPropertyNode_ptr> model_nodes = _models->getChildren("model");
98
99 for (unsigned int i = 0; i < model_nodes.size(); i++)
100 add_model(model_nodes[i]);
101 }
102
103 void FGModelMgr::shutdown()
104 {
105 osg::Group *scene_graph = NULL;
106 if (globals->get_scenery()) {
107 scene_graph = globals->get_scenery()->get_scene_graph();
108 }
109
110 // always delete instances, even if the scene-graph is gone
111 for (unsigned int i = 0; i < _instances.size(); i++) {
112 if (scene_graph) {
113 scene_graph->removeChild(_instances[i]->model->getSceneGraph());
114 }
115
116 delete _instances[i];
117 }
118 }
119
120 void
121 FGModelMgr::add_model (SGPropertyNode * node)
122 {
123 const std::string model_path{node->getStringValue("path", "Models/Geometry/glider.ac")};
124 if (model_path.empty()) {
125 SG_LOG(SG_AIRCRAFT, SG_WARN, "add_model called with empty path");
126 return;
127 }
128
129 const std::string internal_model{node->getStringValue("internal-model", "external")};
130
131 osg::ref_ptr<osg::Node> object;
132
133 Instance* instance = new Instance;
134 instance->loaded_node = node->addChild("loaded");
135 instance->loaded_node->setBoolValue(false);
136
137 if (internal_model == "marker") {
138 std::string label{node->getStringValue("marker/text", "MARKER")};
139 float r = node->getFloatValue("marker/color[0]", 1.0f);
140 float g = node->getFloatValue("marker/color[1]", 1.0f);
141 float b = node->getFloatValue("marker/color[2]", 1.0f);
142 osg::Vec4f color(r, g, b, 1.0f);
143 float font_size = node->getFloatValue("marker/size", 1.0f);
144 float pin_height = node->getFloatValue("marker/height", 1000.0f);
145 float tip_height = node->getFloatValue("marker/tip-height", 0.0f);
146 object = fgCreateMarkerNode(osgText::String(label, osgText::String::ENCODING_UTF8), font_size, pin_height, tip_height, color);
147 } else if (internal_model == "external") {
148 try {
149 std::string fullPath = simgear::SGModelLib::findDataFile(model_path);
150 if (fullPath.empty()) {
151 SG_LOG(SG_AIRCRAFT, SG_ALERT, "add_model: unable to find model with name '" << model_path << "'");
152 return;
153 }
154 object = SGModelLib::loadDeferredModel(fullPath, globals->get_props());
155 } catch (const sg_throwable& t) {
156 SG_LOG(SG_AIRCRAFT, SG_ALERT, "Error loading " << model_path << ":\n " << t.getFormattedMessage() << t.getOrigin());
157 return;
158 }
159 }
160 else {
161 object = new osg::Node;
162 SG_LOG(SG_AIRCRAFT, SG_WARN, "Unsupported internal-model type " << internal_model);
163 }
164
165 const std::string modelName{node->getStringValue("name", model_path.c_str())};
166 SG_LOG(SG_AIRCRAFT, SG_INFO, "Adding model " << modelName);
167
168 SGModelPlacement *model = new SGModelPlacement;
169 instance->model = model;
170 instance->node = node;
171
172 model->init( object );
173 double lon = node->getDoubleValue("longitude-deg"),
174 lat = node->getDoubleValue("latitude-deg"),
175 elevFt = node->getDoubleValue("elevation-ft");
176
177 model->setPosition(SGGeod::fromDegFt(lon, lat, elevFt));
178 // Set position and orientation either
179 // indirectly through property refs
180 // or directly with static values.
181 SGPropertyNode * child = node->getChild("longitude-deg-prop");
182 if (child != 0)
183 instance->lon_deg_node = fgGetNode(child->getStringValue(), true);
184
185 child = node->getChild("latitude-deg-prop");
186 if (child != 0)
187 instance->lat_deg_node = fgGetNode(child->getStringValue(), true);
188
189 child = node->getChild("elevation-ft-prop");
190 if (child != 0)
191 instance->elev_ft_node = fgGetNode(child->getStringValue(), true);
192
193 child = node->getChild("roll-deg-prop");
194 if (child != 0)
195 instance->roll_deg_node = fgGetNode(child->getStringValue(), true);
196 else
197 model->setRollDeg(node->getDoubleValue("roll-deg"));
198
199 child = node->getChild("pitch-deg-prop");
200 if (child != 0)
201 instance->pitch_deg_node = fgGetNode(child->getStringValue(), true);
202 else
203 model->setPitchDeg(node->getDoubleValue("pitch-deg"));
204
205 child = node->getChild("heading-deg-prop");
206 if (child != 0)
207 instance->heading_deg_node = fgGetNode(child->getStringValue(), true);
208 else
209 model->setHeadingDeg(node->getDoubleValue("heading-deg"));
210
211 if (node->hasChild("enable-hot")) {
212 osg::Node::NodeMask mask = model->getSceneGraph()->getNodeMask();
213 if (node->getBoolValue("enable-hot")) {
214 mask |= SG_NODEMASK_TERRAIN_BIT;
215 } else {
216 mask &= ~SG_NODEMASK_TERRAIN_BIT;
217 }
218 model->getSceneGraph()->setNodeMask(mask);
219 }
220
221 // Add this model to the global scene graph
222 globals->get_scenery()->get_scene_graph()->addChild(model->getSceneGraph());
223
224
225 // Save this instance for updating
226 add_instance(instance);
227 }
228
229 void
230 FGModelMgr::bind ()
231 {
232 _models = fgGetNode("/models", true);
233
234 _listener.reset(new Listener(this));
235 _models->addChangeListener(_listener.get());
236 }
237
238 void
239 FGModelMgr::unbind ()
240 {
241 // work-around for FLIGHTGEAR-37D : crash when quitting during
242 // early startup
243 if (_listener) {
244 _models->removeChangeListener(_listener.get());
245 }
246
247 _listener.reset();
248 _models.clear();
249 }
250
251 namespace
252 {
253 double testNan(double val)
254 {
255 if (SGMisc<double>::isNaN(val))
256 throw sg_range_exception("value is nan");
257
258 return val;
259 }
260 } // namespace
261
262 void FGModelMgr::update(double dt)
263 {
264 std::for_each(_instances.begin(), _instances.end(), [](FGModelMgr::Instance* instance) {
265 SGModelPlacement* model = instance->model;
266 double roll, pitch, heading;
267 roll = pitch = heading = 0.0;
268 SGGeod pos = model->getPosition();
269
270 try {
271 // Optionally set position from properties
272 if (instance->lon_deg_node != 0)
273 pos.setLongitudeDeg(testNan(instance->lon_deg_node->getDoubleValue()));
274 if (instance->lat_deg_node != 0)
275 pos.setLatitudeDeg(testNan(instance->lat_deg_node->getDoubleValue()));
276 if (instance->elev_ft_node != 0)
277 pos.setElevationFt(testNan(instance->elev_ft_node->getDoubleValue()));
278
279 // Optionally set orientation from properties
280 if (instance->roll_deg_node != 0)
281 roll = testNan(instance->roll_deg_node->getDoubleValue());
282 if (instance->pitch_deg_node != 0)
283 pitch = testNan(instance->pitch_deg_node->getDoubleValue());
284 if (instance->heading_deg_node != 0)
285 heading = testNan(instance->heading_deg_node->getDoubleValue());
286 } catch (const sg_range_exception&) {
287 std::string path = instance->node->getStringValue("path", "unknown");
288 SG_LOG(SG_AIRCRAFT, SG_INFO, "Instance of model " << path
289 << " has invalid values");
290 return;
291 }
292
293 model->setPosition(pos);
294 // Optionally set orientation from properties
295 if (instance->roll_deg_node != 0)
296 model->setRollDeg(roll);
297 if (instance->pitch_deg_node != 0)
298 model->setPitchDeg(pitch);
299 if (instance->heading_deg_node != 0)
300 model->setHeadingDeg(heading);
301
302 instance->model->update();
303 instance->checkLoaded();
304 });
305 }
306
307 void
308 FGModelMgr::add_instance (Instance * instance)
309 {
310 _instances.push_back(instance);
311 }
312
313 void
314 FGModelMgr::remove_instance (Instance * instance)
315 {
316 std::vector<Instance *>::iterator it;
317 for (it = _instances.begin(); it != _instances.end(); it++) {
318 if (*it == instance) {
319 _instances.erase(it);
320 delete instance;
321 return;
322 }
323 }
324 }
325
326 FGModelMgr::Instance*
327 FGModelMgr::findInstanceByNodePath(const std::string& node_path) const
328 {
329 if (node_path.empty())
330 return nullptr;
331
332 SGPropertyNode* node = fgGetNode(node_path, false);
333 if (!node)
334 return nullptr;
335
336 auto it = std::find_if(_instances.begin(), _instances.end(),
337 [node](const Instance* instance)
338 { return instance->node == node; });
339
340 if (it == _instances.end()) {
341 return nullptr;
342 }
343
344 return *it;
345 }
346
347 ////////////////////////////////////////////////////////////////////////
348 // Implementation of FGModelMgr::Instance
349 ////////////////////////////////////////////////////////////////////////
350
351 FGModelMgr::Instance::~Instance ()
352 {
353 delete model;
354 }
355
356 bool FGModelMgr::Instance::checkLoaded() const
357 {
358 if (!model)
359 return false;
360
361 if (loaded_node->getBoolValue()) {
362 return true;
363 }
364
365 CheckInstanceModelLoadedVisitor cilv;
366 model->getSceneGraph()->accept(cilv);
367 const bool loadedNow = cilv.isLoaded();
368
369 if (loadedNow) {
370 loaded_node->setBoolValue(true);
371 }
372 return loadedNow;
373 }
374
375 ////////////////////////////////////////////////////////////////////////
376 // Implementation of FGModelMgr::Listener
377 ////////////////////////////////////////////////////////////////////////
378
379 void
380 FGModelMgr::Listener::childAdded(SGPropertyNode * parent, SGPropertyNode * child)
381 {
382 if (parent->getNameString() != "model" || child->getNameString() != "load")
383 return;
384
385 _mgr->add_model(parent);
386 }
387
388 void
389 FGModelMgr::Listener::childRemoved(SGPropertyNode * parent, SGPropertyNode * child)
390 {
391 if (parent->getNameString() != "models" || child->getNameString() != "model")
392 return;
393
394 // search instance by node and remove it from scenegraph
395 std::vector<Instance *>::iterator it = _mgr->_instances.begin();
396 std::vector<Instance *>::iterator end = _mgr->_instances.end();
397
398 for (; it != end; ++it) {
399 Instance *instance = *it;
400 if (instance->node != child)
401 continue;
402
403 _mgr->_instances.erase(it);
404 osg::Node *branch = instance->model->getSceneGraph();
405 // OSGFIXME
406 // if (shadows && instance->shadow)
407 // shadows->deleteOccluder(branch);
408
409 if (globals->get_scenery() && globals->get_scenery()->get_scene_graph()) {
410 globals->get_scenery()->get_scene_graph()->removeChild(branch);
411 }
412
413 delete instance;
414 break;
415 }
416 }
417
418
419 // Register the subsystem.
420 SGSubsystemMgr::Registrant<FGModelMgr> registrantFGModelMgr(
421 SGSubsystemMgr::DISPLAY);
422
423 // end of modelmgr.cxx