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