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