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& fileName,
81 const osgDB::Options* options) const
85 SGPath p = SGModelLib::findDataFile(fileName);
87 return ReadResult::FILE_NOT_FOUND;
90 result=sgLoad3DModel_internal(p, options);
91 } catch (const sg_exception &t) {
92 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load model: " << t.getFormattedMessage()
93 << "\n\tfrom:" << fileName);
99 return ReadResult::FILE_NOT_HANDLED;
102 class SGSwitchUpdateCallback : public osg::NodeCallback
105 SGSwitchUpdateCallback(SGCondition* condition) :
106 mCondition(condition) {}
107 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) {
108 assert(dynamic_cast<osg::Switch*>(node));
109 osg::Switch* s = static_cast<osg::Switch*>(node);
111 if (mCondition && mCondition->test()) {
112 s->setAllChildrenOn();
113 // note, callback is responsible for scenegraph traversal so
114 // should always include call traverse(node,nv) to ensure
115 // that the rest of cullbacks and the scene graph are traversed.
118 s->setAllChildrenOff();
122 SGSharedPtr<SGCondition> mCondition;
126 // Little helper class that holds an extra reference to a
128 // Since we clone all structural nodes from our 3d models,
129 // the database pager will only see one single reference to
130 // top node of the model and expire it relatively fast.
131 // We attach that extra reference to every model cloned from
132 // a base model in the pager. When that cloned model is deleted
133 // this extra reference is deleted too. So if there are no
134 // cloned models left the model will expire.
136 class SGDatabaseReference : public osg::Observer
139 SGDatabaseReference(osg::Referenced* referenced) :
140 mReferenced(referenced)
142 virtual void objectDeleted(void*)
147 osg::ref_ptr<osg::Referenced> mReferenced;
150 void makeEffectAnimations(PropertyList& animation_nodes,
151 PropertyList& effect_nodes)
153 for (PropertyList::iterator itr = animation_nodes.begin();
154 itr != animation_nodes.end();
156 SGPropertyNode_ptr effectProp;
157 SGPropertyNode* animProp = itr->ptr();
158 SGPropertyNode* typeProp = animProp->getChild("type");
161 const char* typeString = typeProp->getStringValue();
162 if (!strcmp(typeString, "material")) {
164 = SGMaterialAnimation::makeEffectProperties(animProp);
165 } else if (!strcmp(typeString, "shader")) {
167 SGPropertyNode* shaderProp = animProp->getChild("shader");
168 if (!shaderProp || strcmp(shaderProp->getStringValue(), "chrome"))
170 *itr = 0; // effect replaces animation
171 SGPropertyNode* textureProp = animProp->getChild("texture");
174 effectProp = new SGPropertyNode();
175 makeChild(effectProp.ptr(), "inherits-from")
176 ->setValue("Effects/chrome");
177 SGPropertyNode* paramsProp = makeChild(effectProp.get(), "parameters");
178 makeChild(paramsProp, "chrome-texture")
179 ->setValue(textureProp->getStringValue());
181 if (effectProp.valid()) {
182 PropertyList objectNameNodes = animProp->getChildren("object-name");
183 for (PropertyList::iterator objItr = objectNameNodes.begin(),
184 end = objectNameNodes.end();
187 effectProp->addChild("object-name")
188 ->setStringValue((*objItr)->getStringValue());
189 effect_nodes.push_back(effectProp);
193 animation_nodes.erase(remove_if(animation_nodes.begin(),
194 animation_nodes.end(),
195 !boost::bind(&SGPropertyNode_ptr::valid,
197 animation_nodes.end());
202 sgLoad3DModel_internal(const SGPath& path,
203 const osgDB::Options* dbOptions,
204 SGPropertyNode *overlay)
206 if (!path.exists()) {
207 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << path.str() << "\"");
211 osg::ref_ptr<SGReaderWriterOptions> options;
212 options = SGReaderWriterOptions::copyOrCreate(dbOptions);
214 SGPath modelpath(path);
215 SGPath texturepath(path);
216 SGPath modelDir(modelpath.dir());
218 SGSharedPtr<SGPropertyNode> prop_root = options->getPropertyNode();
219 if (!prop_root.valid())
220 prop_root = new SGPropertyNode;
221 // The model data appear to be only used in the topmost model
222 osg::ref_ptr<SGModelData> data = options->getModelData();
223 options->setModelData(0);
225 osg::ref_ptr<osg::Node> model;
226 osg::ref_ptr<osg::Group> group;
227 SGPropertyNode_ptr props = new SGPropertyNode;
229 // Check for an XML wrapper
230 if (modelpath.extension() == "xml") {
232 readProperties(modelpath.str(), props);
233 } catch (const sg_exception &t) {
234 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load xml: "
235 << t.getFormattedMessage());
239 copyProperties(overlay, props);
241 if (props->hasValue("/path")) {
242 string modelPathStr = props->getStringValue("/path");
243 modelpath = SGModelLib::findDataFile(modelPathStr, NULL, modelDir);
244 if (modelpath.isNull())
245 throw sg_io_exception("Model file not found: '" + modelPathStr + "'",
248 if (props->hasValue("/texture-path")) {
249 string texturePathStr = props->getStringValue("/texture-path");
250 texturepath = SGModelLib::findDataFile(texturePathStr, NULL, modelDir);
251 if (texturepath.isNull())
252 throw sg_io_exception("Texture file not found: '" + texturePathStr + "'",
256 model = new osg::Node;
259 SGPropertyNode *mp = props->getNode("multiplay");
260 if (mp && prop_root && prop_root->getParent())
261 copyProperties(mp, prop_root);
263 // model without wrapper
266 // Assume that textures are in
267 // the same location as the XML file.
269 if (!texturepath.extension().empty())
270 texturepath = texturepath.dir();
272 options->setDatabasePath(texturepath.str());
273 osgDB::ReaderWriter::ReadResult modelResult;
274 modelResult = osgDB::readNodeFile(modelpath.str(), options.get());
275 if (!modelResult.validNode())
276 throw sg_io_exception("Failed to load 3D model:" + modelResult.message(),
278 model = copyModel(modelResult.getNode());
279 // Add an extra reference to the model stored in the database.
280 // That is to avoid expiring the object from the cache even if
281 // it is still in use. Note that the object cache will think
282 // that a model is unused if the reference count is 1. If we
283 // clone all structural nodes here we need that extra
284 // reference to the original object
285 SGDatabaseReference* databaseReference;
286 databaseReference = new SGDatabaseReference(modelResult.getNode());
287 model->addObserver(databaseReference);
290 TextureUpdateVisitor liveryUpdate(options->getDatabasePathList());
291 model->accept(liveryUpdate);
293 // Copy the userdata fields, still sharing the boundingvolumes,
294 // but introducing new data for velocities.
295 UserDataCopyVisitor userDataCopyVisitor;
296 model->accept(userDataCopyVisitor);
298 model->setName(modelpath.str());
300 bool needTransform=false;
301 // Set up the alignment node if needed
302 SGPropertyNode *offsets = props->getNode("offsets", false);
305 osg::MatrixTransform *alignmainmodel = new osg::MatrixTransform;
306 alignmainmodel->setDataVariance(osg::Object::STATIC);
307 osg::Matrix res_matrix;
308 res_matrix.makeRotate(
309 offsets->getFloatValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
311 offsets->getFloatValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
313 offsets->getFloatValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
317 tmat.makeTranslate(offsets->getFloatValue("x-m", 0.0),
318 offsets->getFloatValue("y-m", 0.0),
319 offsets->getFloatValue("z-m", 0.0));
320 alignmainmodel->setMatrix(res_matrix*tmat);
321 group = alignmainmodel;
324 group = new osg::Group;
326 group->addChild(model.get());
329 vector<SGPropertyNode_ptr> model_nodes = props->getChildren("model");
330 for (unsigned i = 0; i < model_nodes.size(); i++) {
331 SGPropertyNode_ptr sub_props = model_nodes[i];
334 osg::ref_ptr<osg::Node> submodel;
336 string subPathStr = sub_props->getStringValue("path");
337 SGPath submodelPath = SGModelLib::findDataFile(subPathStr,
340 if (submodelPath.isNull()) {
341 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << subPathStr << "\"");
346 submodel = sgLoad3DModel_internal(submodelPath, options.get(),
347 sub_props->getNode("overlay"));
348 } catch (const sg_exception &t) {
349 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage()
350 << "\n\tfrom:" << t.getOrigin());
354 osg::ref_ptr<osg::Node> submodel_final = submodel;
355 SGPropertyNode *offs = sub_props->getNode("offsets", false);
357 osg::Matrix res_matrix;
358 osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
359 align->setDataVariance(osg::Object::STATIC);
360 res_matrix.makeIdentity();
361 res_matrix.makeRotate(
362 offs->getDoubleValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
364 offs->getDoubleValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
366 offs->getDoubleValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
371 tmat.makeTranslate(offs->getDoubleValue("x-m", 0),
372 offs->getDoubleValue("y-m", 0),
373 offs->getDoubleValue("z-m", 0));
374 align->setMatrix(res_matrix*tmat);
375 align->addChild(submodel.get());
376 submodel_final = align;
378 submodel_final->setName(sub_props->getStringValue("name", ""));
380 SGPropertyNode *cond = sub_props->getNode("condition", false);
382 osg::ref_ptr<osg::Switch> sw = new osg::Switch;
383 sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
384 group->addChild(sw.get());
385 sw->addChild(submodel_final.get());
386 sw->setName("submodel condition switch");
388 group->addChild(submodel_final.get());
390 } // end of submodel loading
392 osg::Node *(*load_panel)(SGPropertyNode *) = options->getLoadPanel();
395 vector<SGPropertyNode_ptr> panel_nodes = props->getChildren("panel");
396 for (unsigned i = 0; i < panel_nodes.size(); i++) {
397 SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
398 osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
399 if (panel_nodes[i]->hasValue("name"))
400 panel->setName(panel_nodes[i]->getStringValue("name"));
401 group->addChild(panel.get());
405 if (dbOptions->getPluginStringData("SimGear::PARTICLESYSTEM") != "OFF") {
406 std::vector<SGPropertyNode_ptr> particle_nodes;
407 particle_nodes = props->getChildren("particlesystem");
408 for (unsigned i = 0; i < particle_nodes.size(); ++i) {
409 osg::ref_ptr<SGReaderWriterOptions> options2;
410 options2 = new SGReaderWriterOptions(*options);
412 if (!texturepath.extension().empty())
413 texturepath = texturepath.dir();
415 options2->setDatabasePath(texturepath.str());
417 group->addChild(Particles::appendParticles(particle_nodes[i],
423 std::vector<SGPropertyNode_ptr> text_nodes;
424 text_nodes = props->getChildren("text");
425 for (unsigned i = 0; i < text_nodes.size(); ++i) {
426 group->addChild(SGText::appendText(text_nodes[i],
430 PropertyList effect_nodes = props->getChildren("effect");
431 PropertyList animation_nodes = props->getChildren("animation");
432 PropertyList light_nodes = props->getChildren("light");
433 // Some material animations (eventually all) are actually effects.
434 makeEffectAnimations(animation_nodes, effect_nodes);
436 ref_ptr<Node> modelWithEffects
437 = instantiateEffects(group.get(), effect_nodes, options.get());
438 group = static_cast<Group*>(modelWithEffects.get());
440 for (unsigned i = 0; i < animation_nodes.size(); ++i)
441 /// OSGFIXME: duh, why not only model?????
442 SGAnimation::animate(group.get(), animation_nodes[i], prop_root,
443 options.get(), path.str(), i);
445 if (!needTransform && group->getNumChildren() < 2) {
446 model = group->getChild(0);
447 group->removeChild(model.get());
449 data->modelLoaded(modelpath.str(), props, model.get());
450 return model.release();
453 data->modelLoaded(modelpath.str(), props, group.get());
454 if (props->hasChild("debug-outfile")) {
455 std::string outputfile = props->getStringValue("debug-outfile",
457 osgDB::writeNodeFile(*group, outputfile);
460 return group.release();