1 // Copyright (C) 2007 Tim Moore timoore@redhat.com
2 // Copyright (C) 2008 Till Busch buti@bux.at
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License as
6 // published by the Free Software Foundation; either version 2 of the
7 // License, or (at your option) any later version.
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 # include <simgear_config.h>
28 #include <boost/bind.hpp>
31 #include <osg/MatrixTransform>
32 #include <osgDB/ReadFile>
33 #include <osgDB/WriteFile>
34 #include <osgDB/Registry>
36 #include <osgDB/FileNameUtils>
38 #include <simgear/compiler.h>
39 #include <simgear/structure/exception.hxx>
40 #include <simgear/props/props.hxx>
41 #include <simgear/props/props_io.hxx>
42 #include <simgear/props/condition.hxx>
43 #include <simgear/scene/util/SGNodeMasks.hxx>
44 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
46 #include "modellib.hxx"
47 #include "SGReaderWriterXML.hxx"
49 #include "animation.hxx"
50 #include "particles.hxx"
53 #include "SGMaterialAnimation.hxx"
56 using namespace simgear;
60 sgLoad3DModel_internal(const SGPath& path,
61 const osgDB::Options* options,
62 SGPropertyNode *overlay = 0);
65 SGReaderWriterXML::SGReaderWriterXML()
67 supportsExtension("xml", "SimGear xml database format");
70 SGReaderWriterXML::~SGReaderWriterXML()
74 const char* SGReaderWriterXML::className() const
76 return "XML database reader";
79 osgDB::ReaderWriter::ReadResult
80 SGReaderWriterXML::readNode(const std::string& name,
81 const osgDB::Options* options) const
83 std::string fileName = osgDB::findDataFile(name, options);
87 SGPath p = SGModelLib::findDataFile(fileName);
89 return ReadResult::FILE_NOT_FOUND;
92 result=sgLoad3DModel_internal(p, options);
93 } catch (const sg_exception &t) {
94 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load model: " << t.getFormattedMessage()
95 << "\n\tfrom:" << fileName);
101 return ReadResult::FILE_NOT_HANDLED;
104 class SGSwitchUpdateCallback : public osg::NodeCallback
107 SGSwitchUpdateCallback(SGCondition* condition) :
108 mCondition(condition) {}
109 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) {
110 assert(dynamic_cast<osg::Switch*>(node));
111 osg::Switch* s = static_cast<osg::Switch*>(node);
113 if (mCondition && mCondition->test()) {
114 s->setAllChildrenOn();
115 // note, callback is responsible for scenegraph traversal so
116 // should always include call traverse(node,nv) to ensure
117 // that the rest of cullbacks and the scene graph are traversed.
120 s->setAllChildrenOff();
124 SGSharedPtr<SGCondition> mCondition;
128 // Little helper class that holds an extra reference to a
130 // Since we clone all structural nodes from our 3d models,
131 // the database pager will only see one single reference to
132 // top node of the model and expire it relatively fast.
133 // We attach that extra reference to every model cloned from
134 // a base model in the pager. When that cloned model is deleted
135 // this extra reference is deleted too. So if there are no
136 // cloned models left the model will expire.
138 class SGDatabaseReference : public osg::Observer
141 SGDatabaseReference(osg::Referenced* referenced) :
142 mReferenced(referenced)
144 virtual void objectDeleted(void*)
149 osg::ref_ptr<osg::Referenced> mReferenced;
152 void makeEffectAnimations(PropertyList& animation_nodes,
153 PropertyList& effect_nodes)
155 for (PropertyList::iterator itr = animation_nodes.begin();
156 itr != animation_nodes.end();
158 SGPropertyNode_ptr effectProp;
159 SGPropertyNode* animProp = itr->ptr();
160 SGPropertyNode* typeProp = animProp->getChild("type");
163 const char* typeString = typeProp->getStringValue();
164 if (!strcmp(typeString, "material")) {
166 = SGMaterialAnimation::makeEffectProperties(animProp);
167 } else if (!strcmp(typeString, "shader")) {
169 SGPropertyNode* shaderProp = animProp->getChild("shader");
170 if (!shaderProp || strcmp(shaderProp->getStringValue(), "chrome"))
172 *itr = 0; // effect replaces animation
173 SGPropertyNode* textureProp = animProp->getChild("texture");
176 effectProp = new SGPropertyNode();
177 makeChild(effectProp.ptr(), "inherits-from")
178 ->setValue("Effects/chrome");
179 SGPropertyNode* paramsProp = makeChild(effectProp.get(), "parameters");
180 makeChild(paramsProp, "chrome-texture")
181 ->setValue(textureProp->getStringValue());
183 if (effectProp.valid()) {
184 PropertyList objectNameNodes = animProp->getChildren("object-name");
185 for (PropertyList::iterator objItr = objectNameNodes.begin(),
186 end = objectNameNodes.end();
189 effectProp->addChild("object-name")
190 ->setStringValue((*objItr)->getStringValue());
191 effect_nodes.push_back(effectProp);
195 animation_nodes.erase(remove_if(animation_nodes.begin(),
196 animation_nodes.end(),
197 !boost::bind(&SGPropertyNode_ptr::valid,
199 animation_nodes.end());
204 class SetNodeMaskVisitor : public osg::NodeVisitor {
206 SetNodeMaskVisitor(osg::Node::NodeMask nms, osg::Node::NodeMask nmc) :
207 osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), nodeMaskSet(nms), nodeMaskClear(nmc)
209 virtual void apply(osg::Geode& node) {
210 node.setNodeMask((node.getNodeMask() | nodeMaskSet) & ~nodeMaskClear);
214 osg::Node::NodeMask nodeMaskSet;
215 osg::Node::NodeMask nodeMaskClear;
220 sgLoad3DModel_internal(const SGPath& path,
221 const osgDB::Options* dbOptions,
222 SGPropertyNode *overlay)
224 if (!path.exists()) {
225 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << path.str() << "\"");
229 osg::ref_ptr<SGReaderWriterOptions> options;
230 options = SGReaderWriterOptions::copyOrCreate(dbOptions);
232 SGPath modelpath(path);
233 SGPath texturepath(path);
234 SGPath modelDir(modelpath.dir());
236 SGSharedPtr<SGPropertyNode> prop_root = options->getPropertyNode();
237 if (!prop_root.valid())
238 prop_root = new SGPropertyNode;
239 // The model data appear to be only used in the topmost model
240 osg::ref_ptr<SGModelData> data = options->getModelData();
241 options->setModelData(0);
243 osg::ref_ptr<osg::Node> model;
244 osg::ref_ptr<osg::Group> group;
245 SGPropertyNode_ptr props = new SGPropertyNode;
247 // Check for an XML wrapper
248 if (modelpath.extension() == "xml") {
250 readProperties(modelpath.str(), props);
251 } catch (const sg_exception &t) {
252 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load xml: "
253 << t.getFormattedMessage());
257 copyProperties(overlay, props);
259 if (props->hasValue("/path")) {
260 string modelPathStr = props->getStringValue("/path");
261 modelpath = SGModelLib::findDataFile(modelPathStr, NULL, modelDir);
262 if (modelpath.isNull())
263 throw sg_io_exception("Model file not found: '" + modelPathStr + "'",
266 if (props->hasValue("/texture-path")) {
267 string texturePathStr = props->getStringValue("/texture-path");
268 if (!texturePathStr.empty())
270 texturepath = SGModelLib::findDataFile(texturePathStr, NULL, modelDir);
271 if (texturepath.isNull())
272 throw sg_io_exception("Texture file not found: '" + texturePathStr + "'",
277 model = new osg::Node;
280 SGPropertyNode *mp = props->getNode("multiplay");
281 if (mp && prop_root && prop_root->getParent())
282 copyProperties(mp, prop_root);
284 // model without wrapper
287 // Assume that textures are in
288 // the same location as the XML file.
290 if (!texturepath.extension().empty())
291 texturepath = texturepath.dir();
293 options->setDatabasePath(texturepath.str());
294 osgDB::ReaderWriter::ReadResult modelResult;
295 modelResult = osgDB::readNodeFile(modelpath.str(), options.get());
296 if (!modelResult.validNode())
297 throw sg_io_exception("Failed to load 3D model:" + modelResult.message(),
299 model = copyModel(modelResult.getNode());
300 // Add an extra reference to the model stored in the database.
301 // That is to avoid expiring the object from the cache even if
302 // it is still in use. Note that the object cache will think
303 // that a model is unused if the reference count is 1. If we
304 // clone all structural nodes here we need that extra
305 // reference to the original object
306 SGDatabaseReference* databaseReference;
307 databaseReference = new SGDatabaseReference(modelResult.getNode());
308 model->addObserver(databaseReference);
311 TextureUpdateVisitor liveryUpdate(options->getDatabasePathList());
312 model->accept(liveryUpdate);
314 // Copy the userdata fields, still sharing the boundingvolumes,
315 // but introducing new data for velocities.
316 UserDataCopyVisitor userDataCopyVisitor;
317 model->accept(userDataCopyVisitor);
319 SetNodeMaskVisitor setNodeMaskVisitor(0, simgear::MODELLIGHT_BIT);
320 model->accept(setNodeMaskVisitor);
322 model->setName(modelpath.str());
324 bool needTransform=false;
325 // Set up the alignment node if needed
326 SGPropertyNode *offsets = props->getNode("offsets", false);
329 osg::MatrixTransform *alignmainmodel = new osg::MatrixTransform;
330 alignmainmodel->setDataVariance(osg::Object::STATIC);
331 osg::Matrix res_matrix;
332 res_matrix.makeRotate(
333 offsets->getFloatValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
335 offsets->getFloatValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
337 offsets->getFloatValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
341 tmat.makeTranslate(offsets->getFloatValue("x-m", 0.0),
342 offsets->getFloatValue("y-m", 0.0),
343 offsets->getFloatValue("z-m", 0.0));
344 alignmainmodel->setMatrix(res_matrix*tmat);
345 group = alignmainmodel;
348 group = new osg::Group;
350 group->addChild(model.get());
353 vector<SGPropertyNode_ptr> model_nodes = props->getChildren("model");
354 for (unsigned i = 0; i < model_nodes.size(); i++) {
355 SGPropertyNode_ptr sub_props = model_nodes[i];
358 osg::ref_ptr<osg::Node> submodel;
360 string subPathStr = sub_props->getStringValue("path");
361 SGPath submodelPath = SGModelLib::findDataFile(subPathStr,
364 if (submodelPath.isNull()) {
365 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << subPathStr << "\"");
370 submodel = sgLoad3DModel_internal(submodelPath, options.get(),
371 sub_props->getNode("overlay"));
372 } catch (const sg_exception &t) {
373 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage()
374 << "\n\tfrom:" << t.getOrigin());
378 osg::ref_ptr<osg::Node> submodel_final = submodel;
379 SGPropertyNode *offs = sub_props->getNode("offsets", false);
381 osg::Matrix res_matrix;
382 osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
383 align->setDataVariance(osg::Object::STATIC);
384 res_matrix.makeIdentity();
385 res_matrix.makeRotate(
386 offs->getDoubleValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
388 offs->getDoubleValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
390 offs->getDoubleValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
395 tmat.makeTranslate(offs->getDoubleValue("x-m", 0),
396 offs->getDoubleValue("y-m", 0),
397 offs->getDoubleValue("z-m", 0));
398 align->setMatrix(res_matrix*tmat);
399 align->addChild(submodel.get());
400 submodel_final = align;
402 submodel_final->setName(sub_props->getStringValue("name", ""));
404 SGPropertyNode *cond = sub_props->getNode("condition", false);
406 osg::ref_ptr<osg::Switch> sw = new osg::Switch;
407 sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
408 group->addChild(sw.get());
409 sw->addChild(submodel_final.get());
410 sw->setName("submodel condition switch");
412 group->addChild(submodel_final.get());
414 } // end of submodel loading
416 osg::Node *(*load_panel)(SGPropertyNode *) = options->getLoadPanel();
419 vector<SGPropertyNode_ptr> panel_nodes = props->getChildren("panel");
420 for (unsigned i = 0; i < panel_nodes.size(); i++) {
421 SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
422 osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
423 if (panel_nodes[i]->hasValue("name"))
424 panel->setName(panel_nodes[i]->getStringValue("name"));
425 group->addChild(panel.get());
429 if (dbOptions->getPluginStringData("SimGear::PARTICLESYSTEM") != "OFF") {
430 std::vector<SGPropertyNode_ptr> particle_nodes;
431 particle_nodes = props->getChildren("particlesystem");
432 for (unsigned i = 0; i < particle_nodes.size(); ++i) {
433 osg::ref_ptr<SGReaderWriterOptions> options2;
434 options2 = new SGReaderWriterOptions(*options);
436 if (!texturepath.extension().empty())
437 texturepath = texturepath.dir();
439 options2->setDatabasePath(texturepath.str());
441 group->addChild(Particles::appendParticles(particle_nodes[i],
447 std::vector<SGPropertyNode_ptr> text_nodes;
448 text_nodes = props->getChildren("text");
449 for (unsigned i = 0; i < text_nodes.size(); ++i) {
450 group->addChild(SGText::appendText(text_nodes[i],
455 PropertyList effect_nodes = props->getChildren("effect");
456 PropertyList animation_nodes = props->getChildren("animation");
457 // Some material animations (eventually all) are actually effects.
458 makeEffectAnimations(animation_nodes, effect_nodes);
460 ref_ptr<Node> modelWithEffects
461 = instantiateEffects(group.get(), effect_nodes, options.get());
462 group = static_cast<Group*>(modelWithEffects.get());
465 for (unsigned i = 0; i < animation_nodes.size(); ++i)
466 /// OSGFIXME: duh, why not only model?????
467 SGAnimation::animate(group.get(), animation_nodes[i], prop_root,
468 options.get(), path.str(), i);
470 if (!needTransform && group->getNumChildren() < 2) {
471 model = group->getChild(0);
472 group->removeChild(model.get());
474 data->modelLoaded(modelpath.str(), props, model.get());
475 return model.release();
478 data->modelLoaded(modelpath.str(), props, group.get());
479 if (props->hasChild("debug-outfile")) {
480 std::string outputfile = props->getStringValue("debug-outfile",
482 osgDB::writeNodeFile(*group, outputfile);
485 return group.release();