]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/mat.cxx
Handle dds object masks properly:
[simgear.git] / simgear / scene / material / mat.cxx
1 // mat.cxx -- class to handle material properties
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2000  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <simgear_config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <string.h>
31 #include <map>
32 #include <vector>
33 #include <string>
34
35 #include <boost/foreach.hpp>
36 #include "mat.hxx"
37
38 #include <osg/CullFace>
39 #include <osg/Material>
40 #include <osg/ShadeModel>
41 #include <osg/StateSet>
42 #include <osg/TexEnv>
43 #include <osg/Texture2D>
44 #include <osgDB/ReaderWriter>
45 #include <osgDB/ReadFile>
46 #include <osgDB/Registry>
47 #include <osgDB/FileUtils>
48
49 #include <simgear/debug/logstream.hxx>
50 #include <simgear/misc/sg_path.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
53 #include <simgear/props/props_io.hxx>
54 #include <simgear/scene/model/model.hxx>
55 #include <simgear/scene/util/RenderConstants.hxx>
56 #include <simgear/scene/util/StateAttributeFactory.hxx>
57
58 #include "Effect.hxx"
59 #include "Technique.hxx"
60 #include "Pass.hxx"
61
62 using std::map;
63 using std::string;
64 using namespace simgear;
65
66 \f
67 ////////////////////////////////////////////////////////////////////////
68 // Constructors and destructor.
69 ////////////////////////////////////////////////////////////////////////
70
71 SGMaterial::_internal_state::_internal_state(Effect *e, bool l,
72                                              const SGReaderWriterOptions* o)
73     : effect(e), effect_realized(l), options(o)
74 {
75 }
76
77 SGMaterial::_internal_state::_internal_state(Effect *e, const string &t, bool l, 
78                                              const SGReaderWriterOptions* o)
79     : effect(e), effect_realized(l), options(o)
80 {
81     texture_paths.push_back(std::make_pair(t,0));
82 }
83
84 void SGMaterial::_internal_state::add_texture(const std::string &t, int i)
85 {
86     texture_paths.push_back(std::make_pair(t,i));
87 }
88
89 SGMaterial::SGMaterial( const SGReaderWriterOptions* options,
90                         const SGPropertyNode *props )
91 {
92     init();
93     read_properties( options, props );
94     buildEffectProperties(options);
95 }
96
97 SGMaterial::SGMaterial( const osgDB::ReaderWriter::Options* options,
98                         const SGPropertyNode *props )
99 {
100     osg::ref_ptr<const SGReaderWriterOptions> sgOptions;
101     if (options)
102         sgOptions = new SGReaderWriterOptions(*options);
103     init();
104     read_properties( sgOptions.get(), props );
105     buildEffectProperties(sgOptions.get());
106 }
107
108 SGMaterial::~SGMaterial (void)
109 {
110 }
111
112 \f
113 ////////////////////////////////////////////////////////////////////////
114 // Public methods.
115 ////////////////////////////////////////////////////////////////////////
116
117 void
118 SGMaterial::read_properties(const SGReaderWriterOptions* options,
119                             const SGPropertyNode *props)
120 {
121   std::vector<bool> dds;
122   std::vector<SGPropertyNode_ptr> textures = props->getChildren("texture");
123   for (unsigned int i = 0; i < textures.size(); i++)
124   {
125     string tname = textures[i]->getStringValue();
126     
127     if (tname.empty()) {
128         tname = "unknown.rgb";
129     }
130     
131     if ((tname.rfind(".dds") == (tname.length() - 4)) ||
132         (tname.rfind(".DDS") == (tname.length() - 4))   ) 
133     {
134       dds.push_back(true);
135     } else {
136       dds.push_back(false);      
137     }  
138     
139     SGPath tpath("Textures.high");
140     tpath.append(tname);
141     string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
142     if (fullTexPath.empty()) {
143       tpath = SGPath("Textures");
144       tpath.append(tname);
145       fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
146     }
147     
148     if (!fullTexPath.empty() ) {
149       _internal_state st( NULL, fullTexPath, false, options );
150       _status.push_back( st );
151     }
152   }
153
154   std::vector<SGPropertyNode_ptr> texturesets = props->getChildren("texture-set");
155   for (unsigned int i = 0; i < texturesets.size(); i++)
156   {
157     _internal_state st( NULL, false, options );
158     std::vector<SGPropertyNode_ptr> textures = texturesets[i]->getChildren("texture");
159     for (unsigned int j = 0; j < textures.size(); j++)
160     {
161       string tname = textures[j]->getStringValue();
162       if (tname.empty()) {
163           tname = "unknown.rgb";
164       }
165       
166       if (j == 0) {
167         if ((tname.rfind(".dds") == (tname.length() - 4)) ||
168             (tname.rfind(".DDS") == (tname.length() - 4))   )
169         {
170           dds.push_back(true);
171         } else {
172           dds.push_back(false);      
173         }  
174       }
175   
176       SGPath tpath("Textures.high");
177       tpath.append(tname);
178       string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
179       if (fullTexPath.empty()) {
180         tpath = SGPath("Textures");
181         tpath.append(tname);
182         fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
183       }
184       
185       st.add_texture(fullTexPath, textures[j]->getIndex());
186     }
187
188     if (!st.texture_paths.empty() ) {
189       _status.push_back( st );
190     }
191   }
192
193   if (textures.size() == 0 && texturesets.size() == 0) {
194     SGPath tpath("Textures");
195     tpath.append("Terrain");
196     tpath.append("unknown.rgb");
197     _internal_state st( NULL, tpath.str(), true, options );
198     _status.push_back( st );
199   }
200   
201   std::vector<SGPropertyNode_ptr> masks = props->getChildren("object-mask");
202   for (unsigned int i = 0; i < masks.size(); i++)
203   {
204     string omname = masks[i]->getStringValue();
205     
206     if (! omname.empty()) {
207       SGPath ompath("Textures.high");
208       ompath.append(omname);
209       string fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
210       
211       if (fullMaskPath.empty()) {
212         ompath = SGPath("Textures");
213         ompath.append(omname);
214         fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
215       }    
216       
217       osg::Image* image = osgDB::readImageFile(fullMaskPath, options);
218       if (image->valid())
219       {
220         osg::Texture2D* object_mask = new osg::Texture2D;
221         
222         bool dds_mask = ((omname.rfind(".dds") == (omname.length() - 4)) ||
223                          (omname.rfind(".DDS") == (omname.length() - 4))   );
224         
225         if (dds[i] != dds_mask) {
226           // Texture format does not match mask format. This is relevant for 
227           // the object mask, as DDS textures have an origin at the bottom 
228           // left rather than top left, therefore we flip the object mask 
229           // vertically.
230           image->flipVertical();          
231         }
232         
233         object_mask->setImage(image);
234         object_mask->setDataVariance(osg::Object::STATIC);
235         object_mask->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
236         object_mask->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
237         _masks.push_back(object_mask);
238       } 
239     }
240   } 
241
242   xsize = props->getDoubleValue("xsize", 0.0);
243   ysize = props->getDoubleValue("ysize", 0.0);
244   wrapu = props->getBoolValue("wrapu", true);
245   wrapv = props->getBoolValue("wrapv", true);
246   mipmap = props->getBoolValue("mipmap", true);
247   light_coverage = props->getDoubleValue("light-coverage", 0.0);
248   wood_coverage = props->getDoubleValue("wood-coverage", 0.0);
249   tree_height = props->getDoubleValue("tree-height-m", 0.0);
250   tree_width = props->getDoubleValue("tree-width-m", 0.0);
251   tree_range = props->getDoubleValue("tree-range-m", 0.0);
252   tree_varieties = props->getIntValue("tree-varieties", 1);
253
254   const SGPropertyNode* treeTexNode = props->getChild("tree-texture");
255   
256   if (treeTexNode) {
257     string treeTexPath = props->getStringValue("tree-texture");
258     
259     if (! treeTexPath.empty()) {
260       SGPath treePath("Textures.high");
261       treePath.append(treeTexPath);
262       tree_texture = SGModelLib::findDataFile(treePath.str(), options);
263       
264       if (tree_texture.empty()) {
265         treePath = SGPath("Textures");
266         treePath.append(treeTexPath);
267         tree_texture = SGModelLib::findDataFile(treePath.str(), options);
268       }    
269     }
270   }
271   
272   // surface values for use with ground reactions
273   solid = props->getBoolValue("solid", true);
274   friction_factor = props->getDoubleValue("friction-factor", 1.0);
275   rolling_friction = props->getDoubleValue("rolling-friction", 0.02);
276   bumpiness = props->getDoubleValue("bumpiness", 0.0);
277   load_resistance = props->getDoubleValue("load-resistance", 1e30);
278
279   // Taken from default values as used in ac3d
280   ambient[0] = props->getDoubleValue("ambient/r", 0.2);
281   ambient[1] = props->getDoubleValue("ambient/g", 0.2);
282   ambient[2] = props->getDoubleValue("ambient/b", 0.2);
283   ambient[3] = props->getDoubleValue("ambient/a", 1.0);
284
285   diffuse[0] = props->getDoubleValue("diffuse/r", 0.8);
286   diffuse[1] = props->getDoubleValue("diffuse/g", 0.8);
287   diffuse[2] = props->getDoubleValue("diffuse/b", 0.8);
288   diffuse[3] = props->getDoubleValue("diffuse/a", 1.0);
289
290   specular[0] = props->getDoubleValue("specular/r", 0.0);
291   specular[1] = props->getDoubleValue("specular/g", 0.0);
292   specular[2] = props->getDoubleValue("specular/b", 0.0);
293   specular[3] = props->getDoubleValue("specular/a", 1.0);
294
295   emission[0] = props->getDoubleValue("emissive/r", 0.0);
296   emission[1] = props->getDoubleValue("emissive/g", 0.0);
297   emission[2] = props->getDoubleValue("emissive/b", 0.0);
298   emission[3] = props->getDoubleValue("emissive/a", 1.0);
299
300   shininess = props->getDoubleValue("shininess", 1.0);
301
302   if (props->hasChild("effect"))
303       effect = props->getStringValue("effect");
304   
305   std::vector<SGPropertyNode_ptr> object_group_nodes =
306     ((SGPropertyNode *)props)->getChildren("object-group");
307   for (unsigned int i = 0; i < object_group_nodes.size(); i++)
308     object_groups.push_back(new SGMatModelGroup(object_group_nodes[i]));
309
310   // read glyph table for taxi-/runway-signs
311   std::vector<SGPropertyNode_ptr> glyph_nodes = props->getChildren("glyph");
312   for (unsigned int i = 0; i < glyph_nodes.size(); i++) {
313     const char *name = glyph_nodes[i]->getStringValue("name");
314     if (name)
315       glyphs[name] = new SGMaterialGlyph(glyph_nodes[i]);
316   }
317 }
318
319
320 \f
321 ////////////////////////////////////////////////////////////////////////
322 // Private methods.
323 ////////////////////////////////////////////////////////////////////////
324
325 void 
326 SGMaterial::init ()
327 {
328     _status.clear();
329     xsize = 0;
330     ysize = 0;
331     wrapu = true;
332     wrapv = true;
333
334     mipmap = true;
335     light_coverage = 0.0;
336
337     solid = true;
338     friction_factor = 1;
339     rolling_friction = 0.02;
340     bumpiness = 0;
341     load_resistance = 1e30;
342
343     shininess = 1.0;
344     for (int i = 0; i < 4; i++) {
345         ambient[i]  = (i < 3) ? 0.2 : 1.0;
346         specular[i] = (i < 3) ? 0.0 : 1.0;
347         diffuse[i]  = (i < 3) ? 0.8 : 1.0;
348         emission[i] = (i < 3) ? 0.0 : 1.0;
349     }
350     effect = "Effects/terrain-default";
351 }
352
353 Effect* SGMaterial::get_effect(int i)
354 {    
355     if(!_status[i].effect_realized) {
356         _status[i].effect->realizeTechniques(_status[i].options.get());
357         _status[i].effect_realized = true;
358     }
359     return _status[i].effect.get();
360 }
361
362 Effect* SGMaterial::get_effect(SGTexturedTriangleBin triangleBin)
363 {
364     if (_status.size() == 0) {
365         SG_LOG( SG_GENERAL, SG_WARN, "No effect available.");
366         return 0;
367     }
368     
369     int i = triangleBin.getTextureIndex() % _status.size();
370     return get_effect(i);
371 }
372
373 Effect* SGMaterial::get_effect()
374 {
375     return get_effect(0);
376 }
377
378
379 osg::Texture2D* SGMaterial::get_object_mask(SGTexturedTriangleBin triangleBin)
380 {
381     if (_status.size() == 0) {
382         SG_LOG( SG_GENERAL, SG_WARN, "No mask available.");
383         return 0;
384     }
385     
386     // Note that the object mask is closely linked to the texture/effect
387     // so we index based on the texture index, 
388     unsigned int i = triangleBin.getTextureIndex() % _status.size();
389     if (i < _masks.size()) {
390         return _masks[i];      
391     } else {
392         return 0;      
393     }
394 }
395
396 void SGMaterial::buildEffectProperties(const SGReaderWriterOptions* options)
397 {
398     using namespace osg;
399     ref_ptr<SGReaderWriterOptions> xmlOptions;
400     if (options)
401         xmlOptions = new SGReaderWriterOptions(*options);
402     ref_ptr<SGMaterialUserData> user = new SGMaterialUserData(this);
403     SGPropertyNode_ptr propRoot = new SGPropertyNode();
404     makeChild(propRoot, "inherits-from")->setStringValue(effect);
405     SGPropertyNode* paramProp = makeChild(propRoot, "parameters");
406     SGPropertyNode* materialProp = makeChild(paramProp, "material");
407     makeChild(materialProp, "ambient")->setValue(SGVec4d(ambient));    
408     makeChild(materialProp, "diffuse")->setValue(SGVec4d(diffuse));
409     makeChild(materialProp, "specular")->setValue(SGVec4d(specular));
410     makeChild(materialProp, "emissive")->setValue(SGVec4d(emission));
411     makeChild(materialProp, "shininess")->setFloatValue(shininess);
412     if (ambient[3] < 1 || diffuse[3] < 1 ||
413         specular[3] < 1 || emission[3] < 1) {
414         makeChild(paramProp, "transparent")->setBoolValue(true);
415         SGPropertyNode* binProp = makeChild(paramProp, "render-bin");
416         makeChild(binProp, "bin-number")->setIntValue(TRANSPARENT_BIN);
417         makeChild(binProp, "bin-name")->setStringValue("DepthSortedBin");
418     }
419     BOOST_FOREACH(_internal_state& matState, _status)
420     {
421         SGPropertyNode_ptr effectProp = new SGPropertyNode();
422         copyProperties(propRoot, effectProp);
423         SGPropertyNode* effectParamProp = effectProp->getChild("parameters", 0);
424         for (unsigned int i = 0; i < matState.texture_paths.size(); i++) {
425             SGPropertyNode* texProp = makeChild(effectParamProp, "texture", matState.texture_paths[i].second);
426             makeChild(texProp, "image")->setStringValue(matState.texture_paths[i].first);
427             makeChild(texProp, "filter")
428                 ->setStringValue(mipmap ? "linear-mipmap-linear" : "nearest");
429             makeChild(texProp, "wrap-s")
430                 ->setStringValue(wrapu ? "repeat" : "clamp");
431             makeChild(texProp, "wrap-t")
432                 ->setStringValue(wrapv ? "repeat" : "clamp");
433         }
434         makeChild(effectParamProp, "xsize")->setDoubleValue(xsize);
435         makeChild(effectParamProp, "ysize")->setDoubleValue(ysize);
436         makeChild(effectParamProp, "scale")->setValue(SGVec3d(xsize,ysize,0.0));
437         makeChild(effectParamProp, "light-coverage")->setDoubleValue(light_coverage);
438
439         matState.effect = makeEffect(effectProp, false, xmlOptions.get());
440         matState.effect->setUserData(user.get());
441     }
442 }
443
444 SGMaterialGlyph* SGMaterial::get_glyph (const string& name) const
445 {
446   map<string, SGSharedPtr<SGMaterialGlyph> >::const_iterator it;
447   it = glyphs.find(name);
448   if (it == glyphs.end())
449     return 0;
450
451   return it->second;
452 }
453
454 \f
455 ////////////////////////////////////////////////////////////////////////
456 // SGMaterialGlyph.
457 ////////////////////////////////////////////////////////////////////////
458
459 SGMaterialGlyph::SGMaterialGlyph(SGPropertyNode *p) :
460     _left(p->getDoubleValue("left", 0.0)),
461     _right(p->getDoubleValue("right", 1.0))
462 {
463 }
464
465 void
466 SGSetTextureFilter( int max) {
467         SGSceneFeatures::instance()->setTextureFilter( max);
468 }
469
470 int
471 SGGetTextureFilter() {
472         return SGSceneFeatures::instance()->getTextureFilter();
473 }