]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/Effect.cxx
Fix removal of directories.
[simgear.git] / simgear / scene / material / Effect.cxx
1 // Copyright (C) 2008 - 2010  Tim Moore timoore33@gmail.com
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Library General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 #ifdef HAVE_CONFIG_H
18 #  include <simgear_config.h>
19 #endif
20
21 #include "Effect.hxx"
22 #include "EffectBuilder.hxx"
23 #include "EffectGeode.hxx"
24 #include "Technique.hxx"
25 #include "Pass.hxx"
26 #include "TextureBuilder.hxx"
27 #include "parseBlendFunc.hxx"
28
29 #include <algorithm>
30 #include <functional>
31 #include <iterator>
32 #include <map>
33 #include <queue>
34 #include <utility>
35 #include <boost/tr1/unordered_map.hpp>
36
37 #include <boost/bind.hpp>
38 #include <boost/foreach.hpp>
39 #include <boost/functional/hash.hpp>
40 #include <boost/tuple/tuple.hpp>
41 #include <boost/tuple/tuple_comparison.hpp>
42
43 #include <osg/AlphaFunc>
44 #include <osg/BlendFunc>
45 #include <osg/CullFace>
46 #include <osg/Depth>
47 #include <osg/Drawable>
48 #include <osg/Material>
49 #include <osg/Math>
50 #include <osg/PolygonMode>
51 #include <osg/PolygonOffset>
52 #include <osg/Point>
53 #include <osg/Program>
54 #include <osg/Referenced>
55 #include <osg/RenderInfo>
56 #include <osg/ShadeModel>
57 #include <osg/StateSet>
58 #include <osg/Stencil>
59 #include <osg/TexEnv>
60 #include <osg/Texture1D>
61 #include <osg/Texture2D>
62 #include <osg/Texture3D>
63 #include <osg/TextureRectangle>
64 #include <osg/Uniform>
65 #include <osg/Vec4d>
66 #include <osgUtil/CullVisitor>
67 #include <osgDB/FileUtils>
68 #include <osgDB/Input>
69 #include <osgDB/ParameterOutput>
70 #include <osgDB/ReadFile>
71 #include <osgDB/Registry>
72
73 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
74 #include <simgear/scene/tgdb/userdata.hxx>
75 #include <simgear/scene/util/OsgMath.hxx>
76 #include <simgear/scene/util/SGSceneFeatures.hxx>
77 #include <simgear/scene/util/StateAttributeFactory.hxx>
78 #include <simgear/structure/OSGUtils.hxx>
79 #include <simgear/structure/SGExpression.hxx>
80 #include <simgear/props/vectorPropTemplates.hxx>
81 #include <simgear/threads/SGThread.hxx>
82 #include <simgear/threads/SGGuard.hxx>
83
84 namespace simgear
85 {
86 using namespace std;
87 using namespace osg;
88 using namespace osgUtil;
89
90 using namespace effect;
91
92 class UniformFactoryImpl {
93 public:
94     ref_ptr<Uniform> getUniform( Effect * effect, 
95                                  const string & name, 
96                                  Uniform::Type uniformType, 
97                                  SGConstPropertyNode_ptr valProp, 
98                                  const SGReaderWriterOptions* options );
99     void updateListeners( SGPropertyNode* propRoot );
100     void addListener(DeferredPropertyListener* listener);
101 private:
102     // Default names for vector property components
103     static const char* vec3Names[];
104     static const char* vec4Names[];
105
106     SGMutex _mutex;
107
108     typedef boost::tuple<std::string, Uniform::Type, std::string, std::string> UniformCacheKey;
109     typedef boost::tuple<ref_ptr<Uniform>, SGPropertyChangeListener*> UniformCacheValue;
110     std::map<UniformCacheKey,ref_ptr<Uniform> > uniformCache;
111
112     typedef std::queue<DeferredPropertyListener*> DeferredListenerList;
113     DeferredListenerList deferredListenerList;
114 };
115
116 const char* UniformFactoryImpl::vec3Names[] = {"x", "y", "z"};
117 const char* UniformFactoryImpl::vec4Names[] = {"x", "y", "z", "w"};
118
119 ref_ptr<Uniform> UniformFactoryImpl::getUniform( Effect * effect, 
120                                  const string & name, 
121                                  Uniform::Type uniformType, 
122                                  SGConstPropertyNode_ptr valProp,
123                                  const SGReaderWriterOptions* options )
124 {
125         SGGuard<SGMutex> scopeLock(_mutex);
126         std::string val = "0";
127
128         if (valProp->nChildren() == 0) {
129                 // Completely static value
130                 val = valProp->getStringValue();
131         } else {
132                 // Value references <parameters> section of Effect
133                 const SGPropertyNode* prop = getEffectPropertyNode(effect, valProp);
134
135                 if (prop) {
136                         if (prop->nChildren() == 0) {
137                                 // Static value in parameters section
138                                 val = prop->getStringValue();
139                         } else {
140                                 // Dynamic property value in parameters section
141                                 val = getGlobalProperty(prop, options);
142                         }
143                 } else {
144                         SG_LOG(SG_GL,SG_DEBUG,"Invalid parameter " << valProp->getName() << " for uniform " << name << " in Effect ");
145                 }
146         }
147
148         UniformCacheKey key = boost::make_tuple(name, uniformType, val, effect->getName());
149         ref_ptr<Uniform> uniform = uniformCache[key];
150
151     if (uniform.valid()) {
152         // We've got a hit to cache - simply return it
153         return uniform;
154     }
155
156     SG_LOG(SG_GL,SG_DEBUG,"new uniform " << name << " value " << uniformCache.size());
157     uniformCache[key] = uniform = new Uniform;
158
159     uniform->setName(name);
160     uniform->setType(uniformType);
161     switch (uniformType) {
162     case Uniform::BOOL:
163         initFromParameters(effect, valProp, uniform.get(),
164                            static_cast<bool (Uniform::*)(bool)>(&Uniform::set),
165                            options);
166         break;
167     case Uniform::FLOAT:
168         initFromParameters(effect, valProp, uniform.get(),
169                            static_cast<bool (Uniform::*)(float)>(&Uniform::set),
170                            options);
171         break;
172     case Uniform::FLOAT_VEC3:
173         initFromParameters(effect, valProp, uniform.get(),
174                            static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
175                            vec3Names, options);
176         break;
177     case Uniform::FLOAT_VEC4:
178         initFromParameters(effect, valProp, uniform.get(),
179                            static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
180                            vec4Names, options);
181         break;
182     case Uniform::INT:
183     case Uniform::SAMPLER_1D:
184     case Uniform::SAMPLER_2D:
185     case Uniform::SAMPLER_3D:
186     case Uniform::SAMPLER_1D_SHADOW:
187     case Uniform::SAMPLER_2D_SHADOW:
188     case Uniform::SAMPLER_CUBE:
189         initFromParameters(effect, valProp, uniform.get(),
190                            static_cast<bool (Uniform::*)(int)>(&Uniform::set),
191                            options);
192         break;
193     default: // avoid compiler warning
194         SG_LOG(SG_ALL,SG_ALERT,"UNKNOWN Uniform type '" << uniformType << "'");
195         break;
196     }
197
198     return uniform;
199 }
200
201 void UniformFactoryImpl::addListener(DeferredPropertyListener* listener)
202 {
203     if (listener != 0) {
204         // Uniform requires a property listener. Add it to the list to be
205         // created when the main thread gets to it.
206         deferredListenerList.push(listener);
207     }
208 }
209
210 void UniformFactoryImpl::updateListeners( SGPropertyNode* propRoot )
211 {
212         SGGuard<SGMutex> scopeLock(_mutex);
213
214         if (deferredListenerList.empty()) return;
215
216         SG_LOG(SG_GL,SG_DEBUG,"Adding " << deferredListenerList.size() << " listeners for effects.");
217
218         // Instantiate all queued listeners
219         while (! deferredListenerList.empty()) {
220                 DeferredPropertyListener* listener = deferredListenerList.front();
221                 listener->activate(propRoot);
222                 deferredListenerList.pop();
223         }
224 }
225
226 typedef Singleton<UniformFactoryImpl> UniformFactory;
227
228
229 Effect::Effect()
230     : _cache(0), _isRealized(false)
231 {
232 }
233
234 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
235     : osg::Object(rhs,copyop), root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
236       _isRealized(rhs._isRealized)
237 {
238     typedef vector<ref_ptr<Technique> > TechniqueList;
239     for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
240              end = rhs.techniques.end();
241          itr != end;
242          ++itr)
243         techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
244
245     generator = rhs.generator;
246     _name = rhs._name;
247     _name += " clone";
248 }
249
250 // Assume that the last technique is always valid.
251 StateSet* Effect::getDefaultStateSet()
252 {
253     Technique* tniq = techniques.back().get();
254     if (!tniq)
255         return 0;
256     Pass* pass = tniq->passes.front().get();
257     return pass;
258 }
259
260 int Effect::getGenerator(Effect::Generator what) const
261 {
262     std::map<Generator,int>::const_iterator it = generator.find(what);
263     if(it == generator.end()) return -1;
264     else return it->second;
265 }
266
267 // There should always be a valid technique in an effect.
268
269 Technique* Effect::chooseTechnique(RenderInfo* info)
270 {
271     BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
272     {
273         if (technique->valid(info) == Technique::VALID)
274             return technique.get();
275     }
276     return 0;
277 }
278
279 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
280 {
281     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
282     {
283         technique->resizeGLObjectBuffers(maxSize);
284     }
285 }
286
287 void Effect::releaseGLObjects(osg::State* state) const
288 {
289     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
290     {
291         technique->releaseGLObjects(state);
292     }
293 }
294
295 Effect::~Effect()
296 {
297     delete _cache;
298 }
299
300 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
301                const SGReaderWriterOptions* options)
302 {
303     Pass* pass = new Pass;
304     tniq->passes.push_back(pass);
305     for (int i = 0; i < prop->nChildren(); ++i) {
306         const SGPropertyNode* attrProp = prop->getChild(i);
307         PassAttributeBuilder* builder
308             = PassAttributeBuilder::find(attrProp->getNameString());
309         if (builder)
310             builder->buildAttribute(effect, pass, attrProp, options);
311         else
312             SG_LOG(SG_INPUT, SG_ALERT,
313                    "skipping unknown pass attribute " << attrProp->getName());
314     }
315 }
316
317 osg::Vec4f getColor(const SGPropertyNode* prop)
318 {
319     if (prop->nChildren() == 0) {
320         if (prop->getType() == props::VEC4D) {
321             return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
322         } else if (prop->getType() == props::VEC3D) {
323             return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
324         } else {
325             SG_LOG(SG_INPUT, SG_ALERT,
326                    "invalid color property " << prop->getName() << " "
327                    << prop->getStringValue());
328             return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
329         }
330     } else {
331         osg::Vec4f result;
332         static const char* colors[] = {"r", "g", "b"};
333         for (int i = 0; i < 3; ++i) {
334             const SGPropertyNode* componentProp = prop->getChild(colors[i]);
335             result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
336         }
337         const SGPropertyNode* alphaProp = prop->getChild("a");
338         result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
339         return result;
340     }
341 }
342
343 struct LightingBuilder : public PassAttributeBuilder
344 {
345     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
346                         const SGReaderWriterOptions* options);
347 };
348
349 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
350                                      const SGPropertyNode* prop,
351                                      const SGReaderWriterOptions* options)
352 {
353     const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
354     if (!realProp)
355         return;
356     pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
357                                 : StateAttribute::OFF));
358 }
359
360 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
361
362 struct ShadeModelBuilder : public PassAttributeBuilder
363 {
364     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
365                         const SGReaderWriterOptions* options)
366     {
367         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
368         if (!realProp)
369             return;
370         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
371         string propVal = realProp->getStringValue();
372         if (propVal == "flat")
373             pass->setAttribute(attrFact->getFlatShadeModel());
374         else if (propVal == "smooth")
375             pass->setAttribute(attrFact->getSmoothShadeModel());
376         else
377             SG_LOG(SG_INPUT, SG_ALERT,
378                    "invalid shade model property " << propVal);
379     }
380 };
381
382 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
383
384 struct CullFaceBuilder : PassAttributeBuilder
385 {
386     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
387                         const SGReaderWriterOptions* options)
388     {
389         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
390         if (!realProp) {
391             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
392             return;
393         }
394         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
395         string propVal = realProp->getStringValue();
396         if (propVal == "front")
397             pass->setAttributeAndModes(attrFact->getCullFaceFront());
398         else if (propVal == "back")
399             pass->setAttributeAndModes(attrFact->getCullFaceBack());
400         else if (propVal == "front-back")
401             pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
402         else if (propVal == "off")
403             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
404         else
405             SG_LOG(SG_INPUT, SG_ALERT,
406                    "invalid cull face property " << propVal);
407     }
408 };
409
410 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
411
412 struct ColorMaskBuilder : PassAttributeBuilder
413 {
414     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
415                         const SGReaderWriterOptions* options)
416     {
417         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
418         if (!realProp)
419             return;
420
421         ColorMask *mask = new ColorMask;
422         Vec4 m = getColor(realProp);
423         mask->setMask(m.r() > 0.0, m.g() > 0.0, m.b() > 0.0, m.a() > 0.0);
424         pass->setAttributeAndModes(mask);
425     }
426 };
427
428 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
429
430 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
431 {
432     { "default", StateSet::DEFAULT_BIN },
433     { "opaque", StateSet::OPAQUE_BIN },
434     { "transparent", StateSet::TRANSPARENT_BIN }
435 };
436
437 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
438
439 struct HintBuilder : public PassAttributeBuilder
440 {
441     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
442                         const SGReaderWriterOptions* options)
443     {
444         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
445         if (!realProp)
446             return;
447         StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
448         findAttr(renderingHints, realProp, renderingHint);
449         pass->setRenderingHint(renderingHint);
450     }
451 };
452
453 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
454
455 struct RenderBinBuilder : public PassAttributeBuilder
456 {
457     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
458                         const SGReaderWriterOptions* options)
459     {
460         if (!isAttributeActive(effect, prop))
461             return;
462         const SGPropertyNode* binProp = prop->getChild("bin-number");
463         binProp = getEffectPropertyNode(effect, binProp);
464         const SGPropertyNode* nameProp = prop->getChild("bin-name");
465         nameProp = getEffectPropertyNode(effect, nameProp);
466         if (binProp && nameProp) {
467             pass->setRenderBinDetails(binProp->getIntValue(),
468                                       nameProp->getStringValue());
469         } else {
470             if (!binProp)
471                 SG_LOG(SG_INPUT, SG_ALERT,
472                        "No render bin number specified in render bin section");
473             if (!nameProp)
474                 SG_LOG(SG_INPUT, SG_ALERT,
475                        "No render bin name specified in render bin section");
476         }
477     }
478 };
479
480 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
481
482 struct MaterialBuilder : public PassAttributeBuilder
483 {
484     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
485                         const SGReaderWriterOptions* options);
486 };
487
488 EffectNameValue<Material::ColorMode> colorModeInit[] =
489 {
490     { "ambient", Material::AMBIENT },
491     { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
492     { "diffuse", Material::DIFFUSE },
493     { "emissive", Material::EMISSION },
494     { "specular", Material::SPECULAR },
495     { "off", Material::OFF }
496 };
497 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
498
499 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
500                                      const SGPropertyNode* prop,
501                                      const SGReaderWriterOptions* options)
502 {
503     if (!isAttributeActive(effect, prop))
504         return;
505     Material* mat = new Material;
506     const SGPropertyNode* color = 0;
507     if ((color = getEffectPropertyChild(effect, prop, "ambient")))
508         mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
509     if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
510         mat->setAmbient(Material::FRONT, getColor(color));
511     if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
512         mat->setAmbient(Material::BACK, getColor(color));
513     if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
514         mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
515     if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
516         mat->setDiffuse(Material::FRONT, getColor(color));
517     if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
518         mat->setDiffuse(Material::BACK, getColor(color));
519     if ((color = getEffectPropertyChild(effect, prop, "specular")))
520         mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
521     if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
522         mat->setSpecular(Material::FRONT, getColor(color));
523     if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
524         mat->setSpecular(Material::BACK, getColor(color));
525     if ((color = getEffectPropertyChild(effect, prop, "emissive")))
526         mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
527     if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
528         mat->setEmission(Material::FRONT, getColor(color));
529     if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
530         mat->setEmission(Material::BACK, getColor(color));
531     const SGPropertyNode* shininess = 0;
532     mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
533     if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
534         mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
535     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
536         mat->setShininess(Material::FRONT, shininess->getFloatValue());
537     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
538         mat->setShininess(Material::BACK, shininess->getFloatValue());
539     Material::ColorMode colorMode = Material::OFF;
540     findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
541              colorMode);
542     mat->setColorMode(colorMode);
543     pass->setAttribute(mat);
544 }
545
546 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
547
548 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
549 {
550     {"dst-alpha", BlendFunc::DST_ALPHA},
551     {"dst-color", BlendFunc::DST_COLOR},
552     {"one", BlendFunc::ONE},
553     {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
554     {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
555     {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
556     {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
557     {"src-alpha", BlendFunc::SRC_ALPHA},
558     {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
559     {"src-color", BlendFunc::SRC_COLOR},
560     {"constant-color", BlendFunc::CONSTANT_COLOR},
561     {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
562     {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
563     {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
564     {"zero", BlendFunc::ZERO}
565 };
566 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
567
568 struct BlendBuilder : public PassAttributeBuilder
569 {
570     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
571                         const SGReaderWriterOptions* options)
572     {
573         if (!isAttributeActive(effect, prop))
574             return;
575         // XXX Compatibility with early <blend> syntax; should go away
576         // before a release
577         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
578         if (!realProp)
579             return;
580         if (realProp->nChildren() == 0) {
581             pass->setMode(GL_BLEND, (realProp->getBoolValue()
582                                      ? StateAttribute::ON
583                                      : StateAttribute::OFF));
584             return;
585         }
586
587         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
588                                                              "mode");
589         // XXX When dynamic parameters are supported, this code should
590         // create the blend function even if the mode is off.
591         if (pmode && !pmode->getValue<bool>()) {
592             pass->setMode(GL_BLEND, StateAttribute::OFF);
593             return;
594         }
595
596         parseBlendFunc(
597           pass,
598           getEffectPropertyChild(effect, prop, "source"),
599           getEffectPropertyChild(effect, prop, "destination"),
600           getEffectPropertyChild(effect, prop, "source-rgb"),
601           getEffectPropertyChild(effect, prop, "destination-rgb"),
602           getEffectPropertyChild(effect, prop, "source-alpha"),
603           getEffectPropertyChild(effect, prop, "destination-alpha")
604         );
605     }
606 };
607
608 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
609
610
611 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
612 {
613     {"never", Stencil::NEVER },
614     {"less", Stencil::LESS},
615     {"equal", Stencil::EQUAL},
616     {"less-or-equal", Stencil::LEQUAL},
617     {"greater", Stencil::GREATER},
618     {"not-equal", Stencil::NOTEQUAL},
619     {"greater-or-equal", Stencil::GEQUAL},
620     {"always", Stencil::ALWAYS}
621 };
622
623 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
624
625 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
626 {
627     {"keep", Stencil::KEEP},
628     {"zero", Stencil::ZERO},
629     {"replace", Stencil::REPLACE},
630     {"increase", Stencil::INCR},
631     {"decrease", Stencil::DECR},
632     {"invert", Stencil::INVERT},
633     {"increase-wrap", Stencil::INCR_WRAP},
634     {"decrease-wrap", Stencil::DECR_WRAP}
635 };
636
637 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
638
639 struct StencilBuilder : public PassAttributeBuilder
640 {
641     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
642                         const SGReaderWriterOptions* options)
643     {
644         if (!isAttributeActive(effect, prop))
645             return;
646
647         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
648                                                              "mode");
649         if (pmode && !pmode->getValue<bool>()) {
650             pass->setMode(GL_STENCIL, StateAttribute::OFF);
651             return;
652         }
653         const SGPropertyNode* pfunction
654             = getEffectPropertyChild(effect, prop, "function");
655         const SGPropertyNode* pvalue
656             = getEffectPropertyChild(effect, prop, "value");
657         const SGPropertyNode* pmask
658             = getEffectPropertyChild(effect, prop, "mask");
659         const SGPropertyNode* psfail
660             = getEffectPropertyChild(effect, prop, "stencil-fail");
661         const SGPropertyNode* pzfail
662             = getEffectPropertyChild(effect, prop, "z-fail");
663         const SGPropertyNode* ppass
664             = getEffectPropertyChild(effect, prop, "pass");
665
666         Stencil::Function func = Stencil::ALWAYS;  // Always pass
667         int ref = 0;
668         unsigned int mask = ~0u;  // All bits on
669         Stencil::Operation sfailop = Stencil::KEEP;  // Keep the old values as default
670         Stencil::Operation zfailop = Stencil::KEEP;
671         Stencil::Operation passop = Stencil::KEEP;
672
673         ref_ptr<Stencil> stencilFunc = new Stencil;
674
675         if (pfunction)
676             findAttr(stencilFunction, pfunction, func);
677         if (pvalue)
678             ref = pvalue->getIntValue();
679         if (pmask)
680             mask = pmask->getIntValue();
681
682         if (psfail)
683             findAttr(stencilOperation, psfail, sfailop);
684         if (pzfail)
685             findAttr(stencilOperation, pzfail, zfailop);
686         if (ppass)
687             findAttr(stencilOperation, ppass, passop);
688
689         // Set the stencil operation
690         stencilFunc->setFunction(func, ref, mask);
691
692         // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
693         stencilFunc->setOperation(sfailop, zfailop, passop);
694
695         // Add the operation to pass
696         pass->setAttributeAndModes(stencilFunc.get());
697     }
698 };
699
700 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
701
702 struct AlphaToCoverageBuilder : public PassAttributeBuilder
703 {
704     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
705                         const SGReaderWriterOptions* options);
706 };
707
708 #ifndef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
709 #define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
710 #endif
711
712 void AlphaToCoverageBuilder::buildAttribute(Effect* effect, Pass* pass,
713                                      const SGPropertyNode* prop,
714                                      const SGReaderWriterOptions* options)
715 {
716     const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
717     if (!realProp)
718         return;
719     pass->setMode(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB, (realProp->getValue<bool>() ?
720                                     StateAttribute::ON : StateAttribute::OFF));
721 }
722
723 InstallAttributeBuilder<AlphaToCoverageBuilder> installAlphaToCoverage("alpha-to-coverage");
724
725 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
726 {
727     {"never", AlphaFunc::NEVER},
728     {"less", AlphaFunc::LESS},
729     {"equal", AlphaFunc::EQUAL},
730     {"lequal", AlphaFunc::LEQUAL},
731     {"greater", AlphaFunc::GREATER},
732     {"notequal", AlphaFunc::NOTEQUAL},
733     {"gequal", AlphaFunc::GEQUAL},
734     {"always", AlphaFunc::ALWAYS}
735 };
736 EffectPropertyMap<AlphaFunc::ComparisonFunction>
737 alphaComparison(alphaComparisonInit);
738
739 struct AlphaTestBuilder : public PassAttributeBuilder
740 {
741     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
742                         const SGReaderWriterOptions* options)
743     {
744         if (!isAttributeActive(effect, prop))
745             return;
746         // XXX Compatibility with early <alpha-test> syntax; should go away
747         // before a release
748         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
749         if (!realProp)
750             return;
751         if (realProp->nChildren() == 0) {
752             pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
753                                      ? StateAttribute::ON
754                                      : StateAttribute::OFF));
755             return;
756         }
757
758         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
759                                                              "mode");
760         // XXX When dynamic parameters are supported, this code should
761         // create the blend function even if the mode is off.
762         if (pmode && !pmode->getValue<bool>()) {
763             pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
764             return;
765         }
766         const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
767                                                              "comparison");
768         const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
769                                                              "reference");
770
771         AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
772         float refValue = 1.0f;
773         if (pComp)
774             findAttr(alphaComparison, pComp, func);
775         if (pRef)
776             refValue = pRef->getValue<float>();
777         if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
778             pass->setAttributeAndModes(StateAttributeFactory::instance()
779                                        ->getStandardAlphaFunc());
780         } else {
781             AlphaFunc* alphaFunc = new AlphaFunc;
782             alphaFunc->setFunction(func);
783             alphaFunc->setReferenceValue(refValue);
784             pass->setAttributeAndModes(alphaFunc);
785         }
786     }
787 };
788
789 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
790
791 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
792
793 // Shader key, used both for shaders with relative and absolute names
794 typedef pair<string, int> ShaderKey;
795
796 inline ShaderKey makeShaderKey(SGPropertyNode_ptr& ptr, int shaderType)
797 {
798     return ShaderKey(ptr->getStringValue(), shaderType);
799 }
800
801 struct ProgramKey
802 {
803     typedef pair<string, int> AttribKey;
804     osgDB::FilePathList paths;
805     vector<ShaderKey> shaders;
806     vector<AttribKey> attributes;
807     struct EqualTo
808     {
809         bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
810         {
811             return (lhs.paths.size() == rhs.paths.size()
812                     && equal(lhs.paths.begin(), lhs.paths.end(),
813                              rhs.paths.begin())
814                     && lhs.shaders.size() == rhs.shaders.size()
815                     && equal (lhs.shaders.begin(), lhs.shaders.end(),
816                               rhs.shaders.begin())
817                     && lhs.attributes.size() == rhs.attributes.size()
818                     && equal(lhs.attributes.begin(), lhs.attributes.end(),
819                              rhs.attributes.begin()));
820         }
821     };
822 };
823
824 size_t hash_value(const ProgramKey& key)
825 {
826     size_t seed = 0;
827     boost::hash_range(seed, key.paths.begin(), key.paths.end());
828     boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
829     boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
830     return seed;
831 }
832
833 // XXX Should these be protected by a mutex? Probably
834
835 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
836                            boost::hash<ProgramKey>, ProgramKey::EqualTo>
837 ProgramMap;
838 ProgramMap programMap;
839 ProgramMap resolvedProgramMap;  // map with resolved shader file names
840
841 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
842 ShaderMap;
843 ShaderMap shaderMap;
844
845 void reload_shaders()
846 {
847     for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
848     {
849         Shader *shader = sitr->second.get();
850         string fileName = SGModelLib::findDataFile(sitr->first.first);
851         if (!fileName.empty()) {
852             shader->loadShaderSourceFromFile(fileName);
853         }
854     }
855 }
856
857 struct ShaderProgramBuilder : PassAttributeBuilder
858 {
859     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
860                         const SGReaderWriterOptions* options);
861 };
862
863
864 EffectNameValue<GLint> geometryInputTypeInit[] =
865 {
866     {"points", GL_POINTS},
867     {"lines", GL_LINES},
868     {"lines-adjacency", GL_LINES_ADJACENCY_EXT},
869     {"triangles", GL_TRIANGLES},
870     {"triangles-adjacency", GL_TRIANGLES_ADJACENCY_EXT},
871 };
872 EffectPropertyMap<GLint>
873 geometryInputType(geometryInputTypeInit);
874
875
876 EffectNameValue<GLint> geometryOutputTypeInit[] =
877 {
878     {"points", GL_POINTS},
879     {"line-strip", GL_LINE_STRIP},
880     {"triangle-strip", GL_TRIANGLE_STRIP}
881 };
882 EffectPropertyMap<GLint>
883 geometryOutputType(geometryOutputTypeInit);
884
885 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
886                                           const SGPropertyNode* prop,
887                                           const SGReaderWriterOptions*
888                                           options)
889 {
890     using namespace boost;
891     if (!isAttributeActive(effect, prop))
892         return;
893     PropertyList pVertShaders = prop->getChildren("vertex-shader");
894     PropertyList pGeomShaders = prop->getChildren("geometry-shader");
895     PropertyList pFragShaders = prop->getChildren("fragment-shader");
896     PropertyList pAttributes = prop->getChildren("attribute");
897     ProgramKey prgKey;
898     std::back_insert_iterator<vector<ShaderKey> > inserter(prgKey.shaders);
899     transform(pVertShaders.begin(), pVertShaders.end(), inserter,
900               boost::bind(makeShaderKey, _1, Shader::VERTEX));
901     transform(pGeomShaders.begin(), pGeomShaders.end(), inserter,
902               boost::bind(makeShaderKey, _1, Shader::GEOMETRY));
903     transform(pFragShaders.begin(), pFragShaders.end(), inserter,
904               boost::bind(makeShaderKey, _1, Shader::FRAGMENT));
905     for (PropertyList::iterator itr = pAttributes.begin(),
906              e = pAttributes.end();
907          itr != e;
908          ++itr) {
909         const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
910                                                              "name");
911         const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
912                                                               "index");
913         if (!pName || ! pIndex)
914             throw BuilderException("malformed attribute property");
915         prgKey.attributes
916             .push_back(ProgramKey::AttribKey(pName->getStringValue(),
917                                              pIndex->getValue<int>()));
918     }
919     if (options)
920         prgKey.paths = options->getDatabasePathList();
921     Program* program = 0;
922     ProgramMap::iterator pitr = programMap.find(prgKey);
923     if (pitr != programMap.end()) {
924         program = pitr->second.get();
925         pass->setAttributeAndModes(program);
926         return;
927     }
928     // The program wasn't in the map using the load path passed in with
929     // the options, but it might have already been loaded using a
930     // different load path i.e., its shaders were found in the fg data
931     // directory. So, resolve the shaders' file names and look in the
932     // resolvedProgramMap for a program using those shaders.
933     ProgramKey resolvedKey;
934     resolvedKey.attributes = prgKey.attributes;
935     BOOST_FOREACH(const ShaderKey& shaderKey, prgKey.shaders)
936     {
937         const string& shaderName = shaderKey.first;
938         Shader::Type stype = (Shader::Type)shaderKey.second;
939         string fileName = SGModelLib::findDataFile(shaderName, options);
940         if (fileName.empty())
941             throw BuilderException(string("couldn't find shader ") +
942                                    shaderName);
943         resolvedKey.shaders.push_back(ShaderKey(fileName, stype));
944     }
945     ProgramMap::iterator resitr = resolvedProgramMap.find(resolvedKey);
946     if (resitr != resolvedProgramMap.end()) {
947         program = resitr->second.get();
948         programMap.insert(ProgramMap::value_type(prgKey, program));
949         pass->setAttributeAndModes(program);
950         return;
951     }
952     program = new Program;
953     BOOST_FOREACH(const ShaderKey& skey, resolvedKey.shaders)
954     {
955         const string& fileName = skey.first;
956         Shader::Type stype = (Shader::Type)skey.second;
957         ShaderMap::iterator sitr = shaderMap.find(skey);
958         if (sitr != shaderMap.end()) {
959             program->addShader(sitr->second.get());
960         } else {
961             ref_ptr<Shader> shader = new Shader(stype);
962                         shader->setName(fileName);
963             if (shader->loadShaderSourceFromFile(fileName)) {
964                 program->addShader(shader.get());
965                 shaderMap.insert(ShaderMap::value_type(skey, shader));
966             }
967         }
968     }
969     BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
970         program->addBindAttribLocation(key.first, key.second);
971     }
972     const SGPropertyNode* pGeometryVerticesOut
973         = getEffectPropertyChild(effect, prop, "geometry-vertices-out");
974     if (pGeometryVerticesOut)
975         program->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT,
976                               pGeometryVerticesOut->getIntValue());
977     const SGPropertyNode* pGeometryInputType
978         = getEffectPropertyChild(effect, prop, "geometry-input-type");
979     if (pGeometryInputType) {
980         GLint type;
981         findAttr(geometryInputType, pGeometryInputType->getStringValue(), type);
982         program->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT, type);
983     }
984     const SGPropertyNode* pGeometryOutputType
985         = getEffectPropertyChild(effect, prop, "geometry-output-type");
986     if (pGeometryOutputType) {
987         GLint type;
988         findAttr(geometryOutputType, pGeometryOutputType->getStringValue(),
989                  type);
990         program->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, type);
991     }
992     programMap.insert(ProgramMap::value_type(prgKey, program));
993     resolvedProgramMap.insert(ProgramMap::value_type(resolvedKey, program));
994     pass->setAttributeAndModes(program);
995 }
996
997 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
998
999 EffectNameValue<Uniform::Type> uniformTypesInit[] =
1000 {
1001     {"bool", Uniform::BOOL},
1002     {"int", Uniform::INT},
1003     {"float", Uniform::FLOAT},
1004     {"float-vec3", Uniform::FLOAT_VEC3},
1005     {"float-vec4", Uniform::FLOAT_VEC4},
1006     {"sampler-1d", Uniform::SAMPLER_1D},
1007     {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
1008     {"sampler-2d", Uniform::SAMPLER_2D},
1009     {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
1010     {"sampler-3d", Uniform::SAMPLER_3D},
1011     {"sampler-cube", Uniform::SAMPLER_CUBE}
1012 };
1013 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
1014
1015 // Optimization hack for common uniforms.
1016 // XXX protect these with a mutex?
1017
1018 ref_ptr<Uniform> texture0;
1019 ref_ptr<Uniform> colorMode[3];
1020
1021 struct UniformBuilder :public PassAttributeBuilder
1022 {
1023     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1024                         const SGReaderWriterOptions* options)
1025     {
1026         if (!texture0.valid()) {
1027             texture0 = new Uniform(Uniform::SAMPLER_2D, "texture");
1028             texture0->set(0);
1029             texture0->setDataVariance(Object::STATIC);
1030             for (int i = 0; i < 3; ++i) {
1031                 colorMode[i] = new Uniform(Uniform::INT, "colorMode");
1032                 colorMode[i]->set(i);
1033                 colorMode[i]->setDataVariance(Object::STATIC);
1034             }
1035         }
1036         if (!isAttributeActive(effect, prop))
1037             return;
1038         SGConstPropertyNode_ptr nameProp = prop->getChild("name");
1039         SGConstPropertyNode_ptr typeProp = prop->getChild("type");
1040         SGConstPropertyNode_ptr positionedProp = prop->getChild("positioned");
1041         SGConstPropertyNode_ptr valProp = prop->getChild("value");
1042         string name;
1043         Uniform::Type uniformType = Uniform::FLOAT;
1044         if (nameProp) {
1045             name = nameProp->getStringValue();
1046         } else {
1047             SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
1048             return;
1049         }
1050         if (!valProp) {
1051             SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
1052                    << name);
1053             return;
1054         }
1055         if (!typeProp) {
1056             props::Type propType = valProp->getType();
1057             switch (propType) {
1058             case props::BOOL:
1059                 uniformType = Uniform::BOOL;
1060                 break;
1061             case props::INT:
1062                 uniformType = Uniform::INT;
1063                 break;
1064             case props::FLOAT:
1065             case props::DOUBLE:
1066                 break;          // default float type;
1067             case props::VEC3D:
1068                 uniformType = Uniform::FLOAT_VEC3;
1069                 break;
1070             case props::VEC4D:
1071                 uniformType = Uniform::FLOAT_VEC4;
1072                 break;
1073             default:
1074                 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
1075                        << name);
1076                 return;
1077             }
1078         } else {
1079             findAttr(uniformTypes, typeProp, uniformType);
1080         }
1081         ref_ptr<Uniform> uniform = UniformFactory::instance()->
1082           getUniform( effect, name, uniformType, valProp, options );
1083
1084         // optimize common uniforms
1085         if (uniformType == Uniform::SAMPLER_2D || uniformType == Uniform::INT)
1086         {
1087             int val = 0;
1088             uniform->get(val); // 'val' remains unchanged in case of error (Uniform is a non-scalar)
1089             if (uniformType == Uniform::SAMPLER_2D && val == 0
1090                 && name == "texture") {
1091                 uniform = texture0;
1092             } else if (uniformType == Uniform::INT && val >= 0 && val < 3
1093                        && name == "colorMode") {
1094                 uniform = colorMode[val];
1095             }
1096         }
1097         pass->addUniform(uniform.get());
1098         if (positionedProp && positionedProp->getBoolValue() && uniformType == Uniform::FLOAT_VEC4) {
1099             osg::Vec4 offset;
1100             uniform->get(offset);
1101             pass->addPositionedUniform( name, offset );
1102         }
1103     }
1104 };
1105
1106 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
1107
1108 // Not sure what to do with "name". At one point I wanted to use it to
1109 // order the passes, but I do support render bin and stuff too...
1110 // Clément de l'Hamaide 10/2014: "name" is now used in the UniformCacheKey
1111
1112 struct NameBuilder : public PassAttributeBuilder
1113 {
1114     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1115                         const SGReaderWriterOptions* options)
1116     {
1117         // name can't use <use>
1118         string name = prop->getStringValue();
1119         if (!name.empty())
1120             pass->setName(name);
1121     }
1122 };
1123
1124 InstallAttributeBuilder<NameBuilder> installName("name");
1125
1126 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
1127 {
1128     {"fill", PolygonMode::FILL},
1129     {"line", PolygonMode::LINE},
1130     {"point", PolygonMode::POINT}
1131 };
1132 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
1133
1134 struct PolygonModeBuilder : public PassAttributeBuilder
1135 {
1136     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1137                         const SGReaderWriterOptions* options)
1138     {
1139         if (!isAttributeActive(effect, prop))
1140             return;
1141         const SGPropertyNode* frontProp
1142             = getEffectPropertyChild(effect, prop, "front");
1143         const SGPropertyNode* backProp
1144             = getEffectPropertyChild(effect, prop, "back");
1145         ref_ptr<PolygonMode> pmode = new PolygonMode;
1146         PolygonMode::Mode frontMode = PolygonMode::FILL;
1147         PolygonMode::Mode backMode = PolygonMode::FILL;
1148         if (frontProp) {
1149             findAttr(polygonModeModes, frontProp, frontMode);
1150             pmode->setMode(PolygonMode::FRONT, frontMode);
1151         }
1152         if (backProp) {
1153             findAttr(polygonModeModes, backProp, backMode);
1154             pmode->setMode(PolygonMode::BACK, backMode);
1155         }
1156         pass->setAttribute(pmode.get());
1157     }
1158 };
1159
1160 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1161
1162 struct PolygonOffsetBuilder : public PassAttributeBuilder
1163 {
1164     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1165                         const SGReaderWriterOptions* options)
1166     {
1167         if (!isAttributeActive(effect, prop))
1168             return;
1169
1170         const SGPropertyNode* factor
1171            = getEffectPropertyChild(effect, prop, "factor");
1172         const SGPropertyNode* units
1173            = getEffectPropertyChild(effect, prop, "units");
1174
1175         ref_ptr<PolygonOffset> polyoffset = new PolygonOffset;
1176
1177         polyoffset->setFactor(factor->getFloatValue());
1178         polyoffset->setUnits(units->getFloatValue());
1179
1180         SG_LOG(SG_INPUT, SG_BULK,
1181                    "Set PolygonOffset to " << polyoffset->getFactor() << polyoffset->getUnits() );
1182
1183         pass->setAttributeAndModes(polyoffset.get(),
1184                                    StateAttribute::OVERRIDE|StateAttribute::ON);
1185     }
1186 };
1187
1188 InstallAttributeBuilder<PolygonOffsetBuilder> installPolygonOffset("polygon-offset");
1189
1190 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1191 {
1192     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1193                         const SGReaderWriterOptions* options)
1194     {
1195         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1196         if (!realProp)
1197             return;
1198         pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1199                       (realProp->getValue<bool>()
1200                        ? StateAttribute::ON : StateAttribute::OFF));
1201     }
1202 };
1203
1204 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1205 installTwoSide("vertex-program-two-side");
1206
1207 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1208 {
1209     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1210                         const SGReaderWriterOptions* options)
1211     {
1212         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1213         if (!realProp)
1214             return;
1215         pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1216                       (realProp->getValue<bool>()
1217                        ? StateAttribute::ON : StateAttribute::OFF));
1218     }
1219 };
1220
1221 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1222 installPointSize("vertex-program-point-size");
1223
1224 struct PointBuilder : public PassAttributeBuilder
1225 {
1226     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1227                         const SGReaderWriterOptions* options)
1228     {
1229         float minsize = 1.0;
1230         float maxsize = 1.0;
1231         float size    = 1.0;
1232         osg::Vec3f attenuation = osg::Vec3f(1.0, 1.0, 1.0);
1233
1234         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1235         if (!realProp)
1236             return;
1237
1238         const SGPropertyNode* pminsize
1239             = getEffectPropertyChild(effect, prop, "min-size");
1240         const SGPropertyNode* pmaxsize
1241             = getEffectPropertyChild(effect, prop, "max-size");
1242         const SGPropertyNode* psize
1243             = getEffectPropertyChild(effect, prop, "size");
1244         const SGPropertyNode* pattenuation
1245             = getEffectPropertyChild(effect, prop, "attenuation");
1246
1247         if (pminsize)
1248             minsize = pminsize->getFloatValue();
1249         if (pmaxsize)
1250             maxsize = pmaxsize->getFloatValue();
1251         if (psize)
1252             size = psize->getFloatValue();
1253         if (pattenuation)
1254             attenuation = osg::Vec3f(pattenuation->getChild("x")->getFloatValue(),
1255                                      pattenuation->getChild("y")->getFloatValue(),
1256                                      pattenuation->getChild("z")->getFloatValue());
1257
1258         osg::Point* point = new osg::Point;
1259         point->setMinSize(minsize);
1260         point->setMaxSize(maxsize);
1261         point->setSize(size);
1262         point->setDistanceAttenuation(attenuation);
1263         pass->setAttributeAndModes(point);
1264     }
1265 };
1266
1267 InstallAttributeBuilder<PointBuilder>
1268 installPoint("point");
1269
1270 EffectNameValue<Depth::Function> depthFunctionInit[] =
1271 {
1272     {"never", Depth::NEVER},
1273     {"less", Depth::LESS},
1274     {"equal", Depth::EQUAL},
1275     {"lequal", Depth::LEQUAL},
1276     {"greater", Depth::GREATER},
1277     {"notequal", Depth::NOTEQUAL},
1278     {"gequal", Depth::GEQUAL},
1279     {"always", Depth::ALWAYS}
1280 };
1281 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1282
1283 struct DepthBuilder : public PassAttributeBuilder
1284 {
1285     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1286                         const SGReaderWriterOptions* options)
1287     {
1288         if (!isAttributeActive(effect, prop))
1289             return;
1290         ref_ptr<Depth> depth = new Depth;
1291         const SGPropertyNode* pfunc
1292             = getEffectPropertyChild(effect, prop, "function");
1293         if (pfunc) {
1294             Depth::Function func = Depth::LESS;
1295             findAttr(depthFunction, pfunc, func);
1296             depth->setFunction(func);
1297         }
1298         const SGPropertyNode* pnear
1299             = getEffectPropertyChild(effect, prop, "near");
1300         if (pnear)
1301             depth->setZNear(pnear->getValue<double>());
1302         const SGPropertyNode* pfar
1303             = getEffectPropertyChild(effect, prop, "far");
1304         if (pfar)
1305             depth->setZFar(pfar->getValue<double>());
1306         const SGPropertyNode* pmask
1307             = getEffectPropertyChild(effect, prop, "write-mask");
1308         if (pmask)
1309             depth->setWriteMask(pmask->getValue<bool>());
1310         const SGPropertyNode* penabled
1311             = getEffectPropertyChild(effect, prop, "enabled");
1312         bool enabled = ( penabled == 0 || penabled->getBoolValue() );
1313         pass->setAttributeAndModes(depth.get(), enabled ? osg::StateAttribute::ON : osg::StateAttribute::OFF);
1314     }
1315 };
1316
1317 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1318
1319 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1320                     const SGReaderWriterOptions* options)
1321 {
1322     Technique* tniq = new Technique;
1323     effect->techniques.push_back(tniq);
1324     const SGPropertyNode* predProp = prop->getChild("predicate");
1325     if (!predProp) {
1326         tniq->setAlwaysValid(true);
1327     } else {
1328         try {
1329             TechniquePredParser parser;
1330             parser.setTechnique(tniq);
1331             expression::BindingLayout& layout = parser.getBindingLayout();
1332             /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1333             SGExpressionb* validExp
1334                 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1335                                                            ->getChild(0)));
1336             if (validExp)
1337                 tniq->setValidExpression(validExp, layout);
1338             else
1339                 throw expression::ParseError("technique predicate is not a boolean expression");
1340         }
1341         catch (expression::ParseError& except)
1342         {
1343             SG_LOG(SG_INPUT, SG_ALERT,
1344                    "parsing technique predicate " << except.getMessage());
1345             tniq->setAlwaysValid(false);
1346         }
1347     }
1348     PropertyList passProps = prop->getChildren("pass");
1349     for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1350          itr != e;
1351          ++itr) {
1352         buildPass(effect, tniq, itr->ptr(), options);
1353     }
1354 }
1355
1356 // Specifically for .ac files...
1357 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1358 {
1359     SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1360     SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1361     Vec4f ambVal, difVal, specVal, emisVal;
1362     float shininess = 0.0f;
1363     const Material* mat = getStateAttribute<Material>(ss);
1364     if (mat) {
1365         ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1366         difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1367         specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1368         emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1369         shininess = mat->getShininess(Material::FRONT_AND_BACK);
1370         makeChild(matNode, "active")->setValue(true);
1371         makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1372         makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1373         makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1374         makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1375         makeChild(matNode, "shininess")->setValue(shininess);
1376         matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1377     } else {
1378         makeChild(matNode, "active")->setValue(false);
1379     }
1380     const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1381     string shadeModelString("smooth");
1382     if (sm) {
1383         ShadeModel::Mode smMode = sm->getMode();
1384         if (smMode == ShadeModel::FLAT)
1385             shadeModelString = "flat";
1386     }
1387     makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1388     string cullFaceString("off");
1389     const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1390     if (cullFace) {
1391         switch (cullFace->getMode()) {
1392         case CullFace::FRONT:
1393             cullFaceString = "front";
1394             break;
1395         case CullFace::BACK:
1396             cullFaceString = "back";
1397             break;
1398         case CullFace::FRONT_AND_BACK:
1399             cullFaceString = "front-back";
1400             break;
1401         default:
1402             break;
1403         }
1404     }
1405     makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1406     // Macintosh ATI workaround
1407     bool vertexTwoSide = cullFaceString == "off";
1408     makeChild(paramRoot, "vertex-program-two-side")->setValue(vertexTwoSide);
1409     const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1410     SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1411     if (blendFunc) {
1412         string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1413         string destMode = findName(blendFuncModes, blendFunc->getDestination());
1414         makeChild(blendNode, "active")->setValue(true);
1415         makeChild(blendNode, "source")->setStringValue(sourceMode);
1416         makeChild(blendNode, "destination")->setStringValue(destMode);
1417         makeChild(blendNode, "mode")->setValue(true);
1418     } else {
1419         makeChild(blendNode, "active")->setValue(false);
1420     }
1421     string renderingHint = findName(renderingHints, ss->getRenderingHint());
1422     makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1423     makeTextureParameters(paramRoot, ss);
1424     return true;
1425 }
1426
1427 // Walk the techniques property tree, building techniques and
1428 // passes.
1429 bool Effect::realizeTechniques(const SGReaderWriterOptions* options)
1430 {
1431     if (_isRealized)
1432         return true;
1433     PropertyList tniqList = root->getChildren("technique");
1434     for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1435          itr != e;
1436          ++itr)
1437         buildTechnique(this, *itr, options);
1438     _isRealized = true;
1439     return true;
1440 }
1441
1442 void Effect::addDeferredPropertyListener(DeferredPropertyListener* listener)
1443 {
1444         UniformFactory::instance()->addListener(listener);
1445 }
1446
1447 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1448 {
1449     EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1450     if (!eg)
1451         return;
1452     Effect* effect = eg->getEffect();
1453     if (!effect)
1454         return;
1455     SGPropertyNode* root = getPropertyRoot();
1456
1457     // Initialize all queued listeners
1458     UniformFactory::instance()->updateListeners(root);
1459 }
1460
1461 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1462                                       const Effect::Key& rhs) const
1463 {
1464     if (lhs.paths.size() != rhs.paths.size()
1465         || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1466         return false;
1467     if (lhs.unmerged.valid() && rhs.unmerged.valid())
1468         return props::Compare()(lhs.unmerged, rhs.unmerged);
1469     else
1470         return lhs.unmerged == rhs.unmerged;
1471 }
1472
1473 size_t hash_value(const Effect::Key& key)
1474 {
1475     size_t seed = 0;
1476     if (key.unmerged.valid())
1477         boost::hash_combine(seed, *key.unmerged);
1478     boost::hash_range(seed, key.paths.begin(), key.paths.end());
1479     return seed;
1480 }
1481
1482 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1483 {
1484     const Effect& effect = static_cast<const Effect&>(obj);
1485
1486     fw.indent() << "techniques " << effect.techniques.size() << "\n";
1487     BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1488         fw.writeObject(*technique);
1489     }
1490     return true;
1491 }
1492
1493 namespace
1494 {
1495 osgDB::RegisterDotOsgWrapperProxy effectProxy
1496 (
1497     new Effect,
1498     "simgear::Effect",
1499     "Object simgear::Effect",
1500     0,
1501     &Effect_writeLocalData
1502     );
1503 }
1504
1505 // Property expressions for technique predicates
1506 template<typename T>
1507 class PropertyExpression : public SGExpression<T>
1508 {
1509 public:
1510     PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode), _listener(NULL) {}
1511
1512     ~PropertyExpression()
1513     {
1514         delete _listener;
1515     }
1516
1517     void eval(T& value, const expression::Binding*) const
1518     {
1519         value = _pnode->getValue<T>();
1520     }
1521
1522     void setListener(SGPropertyChangeListener* l)
1523     {
1524         _listener = l;
1525     }
1526 protected:
1527     SGPropertyNode_ptr _pnode;
1528     SGPropertyChangeListener* _listener;
1529 };
1530
1531 class EffectPropertyListener : public SGPropertyChangeListener
1532 {
1533 public:
1534     EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1535
1536     void valueChanged(SGPropertyNode* node)
1537     {
1538         if (_tniq.valid())
1539             _tniq->refreshValidity();
1540     }
1541
1542     virtual ~EffectPropertyListener() { }
1543
1544 protected:
1545     osg::observer_ptr<Technique> _tniq;
1546 };
1547
1548 template<typename T>
1549 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1550                                      expression::Parser* parser)
1551 {
1552     SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1553                                                           true);
1554     PropertyExpression<T>* pexp = new PropertyExpression<T>(pnode);
1555     TechniquePredParser* predParser
1556         = dynamic_cast<TechniquePredParser*>(parser);
1557     if (predParser) {
1558         EffectPropertyListener* l = new EffectPropertyListener(predParser
1559                                                                ->getTechnique());
1560         pexp->setListener(l);
1561         pnode->addChangeListener(l);
1562     }
1563     return pexp;
1564 }
1565
1566 expression::ExpParserRegistrar propertyRegistrar("property",
1567                                                  propertyExpressionParser<bool>);
1568
1569 expression::ExpParserRegistrar propvalueRegistrar("float-property",
1570                                                  propertyExpressionParser<float>);
1571
1572 }