]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/mat.cxx
Work around apparent OSG 3.2.0 normal binding bug.
[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/props/vectorPropTemplates.hxx>
56 #include <simgear/scene/model/model.hxx>
57 #include <simgear/scene/material/matmodel.hxx>
58 #include <simgear/scene/util/RenderConstants.hxx>
59 #include <simgear/scene/util/StateAttributeFactory.hxx>
60 #include <simgear/props/condition.hxx>
61 #include <simgear/scene/util/SGSceneFeatures.hxx>
62 #include <simgear/scene/tgdb/SGTexturedTriangleBin.hxx>
63
64 #include "Effect.hxx"
65 #include "Technique.hxx"
66 #include "Pass.hxx"
67
68 using std::map;
69 using std::string;
70 using namespace simgear;
71
72 \f
73 ////////////////////////////////////////////////////////////////////////
74 // Constructors and destructor.
75 ////////////////////////////////////////////////////////////////////////
76
77 SGMaterial::_internal_state::_internal_state(Effect *e, bool l,
78                                              const SGReaderWriterOptions* o)
79     : effect(e), effect_realized(l), options(o)
80 {
81 }
82
83 SGMaterial::_internal_state::_internal_state(Effect *e, const string &t, bool l, 
84                                              const SGReaderWriterOptions* o)
85     : effect(e), effect_realized(l), options(o)
86 {
87     texture_paths.push_back(std::make_pair(t,0));
88 }
89
90 void SGMaterial::_internal_state::add_texture(const std::string &t, int i)
91 {
92     texture_paths.push_back(std::make_pair(t,i));
93 }
94
95 SGMaterial::SGMaterial( const SGReaderWriterOptions* options,
96                         const SGPropertyNode *props,
97                         SGPropertyNode *prop_root )
98 {
99     init();
100     read_properties( options, props, prop_root );
101     buildEffectProperties(options);
102 }
103
104 SGMaterial::SGMaterial( const osgDB::Options* options,
105                         const SGPropertyNode *props, 
106                         SGPropertyNode *prop_root)
107 {
108     osg::ref_ptr<SGReaderWriterOptions> opt;
109     opt = SGReaderWriterOptions::copyOrCreate(options);
110     init();
111     read_properties(opt.get(), props, prop_root);
112     buildEffectProperties(opt.get());
113 }
114
115 SGMaterial::~SGMaterial (void)
116 {
117 }
118
119 \f
120 ////////////////////////////////////////////////////////////////////////
121 // Public methods.
122 ////////////////////////////////////////////////////////////////////////
123
124 void
125 SGMaterial::read_properties(const SGReaderWriterOptions* options,
126                             const SGPropertyNode *props,
127                             SGPropertyNode *prop_root)
128 {
129     std::vector<bool> dds;
130     std::vector<SGPropertyNode_ptr> textures = props->getChildren("texture");
131     for (unsigned int i = 0; i < textures.size(); i++)
132     {
133         string tname = textures[i]->getStringValue();
134
135         if (tname.empty()) {
136             tname = "unknown.rgb";
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.set("Textures");
144             tpath.append(tname);
145             fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
146             if (fullTexPath.empty()) {
147                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
148                         << tname << "\" in Textures or Textures.high folders.");
149             }
150         }
151
152         if (tpath.lower_extension() == "dds") {
153             dds.push_back(true);
154         } else {
155             dds.push_back(false);
156         }
157
158         if (!fullTexPath.empty() ) {
159             _internal_state st( NULL, fullTexPath, false, options );
160             _status.push_back( st );
161         }
162     }
163
164     std::vector<SGPropertyNode_ptr> texturesets = props->getChildren("texture-set");
165     for (unsigned int i = 0; i < texturesets.size(); i++)
166     {
167         _internal_state st( NULL, false, options );
168         std::vector<SGPropertyNode_ptr> textures = texturesets[i]->getChildren("texture");
169         for (unsigned int j = 0; j < textures.size(); j++)
170         {
171             string tname = textures[j]->getStringValue();
172             if (tname.empty()) {
173                 tname = "unknown.rgb";
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.set("Textures");
181                 tpath.append(tname);
182                 fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
183                 if (fullTexPath.empty() ) {
184                     SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
185                             << tname << "\" in Textures or Textures.high folders.");
186                 }
187             }
188
189             if (j == 0) {
190                 if (tpath.lower_extension() == "dds") {
191                     dds.push_back(true);
192                 } else {
193                     dds.push_back(false);
194                 }
195             }
196
197             st.add_texture(fullTexPath, textures[j]->getIndex());
198         }
199
200         if (!st.texture_paths.empty() ) {
201             _status.push_back( st );
202         }
203     }
204
205     if (textures.empty() && texturesets.empty()) {
206         SGPath tpath("Textures");
207         tpath.append("Terrain");
208         tpath.append("unknown.rgb");
209         _internal_state st( NULL, tpath.str(), true, options );
210         _status.push_back( st );
211     }
212     
213     std::vector<SGPropertyNode_ptr> masks = props->getChildren("object-mask");
214     for (unsigned int i = 0; i < masks.size(); i++)
215     {
216         string omname = masks[i]->getStringValue();
217
218         if (! omname.empty()) {
219             SGPath ompath("Textures.high");
220             ompath.append(omname);
221             string fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
222
223             if (fullMaskPath.empty()) {
224                 ompath.set("Textures");
225                 ompath.append(omname);
226                 fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
227             }
228
229             if (fullMaskPath.empty()) {
230                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
231                         << omname << "\" in Textures or Textures.high folders.");
232             }
233             else
234             {
235                 osg::Image* image = osgDB::readImageFile(fullMaskPath, options);
236                 if (image && image->valid())
237                 {
238                     osg::Texture2D* object_mask = new osg::Texture2D;
239
240                     bool dds_mask = (ompath.lower_extension() == "dds");
241
242                     if (i < dds.size() && dds[i] != dds_mask) {
243                         // Texture format does not match mask format. This is relevant for
244                         // the object mask, as DDS textures have an origin at the bottom
245                         // left rather than top left. Therefore we flip a copy of the image
246                         // (otherwise a second reference to the object mask would flip it
247                         // back!).                
248                         SG_LOG(SG_GENERAL, SG_DEBUG, "Flipping object mask" << omname);  
249                         image = (osg::Image* ) image->clone(osg::CopyOp::SHALLOW_COPY);
250                         image->flipVertical();
251                     }
252
253                     object_mask->setImage(image);
254
255                     // We force the filtering to be nearest, as the red channel (rotation)
256                     // in particular, doesn't make sense to be interpolated between pixels.
257                     object_mask->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
258                     object_mask->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
259
260                     object_mask->setDataVariance(osg::Object::STATIC);
261                     object_mask->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
262                     object_mask->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
263                     _masks.push_back(object_mask);
264                 }
265             }
266         }
267     }
268
269     xsize = props->getDoubleValue("xsize", 0.0);
270     ysize = props->getDoubleValue("ysize", 0.0);
271     wrapu = props->getBoolValue("wrapu", true);
272     wrapv = props->getBoolValue("wrapv", true);
273     mipmap = props->getBoolValue("mipmap", true);
274     light_coverage = props->getDoubleValue("light-coverage", 0.0);
275     
276     // Building properties
277     building_coverage = props->getDoubleValue("building-coverage", 0.0);
278     building_spacing = props->getDoubleValue("building-spacing-m", 5.0);
279     
280     string bt = props->getStringValue("building-texture", "Textures/buildings.png");
281     building_texture = SGModelLib::findDataFile(bt, options);    
282     
283     if (building_texture.empty()) {
284         SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \"" << bt);
285     }
286     
287     bt = props->getStringValue("building-lightmap", "Textures/buildings-lightmap.png");
288     building_lightmap = SGModelLib::findDataFile(bt, options);    
289     
290     if (building_lightmap.empty()) {
291         SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \"" << bt);
292     }    
293             
294     building_small_ratio = props->getDoubleValue("building-small-ratio", 0.8);
295     building_medium_ratio = props->getDoubleValue("building-medium-ratio", 0.15);
296     building_large_ratio =  props->getDoubleValue("building-large-ratio", 0.05);
297     
298     building_small_pitch =  props->getDoubleValue("building-small-pitch", 0.8);
299     building_medium_pitch =  props->getDoubleValue("building-medium-pitch", 0.2);
300     building_large_pitch =  props->getDoubleValue("building-large-pitch", 0.1);
301
302     building_small_min_floors = props->getIntValue("building-small-min-floors", 1);
303     building_small_max_floors = props->getIntValue("building-small-max-floors", 3);
304     building_medium_min_floors = props->getIntValue("building-medium-min-floors", 3);
305     building_medium_max_floors = props->getIntValue("building-medium-max-floors", 8);
306     building_large_min_floors = props->getIntValue("building-large-min-floors", 5);
307     building_large_max_floors = props->getIntValue("building-large-max-floors", 20);
308     
309     building_small_min_width = props->getFloatValue("building-small-min-width-m", 15.0);
310     building_small_max_width = props->getFloatValue("building-small-max-width-m", 60.0);
311     building_small_min_depth = props->getFloatValue("building-small-min-depth-m", 10.0);
312     building_small_max_depth = props->getFloatValue("building-small-max-depth-m", 20.0);
313     
314     building_medium_min_width = props->getFloatValue("building-medium-min-width-m", 25.0);
315     building_medium_max_width = props->getFloatValue("building-medium-max-width-m", 50.0);
316     building_medium_min_depth = props->getFloatValue("building-medium-min-depth-m", 20.0);
317     building_medium_max_depth = props->getFloatValue("building-medium-max-depth-m", 50.0);
318     
319     building_large_min_width = props->getFloatValue("building-large-min-width-m", 50.0);
320     building_large_max_width = props->getFloatValue("building-large-max-width-m", 75.0);
321     building_large_min_depth = props->getFloatValue("building-large-min-depth-m", 50.0);
322     building_large_max_depth = props->getFloatValue("building-large-max-depth-m", 75.0);
323
324     building_range = props->getDoubleValue("building-range-m", 10000.0);
325     
326     cos_object_max_density_slope_angle  = cos(props->getFloatValue("object-max-density-angle-deg", 20.0) * osg::PI/180.0);
327     cos_object_zero_density_slope_angle = cos(props->getFloatValue("object-zero-density-angle-deg", 30.0) * osg::PI/180.0);
328         
329     // Random vegetation properties
330     wood_coverage = props->getDoubleValue("wood-coverage", 0.0);
331     tree_height = props->getDoubleValue("tree-height-m", 0.0);
332     tree_width = props->getDoubleValue("tree-width-m", 0.0);
333     tree_range = props->getDoubleValue("tree-range-m", 0.0);
334     tree_varieties = props->getIntValue("tree-varieties", 1);
335     cos_tree_max_density_slope_angle  = cos(props->getFloatValue("tree-max-density-angle-deg", 30.0) * osg::PI/180.0);
336     cos_tree_zero_density_slope_angle = cos(props->getFloatValue("tree-zero-density-angle-deg", 45.0) * osg::PI/180.0);
337
338     const SGPropertyNode* treeTexNode = props->getChild("tree-texture");
339     
340     if (treeTexNode) {
341         string treeTexPath = props->getStringValue("tree-texture");
342
343         if (! treeTexPath.empty()) {
344             SGPath treePath("Textures.high");
345             treePath.append(treeTexPath);
346             tree_texture = SGModelLib::findDataFile(treePath.str(), options);
347
348             if (tree_texture.empty()) {
349                 treePath.set("Textures");
350                 treePath.append(treeTexPath);
351                 tree_texture = SGModelLib::findDataFile(treePath.str(), options);
352             }
353         }
354     }
355
356     // surface values for use with ground reactions
357     _solid = props->getBoolValue("solid", _solid);
358     _friction_factor = props->getDoubleValue("friction-factor", _friction_factor);
359     _rolling_friction = props->getDoubleValue("rolling-friction", _rolling_friction);
360     _bumpiness = props->getDoubleValue("bumpiness", _bumpiness);
361     _load_resistance = props->getDoubleValue("load-resistance", _load_resistance);
362
363     // Taken from default values as used in ac3d
364     ambient[0] = props->getDoubleValue("ambient/r", 0.2);
365     ambient[1] = props->getDoubleValue("ambient/g", 0.2);
366     ambient[2] = props->getDoubleValue("ambient/b", 0.2);
367     ambient[3] = props->getDoubleValue("ambient/a", 1.0);
368
369     diffuse[0] = props->getDoubleValue("diffuse/r", 0.8);
370     diffuse[1] = props->getDoubleValue("diffuse/g", 0.8);
371     diffuse[2] = props->getDoubleValue("diffuse/b", 0.8);
372     diffuse[3] = props->getDoubleValue("diffuse/a", 1.0);
373
374     specular[0] = props->getDoubleValue("specular/r", 0.0);
375     specular[1] = props->getDoubleValue("specular/g", 0.0);
376     specular[2] = props->getDoubleValue("specular/b", 0.0);
377     specular[3] = props->getDoubleValue("specular/a", 1.0);
378
379     emission[0] = props->getDoubleValue("emissive/r", 0.0);
380     emission[1] = props->getDoubleValue("emissive/g", 0.0);
381     emission[2] = props->getDoubleValue("emissive/b", 0.0);
382     emission[3] = props->getDoubleValue("emissive/a", 1.0);
383
384     shininess = props->getDoubleValue("shininess", 1.0);
385
386     if (props->hasChild("effect"))
387         effect = props->getStringValue("effect");
388
389     std::vector<SGPropertyNode_ptr> object_group_nodes =
390             ((SGPropertyNode *)props)->getChildren("object-group");
391     for (unsigned int i = 0; i < object_group_nodes.size(); i++)
392         object_groups.push_back(new SGMatModelGroup(object_group_nodes[i]));
393
394     // read glyph table for taxi-/runway-signs
395     std::vector<SGPropertyNode_ptr> glyph_nodes = props->getChildren("glyph");
396     for (unsigned int i = 0; i < glyph_nodes.size(); i++) {
397         const char *name = glyph_nodes[i]->getStringValue("name");
398         if (name)
399             glyphs[name] = new SGMaterialGlyph(glyph_nodes[i]);
400     }
401     
402     // Read parameters entry, which is passed into the effect
403     if (props->hasChild("parameters")) {
404         parameters = props->getChild("parameters");
405     } else {
406         parameters = new SGPropertyNode();
407     }
408
409     // Read conditions node
410     const SGPropertyNode *conditionNode = props->getChild("condition");
411     if (conditionNode) {
412         condition = sgReadCondition(prop_root, conditionNode);
413     }
414 }
415
416
417 \f
418 ////////////////////////////////////////////////////////////////////////
419 // Private methods.
420 ////////////////////////////////////////////////////////////////////////
421
422 void 
423 SGMaterial::init ()
424 {
425     _status.clear();
426     xsize = 0;
427     ysize = 0;
428     wrapu = true;
429     wrapv = true;
430
431     mipmap = true;
432     light_coverage = 0.0;
433     building_coverage = 0.0;
434
435     shininess = 1.0;
436     for (int i = 0; i < 4; i++) {
437         ambient[i]  = (i < 3) ? 0.2 : 1.0;
438         specular[i] = (i < 3) ? 0.0 : 1.0;
439         diffuse[i]  = (i < 3) ? 0.8 : 1.0;
440         emission[i] = (i < 3) ? 0.0 : 1.0;
441     }
442     effect = "Effects/terrain-default";
443 }
444
445 Effect* SGMaterial::get_effect(int i)
446 {    
447     if(!_status[i].effect_realized) {
448         if (!_status[i].effect.valid())
449             return 0;
450         _status[i].effect->realizeTechniques(_status[i].options.get());
451         _status[i].effect_realized = true;
452     }
453     return _status[i].effect.get();
454 }
455
456 Effect* SGMaterial::get_effect(const SGTexturedTriangleBin& triangleBin)
457 {
458     if (_status.empty()) {
459         SG_LOG( SG_GENERAL, SG_WARN, "No effect available.");
460         return 0;
461     }
462     
463     int i = triangleBin.getTextureIndex() % _status.size();
464     return get_effect(i);
465 }
466
467 Effect* SGMaterial::get_effect()
468 {
469     return get_effect(0);
470 }
471
472
473 osg::Texture2D* SGMaterial::get_object_mask(const SGTexturedTriangleBin& triangleBin)
474 {
475     if (_status.empty()) {
476         SG_LOG( SG_GENERAL, SG_WARN, "No mask available.");
477         return 0;
478     }
479     
480     // Note that the object mask is closely linked to the texture/effect
481     // so we index based on the texture index, 
482     unsigned int i = triangleBin.getTextureIndex() % _status.size();
483     if (i < _masks.size()) {
484         return _masks[i];
485     } else {
486         return 0;
487     }
488 }
489
490 void SGMaterial::buildEffectProperties(const SGReaderWriterOptions* options)
491 {
492     using namespace osg;
493     ref_ptr<SGMaterialUserData> user = new SGMaterialUserData(this);
494     SGPropertyNode_ptr propRoot = new SGPropertyNode();
495     makeChild(propRoot, "inherits-from")->setStringValue(effect);
496     
497     SGPropertyNode* paramProp = makeChild(propRoot, "parameters");
498     copyProperties(parameters, paramProp);
499     
500     SGPropertyNode* materialProp = makeChild(paramProp, "material");
501     makeChild(materialProp, "ambient")->setValue(SGVec4d(ambient));
502     makeChild(materialProp, "diffuse")->setValue(SGVec4d(diffuse));
503     makeChild(materialProp, "specular")->setValue(SGVec4d(specular));
504     makeChild(materialProp, "emissive")->setValue(SGVec4d(emission));
505     makeChild(materialProp, "shininess")->setFloatValue(shininess);
506     if (ambient[3] < 1 || diffuse[3] < 1 ||
507         specular[3] < 1 || emission[3] < 1) {
508         makeChild(paramProp, "transparent")->setBoolValue(true);
509         SGPropertyNode* binProp = makeChild(paramProp, "render-bin");
510         makeChild(binProp, "bin-number")->setIntValue(TRANSPARENT_BIN);
511         makeChild(binProp, "bin-name")->setStringValue("DepthSortedBin");
512     }
513     BOOST_FOREACH(_internal_state& matState, _status)
514     {
515         SGPropertyNode_ptr effectProp = new SGPropertyNode();
516         copyProperties(propRoot, effectProp);
517         SGPropertyNode* effectParamProp = effectProp->getChild("parameters", 0);
518         for (unsigned int i = 0; i < matState.texture_paths.size(); i++) {
519             SGPropertyNode* texProp = makeChild(effectParamProp, "texture", matState.texture_paths[i].second);
520             makeChild(texProp, "image")->setStringValue(matState.texture_paths[i].first);
521             makeChild(texProp, "filter")
522                 ->setStringValue(mipmap ? "linear-mipmap-linear" : "nearest");
523             makeChild(texProp, "wrap-s")
524                 ->setStringValue(wrapu ? "repeat" : "clamp-to-edge");
525             makeChild(texProp, "wrap-t")
526                 ->setStringValue(wrapv ? "repeat" : "clamp-to-edge");
527         }
528         makeChild(effectParamProp, "xsize")->setDoubleValue(xsize);
529         makeChild(effectParamProp, "ysize")->setDoubleValue(ysize);
530         makeChild(effectParamProp, "scale")->setValue(SGVec3d(xsize,ysize,0.0));
531         makeChild(effectParamProp, "light-coverage")->setDoubleValue(light_coverage);
532
533         matState.effect = makeEffect(effectProp, false, options);
534         if (matState.effect.valid())
535             matState.effect->setUserData(user.get());
536     }
537 }
538
539 SGMaterialGlyph* SGMaterial::get_glyph (const string& name) const
540 {
541     map<string, SGSharedPtr<SGMaterialGlyph> >::const_iterator it;
542     it = glyphs.find(name);
543     if (it == glyphs.end())
544         return 0;
545
546     return it->second;
547 }
548
549 bool SGMaterial::valid() const
550
551   if (condition) {
552     return condition->test();       
553   } else {
554     return true;
555   }
556 }
557
558 \f
559 ////////////////////////////////////////////////////////////////////////
560 // SGMaterialGlyph.
561 ////////////////////////////////////////////////////////////////////////
562
563 SGMaterialGlyph::SGMaterialGlyph(SGPropertyNode *p) :
564     _left(p->getDoubleValue("left", 0.0)),
565     _right(p->getDoubleValue("right", 1.0))
566 {
567 }
568
569 void
570 SGSetTextureFilter( int max) {
571     SGSceneFeatures::instance()->setTextureFilter( max);
572 }
573
574 int
575 SGGetTextureFilter() {
576     return SGSceneFeatures::instance()->getTextureFilter();
577 }