]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/model.cxx
Don't modify OSG Registry with file path
[simgear.git] / simgear / scene / model / model.cxx
1 // model.cxx - manage a 3D aircraft model.
2 // Written by David Megginson, started 2002.
3 //
4 // This file is in the Public Domain, and comes with no warranty.
5
6 #ifdef HAVE_CONFIG_H
7 #include <simgear_config.h>
8 #endif
9
10 #include <osg/observer_ptr>
11 #include <osg/ref_ptr>
12 #include <osg/Group>
13 #include <osg/NodeCallback>
14 #include <osg/Switch>
15 #include <osg/MatrixTransform>
16 #include <osgDB/Archive>
17 #include <osgDB/FileNameUtils>
18 #include <osgDB/FileUtils>
19 #include <osgDB/ReadFile>
20 #include <osgDB/WriteFile>
21 #include <osgDB/Registry>
22 #include <osgDB/SharedStateManager>
23 #include <osgUtil/Optimizer>
24
25 #include <simgear/scene/util/SGSceneFeatures.hxx>
26 #include <simgear/scene/util/SGStateAttributeVisitor.hxx>
27 #include <simgear/scene/util/SGTextureStateAttributeVisitor.hxx>
28
29 #include <simgear/structure/exception.hxx>
30 #include <simgear/props/props.hxx>
31 #include <simgear/props/props_io.hxx>
32 #include <simgear/props/condition.hxx>
33
34 #include "animation.hxx"
35 #include "model.hxx"
36
37 SG_USING_STD(vector);
38
39 osg::Texture2D*
40 SGLoadTexture2D(const std::string& path,
41                 const osgDB::ReaderWriter::Options* options,
42                 bool wrapu, bool wrapv, int)
43 {
44   osg::Image* image;
45   if (options)
46     image = osgDB::readImageFile(path, options);
47   else
48     image = osgDB::readImageFile(path);
49   osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
50   texture->setImage(image);
51   texture->setDataVariance(osg::Object::STATIC);
52   if (wrapu)
53     texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
54   else
55     texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP);
56   if (wrapv)
57     texture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
58   else
59     texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP);
60
61   if (image) {
62     int s = image->s();
63     int t = image->t();
64
65     if (s <= t && 32 <= s) {
66       SGSceneFeatures::instance()->setTextureCompression(texture.get());
67     } else if (t < s && 32 <= t) {
68       SGSceneFeatures::instance()->setTextureCompression(texture.get());
69     }
70   }
71
72   // Make sure the texture is shared if we already have the same texture
73   // somewhere ...
74   {
75     osg::ref_ptr<osg::Node> tmpNode = new osg::Node;
76     osg::StateSet* stateSet = tmpNode->getOrCreateStateSet();
77     stateSet->setTextureAttribute(0, texture.get());
78
79     // OSGFIXME: don't forget that mutex here
80     osgDB::Registry* registry = osgDB::Registry::instance();
81     registry->getSharedStateManager()->share(tmpNode.get(), 0);
82
83     // should be the same, but be paranoid ...
84     stateSet = tmpNode->getStateSet();
85     osg::StateAttribute* stateAttr;
86     stateAttr = stateSet->getTextureAttribute(0, osg::StateAttribute::TEXTURE);
87     osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(stateAttr);
88     if (texture2D)
89       texture = texture2D;
90   }
91
92   return texture.release();
93 }
94
95 class SGSwitchUpdateCallback : public osg::NodeCallback {
96 public:
97   SGSwitchUpdateCallback(SGCondition* condition) :
98     mCondition(condition) {}
99   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
100   { 
101     assert(dynamic_cast<osg::Switch*>(node));
102     osg::Switch* s = static_cast<osg::Switch*>(node);
103
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.
109       traverse(node, nv);
110     } else
111       s->setAllChildrenOff();
112   }
113
114 private:
115   SGSharedPtr<SGCondition> mCondition;
116 };
117
118 \f
119 ////////////////////////////////////////////////////////////////////////
120 // Global functions.
121 ////////////////////////////////////////////////////////////////////////
122
123 osg::Node *
124 sgLoad3DModel( const string &fg_root, const string &path,
125                SGPropertyNode *prop_root,
126                double sim_time_sec, osg::Node *(*load_panel)(SGPropertyNode *),
127                SGModelData *data,
128                const SGPath& externalTexturePath )
129 {
130   osg::ref_ptr<osg::Node> model;
131   SGPropertyNode props;
132
133   // Load the 3D aircraft object itself
134   SGPath modelpath = path, texturepath = path;
135   if ( !ulIsAbsolutePathName( path.c_str() ) ) {
136     SGPath tmp = fg_root;
137     tmp.append(modelpath.str());
138     modelpath = texturepath = tmp;
139   }
140
141   // Check for an XML wrapper
142   if (modelpath.str().substr(modelpath.str().size() - 4, 4) == ".xml") {
143     readProperties(modelpath.str(), &props);
144     if (props.hasValue("/path")) {
145       modelpath = modelpath.dir();
146       modelpath.append(props.getStringValue("/path"));
147       if (props.hasValue("/texture-path")) {
148         texturepath = texturepath.dir();
149         texturepath.append(props.getStringValue("/texture-path"));
150       }
151     } else {
152       if (!model)
153         model = new osg::Switch;
154     }
155   }
156
157   osg::ref_ptr<osgDB::ReaderWriter::Options> options
158       = new osgDB::ReaderWriter::Options(*osgDB::Registry::instance()
159                                          ->getOptions());
160
161   // Assume that textures are in
162   // the same location as the XML file.
163   if (!model) {
164       if (texturepath.extension() != "")
165           texturepath = texturepath.dir();
166
167       options->setDatabasePath(texturepath.str());
168       if (!externalTexturePath.str().empty())
169           options->getDatabasePathList().push_back(externalTexturePath.str());
170
171       model = osgDB::readNodeFile(modelpath.str(), options.get());
172       if (model == 0)
173           throw sg_io_exception("Failed to load 3D model", 
174                                 sg_location(modelpath.str()));
175   }
176
177   // Set up the alignment node
178   osg::ref_ptr<osg::MatrixTransform> alignmainmodel = new osg::MatrixTransform;
179   alignmainmodel->addChild(model.get());
180   osg::Matrix res_matrix;
181   res_matrix.makeRotate(
182     props.getFloatValue("/offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
183     osg::Vec3(0, 1, 0),
184     props.getFloatValue("/offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
185     osg::Vec3(1, 0, 0),
186     props.getFloatValue("/offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
187     osg::Vec3(0, 0, 1));
188
189   osg::Matrix tmat;
190   tmat.makeTranslate(props.getFloatValue("/offsets/x-m", 0.0),
191                      props.getFloatValue("/offsets/y-m", 0.0),
192                      props.getFloatValue("/offsets/z-m", 0.0));
193   alignmainmodel->setMatrix(res_matrix*tmat);
194
195   // Load sub-models
196   vector<SGPropertyNode_ptr> model_nodes = props.getChildren("model");
197   for (unsigned i = 0; i < model_nodes.size(); i++) {
198     SGPropertyNode_ptr node = model_nodes[i];
199     osg::ref_ptr<osg::MatrixTransform> align = new osg::MatrixTransform;
200     res_matrix.makeIdentity();
201     res_matrix.makeRotate(
202       node->getDoubleValue("offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
203       osg::Vec3(0, 1, 0),
204       node->getDoubleValue("offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
205       osg::Vec3(1, 0, 0),
206       node->getDoubleValue("offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
207       osg::Vec3(0, 0, 1));
208     
209     tmat.makeIdentity();
210     tmat.makeTranslate(node->getDoubleValue("offsets/x-m", 0),
211                        node->getDoubleValue("offsets/y-m", 0),
212                        node->getDoubleValue("offsets/z-m", 0));
213     align->setMatrix(res_matrix*tmat);
214
215     osg::ref_ptr<osg::Node> kid;
216     const char* submodel = node->getStringValue("path");
217     try {
218       kid = sgLoad3DModel( fg_root, submodel, prop_root, sim_time_sec, load_panel );
219
220     } catch (const sg_throwable &t) {
221       SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage());
222       throw;
223     }
224     align->addChild(kid.get());
225
226     align->setName(node->getStringValue("name", ""));
227
228     SGPropertyNode *cond = node->getNode("condition", false);
229     if (cond) {
230       osg::ref_ptr<osg::Switch> sw = new osg::Switch;
231       sw->setUpdateCallback(new SGSwitchUpdateCallback(sgReadCondition(prop_root, cond)));
232       alignmainmodel->addChild(sw.get());
233       sw->addChild(align.get());
234       sw->setName("submodel condition switch");
235     } else {
236       alignmainmodel->addChild(align.get());
237     }
238   }
239
240   if ( load_panel ) {
241     // Load panels
242     vector<SGPropertyNode_ptr> panel_nodes = props.getChildren("panel");
243     for (unsigned i = 0; i < panel_nodes.size(); i++) {
244         SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
245         osg::ref_ptr<osg::Node> panel = load_panel(panel_nodes[i]);
246         if (panel_nodes[i]->hasValue("name"))
247             panel->setName((char *)panel_nodes[i]->getStringValue("name"));
248         alignmainmodel->addChild(panel.get());
249     }
250   }
251
252   if (data) {
253     alignmainmodel->setUserData(data);
254     data->modelLoaded(path, &props, alignmainmodel.get());
255   }
256
257   std::vector<SGPropertyNode_ptr> animation_nodes;
258   animation_nodes = props.getChildren("animation");
259   for (unsigned i = 0; i < animation_nodes.size(); ++i)
260     /// OSGFIXME: duh, why not only model?????
261     SGAnimation::animate(alignmainmodel.get(), animation_nodes[i], prop_root,
262                          options.get());
263
264   if (props.hasChild("debug-outfile")) {
265     std::string outputfile = props.getStringValue("debug-outfile",
266                                                   "debug-model.osg");
267     osgDB::writeNodeFile(*alignmainmodel, outputfile);
268   }
269
270   return alignmainmodel.release();
271 }
272
273 // end of model.cxx