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