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>
27 #include <boost/bind.hpp>
30 #include <osg/MatrixTransform>
31 #include <osgDB/WriteFile>
32 #include <osgDB/Registry>
34 #include <osgDB/FileNameUtils>
36 #include <simgear/compiler.h>
37 #include <simgear/structure/exception.hxx>
38 #include <simgear/props/props.hxx>
39 #include <simgear/props/props_io.hxx>
40 #include <simgear/props/condition.hxx>
41 #include <simgear/scene/util/SGNodeMasks.hxx>
43 #include "modellib.hxx"
44 #include "SGPagedLOD.hxx"
45 #include "SGReaderWriterXML.hxx"
46 #include "SGReaderWriterXMLOptions.hxx"
48 #include "animation.hxx"
49 #include "particles.hxx"
52 #include "SGMaterialAnimation.hxx"
55 using namespace simgear;
59 sgLoad3DModel_internal(const std::string& path,
60 const osgDB::ReaderWriter::Options* options,
61 SGPropertyNode *overlay = 0);
64 SGReaderWriterXML::SGReaderWriterXML()
66 supportsExtension("xml", "SimGear xml database format");
69 SGReaderWriterXML::~SGReaderWriterXML()
73 const char* SGReaderWriterXML::className() const
75 return "XML database reader";
78 osgDB::ReaderWriter::ReadResult
79 SGReaderWriterXML::readNode(const std::string& fileName,
80 const osgDB::ReaderWriter::Options* options) const
84 result=sgLoad3DModel_internal(fileName, options);
85 } catch (const sg_throwable &t) {
86 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load model: " << t.getFormattedMessage());
92 return ReadResult::FILE_NOT_HANDLED;
95 class SGSwitchUpdateCallback : public osg::NodeCallback
98 SGSwitchUpdateCallback(SGCondition* condition) :
99 mCondition(condition) {}
100 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) {
101 assert(dynamic_cast<osg::Switch*>(node));
102 osg::Switch* s = static_cast<osg::Switch*>(node);
104 if (mCondition && mCondition->test()) {
105 s->setAllChildrenOn();
106 // note, callback is responsible for scenegraph traversal so
107 // should always include call traverse(node,nv) to ensure
108 // that the rest of cullbacks and the scene graph are traversed.
111 s->setAllChildrenOff();
115 SGSharedPtr<SGCondition> mCondition;
119 // Little helper class that holds an extra reference to a
121 // Since we clone all structural nodes from our 3d models,
122 // the database pager will only see one single reference to
123 // top node of the model and expire it relatively fast.
124 // We attach that extra reference to every model cloned from
125 // a base model in the pager. When that cloned model is deleted
126 // this extra reference is deleted too. So if there are no
127 // cloned models left the model will expire.
129 class SGDatabaseReference : public osg::Observer
132 SGDatabaseReference(osg::Referenced* referenced) :
133 mReferenced(referenced)
135 virtual void objectDeleted(void*)
140 osg::ref_ptr<osg::Referenced> mReferenced;
143 void makeEffectAnimations(PropertyList& animation_nodes,
144 PropertyList& effect_nodes)
146 for (PropertyList::iterator itr = animation_nodes.begin();
147 itr != animation_nodes.end();
149 SGPropertyNode_ptr effectProp;
150 SGPropertyNode* animProp = itr->ptr();
151 SGPropertyNode* typeProp = animProp->getChild("type");
154 const char* typeString = typeProp->getStringValue();
155 if (!strcmp(typeString, "material")) {
157 = SGMaterialAnimation::makeEffectProperties(animProp);
158 } else if (!strcmp(typeString, "shader")) {
160 SGPropertyNode* shaderProp = animProp->getChild("shader");
161 if (!shaderProp || strcmp(shaderProp->getStringValue(), "chrome"))
163 *itr = 0; // effect replaces animation
164 SGPropertyNode* textureProp = animProp->getChild("texture");
167 effectProp = new SGPropertyNode();
168 makeChild(effectProp.ptr(), "inherits-from")
169 ->setValue("Effects/chrome");
170 SGPropertyNode* paramsProp = makeChild(effectProp.get(), "parameters");
171 makeChild(paramsProp, "chrome-texture")
172 ->setValue(textureProp->getStringValue());
174 if (effectProp.valid()) {
175 PropertyList objectNameNodes = animProp->getChildren("object-name");
176 for (PropertyList::iterator objItr = objectNameNodes.begin(),
177 end = objectNameNodes.end();
180 effectProp->addChild("object-name")
181 ->setStringValue((*objItr)->getStringValue());
182 effect_nodes.push_back(effectProp);
186 animation_nodes.erase(remove_if(animation_nodes.begin(),
187 animation_nodes.end(),
188 !boost::bind(&SGPropertyNode_ptr::valid,
190 animation_nodes.end());
195 sgLoad3DModel_internal(const string &path,
196 const osgDB::ReaderWriter::Options* options_,
197 SGPropertyNode *overlay)
199 const SGReaderWriterXMLOptions* xmlOptions;
200 xmlOptions = dynamic_cast<const SGReaderWriterXMLOptions*>(options_);
202 SGSharedPtr<SGPropertyNode> prop_root;
203 osg::Node *(*load_panel)(SGPropertyNode *)=0;
204 osg::ref_ptr<SGModelData> data;
207 prop_root = xmlOptions->getPropRoot();
208 load_panel = xmlOptions->getLoadPanel();
209 data = xmlOptions->getModelData();
212 prop_root = new SGPropertyNode;
215 osgDB::FilePathList filePathList;
216 filePathList = osgDB::Registry::instance()->getDataFilePathList();
217 filePathList.push_front(std::string());
219 SGPath modelpath = osgDB::findFileInPath(path, filePathList);
220 if (modelpath.str().empty()) {
221 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << path << "\"");
224 SGPath texturepath = modelpath;
226 osg::ref_ptr<osg::Node> model;
227 osg::ref_ptr<osg::Group> group;
228 SGPropertyNode_ptr props = new SGPropertyNode;
230 // Check for an XML wrapper
231 if (modelpath.extension() == "xml") {
233 readProperties(modelpath.str(), props);
234 } catch (const sg_throwable &t) {
235 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load xml: "
236 << t.getFormattedMessage());
240 copyProperties(overlay, props);
242 if (props->hasValue("/path")) {
243 modelpath = modelpath.dir();
244 modelpath.append(props->getStringValue("/path"));
245 if (props->hasValue("/texture-path")) {
246 texturepath = texturepath.dir();
247 texturepath.append(props->getStringValue("/texture-path"));
250 model = new osg::Node;
253 SGPropertyNode *mp = props->getNode("multiplay");
254 if (mp && prop_root && prop_root->getParent())
255 copyProperties(mp, prop_root);
257 SG_LOG(SG_INPUT, SG_DEBUG, "model without wrapper: "
261 osg::ref_ptr<SGReaderWriterXMLOptions> options
262 = new SGReaderWriterXMLOptions(*options_);
263 options->setPropRoot(prop_root);
264 options->setLoadPanel(load_panel);
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 = osgDB::Registry::instance()->readNode(modelpath.str(),
276 if (!modelResult.validNode())
277 throw sg_io_exception("Failed to load 3D model",
278 sg_location(modelpath.str()));
279 model = copyModel(modelResult.getNode());
280 // Add an extra reference to the model stored in the database.
281 // That is to avoid expiring the object from the cache even if
282 // it is still in use. Note that the object cache will think
283 // that a model is unused if the reference count is 1. If we
284 // clone all structural nodes here we need that extra
285 // reference to the original object
286 SGDatabaseReference* databaseReference;
287 databaseReference = new SGDatabaseReference(modelResult.getNode());
288 model->addObserver(databaseReference);
291 TextureUpdateVisitor liveryUpdate(options->getDatabasePathList());
292 model->accept(liveryUpdate);
294 // Copy the userdata fields, still sharing the boundingvolumes,
295 // but introducing new data for velocities.
296 UserDataCopyVisitor userDataCopyVisitor;
297 model->accept(userDataCopyVisitor);
299 model->setName(modelpath.str());
301 bool needTransform=false;
302 // Set up the alignment node if needed
303 SGPropertyNode *offsets = props->getNode("offsets", false);
306 osg::MatrixTransform *alignmainmodel = new osg::MatrixTransform;
307 alignmainmodel->setDataVariance(osg::Object::STATIC);
308 osg::Matrix res_matrix;
309 res_matrix.makeRotate(
310 offsets->getFloatValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
312 offsets->getFloatValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
314 offsets->getFloatValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
318 tmat.makeTranslate(offsets->getFloatValue("x-m", 0.0),
319 offsets->getFloatValue("y-m", 0.0),
320 offsets->getFloatValue("z-m", 0.0));
321 alignmainmodel->setMatrix(res_matrix*tmat);
322 group = alignmainmodel;
325 group = new osg::Group;
327 group->addChild(model.get());
330 vector<SGPropertyNode_ptr> model_nodes = props->getChildren("model");
331 for (unsigned i = 0; i < model_nodes.size(); i++) {
332 SGPropertyNode_ptr sub_props = model_nodes[i];
335 osg::ref_ptr<osg::Node> submodel;
336 string submodelFileName = sub_props->getStringValue("path");
337 if (submodelFileName.size() > 2
338 && !submodelFileName.compare(0, 2, "./" )) {
339 submodelpath = modelpath.dir();
340 submodelpath.append( submodelFileName.substr( 2 ) );
342 submodelpath = submodelFileName;
344 osg::ref_ptr<SGReaderWriterXMLOptions> options;
345 options = new SGReaderWriterXMLOptions(*options_);
346 options->setPropRoot(prop_root);
347 options->setLoadPanel(load_panel);
349 submodel = sgLoad3DModel_internal(submodelpath.str(), options.get(),
350 sub_props->getNode("overlay"));
351 } catch (const sg_throwable &t) {
352 SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage());
356 osg::ref_ptr<osg::Node> submodel_final = submodel;
357 SGPropertyNode *offs = sub_props->getNode("offsets", false);
359 osg::Matrix res_matrix;
360 osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
361 align->setDataVariance(osg::Object::STATIC);
362 res_matrix.makeIdentity();
363 res_matrix.makeRotate(
364 offs->getDoubleValue("pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
366 offs->getDoubleValue("roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
368 offs->getDoubleValue("heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
373 tmat.makeTranslate(offs->getDoubleValue("x-m", 0),
374 offs->getDoubleValue("y-m", 0),
375 offs->getDoubleValue("z-m", 0));
376 align->setMatrix(res_matrix*tmat);
377 align->addChild(submodel.get());
378 submodel_final = align;
380 submodel_final->setName(sub_props->getStringValue("name", ""));
382 SGPropertyNode *cond = sub_props->getNode("condition", false);
384 osg::ref_ptr<osg::Switch> sw = new osg::Switch;
385 sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
386 group->addChild(sw.get());
387 sw->addChild(submodel_final.get());
388 sw->setName("submodel condition switch");
390 group->addChild(submodel_final.get());
392 } // end of submodel loading
396 vector<SGPropertyNode_ptr> panel_nodes = props->getChildren("panel");
397 for (unsigned i = 0; i < panel_nodes.size(); i++) {
398 SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
399 osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
400 if (panel_nodes[i]->hasValue("name"))
401 panel->setName(panel_nodes[i]->getStringValue("name"));
402 group->addChild(panel.get());
406 std::vector<SGPropertyNode_ptr> particle_nodes;
407 particle_nodes = props->getChildren("particlesystem");
408 for (unsigned i = 0; i < particle_nodes.size(); ++i) {
410 if (!texturepath.extension().empty())
411 texturepath = texturepath.dir();
413 options->setDatabasePath(texturepath.str());
415 group->addChild(Particles::appendParticles(particle_nodes[i],
420 std::vector<SGPropertyNode_ptr> text_nodes;
421 text_nodes = props->getChildren("text");
422 for (unsigned i = 0; i < text_nodes.size(); ++i) {
423 group->addChild(SGText::appendText(text_nodes[i],
427 PropertyList effect_nodes = props->getChildren("effect");
428 PropertyList animation_nodes = props->getChildren("animation");
429 // Some material animations (eventually all) are actually effects.
430 makeEffectAnimations(animation_nodes, effect_nodes);
432 ref_ptr<Node> modelWithEffects
433 = instantiateEffects(group.get(), effect_nodes, options.get());
434 group = static_cast<Group*>(modelWithEffects.get());
436 for (unsigned i = 0; i < animation_nodes.size(); ++i)
437 /// OSGFIXME: duh, why not only model?????
438 SGAnimation::animate(group.get(), animation_nodes[i], prop_root,
441 if (!needTransform && group->getNumChildren() < 2) {
442 model = group->getChild(0);
443 group->removeChild(model.get());
445 data->modelLoaded(modelpath.str(), props, model.get());
446 return model.release();
449 data->modelLoaded(modelpath.str(), props, group.get());
450 if (props->hasChild("debug-outfile")) {
451 std::string outputfile = props->getStringValue("debug-outfile",
453 osgDB::writeNodeFile(*group, outputfile);
456 return group.release();