]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/Effect.cxx
c3976d81039ad9e512dc45115939b9345ed5bcb2
[simgear.git] / simgear / scene / material / Effect.cxx
1 // Copyright (C) 2008 - 2009  Tim Moore timoore@redhat.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
28 #include <algorithm>
29 #include <functional>
30 #include <iterator>
31 #include <map>
32 #include <utility>
33 #include <boost/tr1/unordered_map.hpp>
34
35 #include <boost/bind.hpp>
36 #include <boost/foreach.hpp>
37 #include <boost/functional/hash.hpp>
38 #include <boost/tuple/tuple.hpp>
39 #include <boost/tuple/tuple_comparison.hpp>
40
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
43 #include <osg/CullFace>
44 #include <osg/Depth>
45 #include <osg/Drawable>
46 #include <osg/Material>
47 #include <osg/Math>
48 #include <osg/PolygonMode>
49 #include <osg/Program>
50 #include <osg/Referenced>
51 #include <osg/RenderInfo>
52 #include <osg/ShadeModel>
53 #include <osg/StateSet>
54 #include <osg/Stencil>
55 #include <osg/TexEnv>
56 #include <osg/Texture1D>
57 #include <osg/Texture2D>
58 #include <osg/Texture3D>
59 #include <osg/TextureRectangle>
60 #include <osg/Uniform>
61 #include <osg/Vec4d>
62 #include <osgUtil/CullVisitor>
63 #include <osgDB/FileUtils>
64 #include <osgDB/Input>
65 #include <osgDB/ParameterOutput>
66 #include <osgDB/ReadFile>
67 #include <osgDB/Registry>
68
69 #include <simgear/scene/model/SGReaderWriterXMLOptions.hxx>
70 #include <simgear/scene/tgdb/userdata.hxx>
71 #include <simgear/scene/util/SGSceneFeatures.hxx>
72 #include <simgear/scene/util/StateAttributeFactory.hxx>
73 #include <simgear/structure/OSGUtils.hxx>
74 #include <simgear/structure/SGExpression.hxx>
75
76
77
78 namespace simgear
79 {
80 using namespace std;
81 using namespace osg;
82 using namespace osgUtil;
83
84 using namespace effect;
85
86 Effect::Effect()
87     : _cache(0), _isRealized(false)
88 {
89 }
90
91 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
92     : root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
93       _isRealized(rhs._isRealized)
94 {
95     typedef vector<ref_ptr<Technique> > TechniqueList;
96     for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
97              end = rhs.techniques.end();
98          itr != end;
99          ++itr)
100         techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
101
102     generator = rhs.generator;
103 }
104
105 // Assume that the last technique is always valid.
106 StateSet* Effect::getDefaultStateSet()
107 {
108     Technique* tniq = techniques.back().get();
109     if (!tniq)
110         return 0;
111     Pass* pass = tniq->passes.front().get();
112     return pass;
113 }
114
115 int Effect::getGenerator(Effect::Generator what) const
116 {
117     std::map<Generator,int>::const_iterator it = generator.find(what);
118     if(it == generator.end()) return -1;
119     else return it->second;
120 }
121
122 // There should always be a valid technique in an effect.
123
124 Technique* Effect::chooseTechnique(RenderInfo* info)
125 {
126     BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
127     {
128         if (technique->valid(info) == Technique::VALID)
129             return technique.get();
130     }
131     return 0;
132 }
133
134 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
135 {
136     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
137     {
138         technique->resizeGLObjectBuffers(maxSize);
139     }
140 }
141
142 void Effect::releaseGLObjects(osg::State* state) const
143 {
144     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
145     {
146         technique->releaseGLObjects(state);
147     }
148 }
149
150 Effect::~Effect()
151 {
152     delete _cache;
153 }
154
155 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
156                const SGReaderWriterXMLOptions* options)
157 {
158     Pass* pass = new Pass;
159     tniq->passes.push_back(pass);
160     for (int i = 0; i < prop->nChildren(); ++i) {
161         const SGPropertyNode* attrProp = prop->getChild(i);
162         PassAttributeBuilder* builder
163             = PassAttributeBuilder::find(attrProp->getNameString());
164         if (builder)
165             builder->buildAttribute(effect, pass, attrProp, options);
166         else
167             SG_LOG(SG_INPUT, SG_ALERT,
168                    "skipping unknown pass attribute " << attrProp->getName());
169     }
170 }
171
172 // Default names for vector property components
173 const char* vec3Names[] = {"x", "y", "z"};
174 const char* vec4Names[] = {"x", "y", "z", "w"};
175
176 osg::Vec4f getColor(const SGPropertyNode* prop)
177 {
178     if (prop->nChildren() == 0) {
179         if (prop->getType() == props::VEC4D) {
180             return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
181         } else if (prop->getType() == props::VEC3D) {
182             return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
183         } else {
184             SG_LOG(SG_INPUT, SG_ALERT,
185                    "invalid color property " << prop->getName() << " "
186                    << prop->getStringValue());
187             return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
188         }
189     } else {
190         osg::Vec4f result;
191         static const char* colors[] = {"r", "g", "b"};
192         for (int i = 0; i < 3; ++i) {
193             const SGPropertyNode* componentProp = prop->getChild(colors[i]);
194             result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
195         }
196         const SGPropertyNode* alphaProp = prop->getChild("a");
197         result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
198         return result;
199     }
200 }
201
202 struct LightingBuilder : public PassAttributeBuilder
203 {
204     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
205                         const SGReaderWriterXMLOptions* options);
206 };
207
208 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
209                                      const SGPropertyNode* prop,
210                                      const SGReaderWriterXMLOptions* options)
211 {
212     const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
213     if (!realProp)
214         return;
215     pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
216                                 : StateAttribute::OFF));
217 }
218
219 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
220
221 struct ShadeModelBuilder : public PassAttributeBuilder
222 {
223     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
224                         const SGReaderWriterXMLOptions* options)
225     {
226         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
227         if (!realProp)
228             return;
229         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
230         string propVal = realProp->getStringValue();
231         if (propVal == "flat")
232             pass->setAttribute(attrFact->getFlatShadeModel());
233         else if (propVal == "smooth")
234             pass->setAttribute(attrFact->getSmoothShadeModel());
235         else
236             SG_LOG(SG_INPUT, SG_ALERT,
237                    "invalid shade model property " << propVal);
238     }
239 };
240
241 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
242
243 struct CullFaceBuilder : PassAttributeBuilder
244 {
245     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
246                         const SGReaderWriterXMLOptions* options)
247     {
248         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
249         if (!realProp) {
250             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
251             return;
252         }
253         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
254         string propVal = realProp->getStringValue();
255         if (propVal == "front")
256             pass->setAttributeAndModes(attrFact->getCullFaceFront());
257         else if (propVal == "back")
258             pass->setAttributeAndModes(attrFact->getCullFaceBack());
259         else if (propVal == "front-back")
260             pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
261         else if (propVal == "off")
262             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
263         else
264             SG_LOG(SG_INPUT, SG_ALERT,
265                    "invalid cull face property " << propVal);            
266     }    
267 };
268
269 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
270
271 struct ColorMaskBuilder : PassAttributeBuilder
272 {
273     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
274                         const SGReaderWriterXMLOptions* options)
275     {
276         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
277         if (!realProp)
278             return;
279
280         ColorMask *mask = new ColorMask;
281         Vec4 m = getColor(realProp);
282         mask->setMask(m.r(), m.g(), m.b(), m.a());
283         pass->setAttributeAndModes(mask);
284     }    
285 };
286
287 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
288
289 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
290 {
291     { "default", StateSet::DEFAULT_BIN },
292     { "opaque", StateSet::OPAQUE_BIN },
293     { "transparent", StateSet::TRANSPARENT_BIN }
294 };
295
296 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
297
298 struct HintBuilder : public PassAttributeBuilder
299 {
300     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
301                         const SGReaderWriterXMLOptions* options)
302     {
303         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
304         if (!realProp)
305             return;
306         StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
307         findAttr(renderingHints, realProp, renderingHint);
308         pass->setRenderingHint(renderingHint);
309     }    
310 };
311
312 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
313
314 struct RenderBinBuilder : public PassAttributeBuilder
315 {
316     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
317                         const SGReaderWriterXMLOptions* options)
318     {
319         if (!isAttributeActive(effect, prop))
320             return;
321         const SGPropertyNode* binProp = prop->getChild("bin-number");
322         binProp = getEffectPropertyNode(effect, binProp);
323         const SGPropertyNode* nameProp = prop->getChild("bin-name");
324         nameProp = getEffectPropertyNode(effect, nameProp);
325         if (binProp && nameProp) {
326             pass->setRenderBinDetails(binProp->getIntValue(),
327                                       nameProp->getStringValue());
328         } else {
329             if (!binProp)
330                 SG_LOG(SG_INPUT, SG_ALERT,
331                        "No render bin number specified in render bin section");
332             if (!nameProp)
333                 SG_LOG(SG_INPUT, SG_ALERT,
334                        "No render bin name specified in render bin section");
335         }
336     }
337 };
338
339 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
340
341 struct MaterialBuilder : public PassAttributeBuilder
342 {
343     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
344                         const SGReaderWriterXMLOptions* options);
345 };
346
347 EffectNameValue<Material::ColorMode> colorModeInit[] =
348 {
349     { "ambient", Material::AMBIENT },
350     { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
351     { "diffuse", Material::DIFFUSE },
352     { "emissive", Material::EMISSION },
353     { "specular", Material::SPECULAR },
354     { "off", Material::OFF }
355 };
356 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
357
358 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
359                                      const SGPropertyNode* prop,
360                                      const SGReaderWriterXMLOptions* options)
361 {
362     if (!isAttributeActive(effect, prop))
363         return;
364     Material* mat = new Material;
365     const SGPropertyNode* color = 0;
366     if ((color = getEffectPropertyChild(effect, prop, "ambient")))
367         mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
368     if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
369         mat->setAmbient(Material::FRONT, getColor(color));
370     if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
371         mat->setAmbient(Material::BACK, getColor(color));
372     if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
373         mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
374     if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
375         mat->setDiffuse(Material::FRONT, getColor(color));
376     if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
377         mat->setDiffuse(Material::BACK, getColor(color));
378     if ((color = getEffectPropertyChild(effect, prop, "specular")))
379         mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
380     if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
381         mat->setSpecular(Material::FRONT, getColor(color));
382     if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
383         mat->setSpecular(Material::BACK, getColor(color));
384     if ((color = getEffectPropertyChild(effect, prop, "emissive")))
385         mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
386     if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
387         mat->setEmission(Material::FRONT, getColor(color));        
388     if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
389         mat->setEmission(Material::BACK, getColor(color));        
390     const SGPropertyNode* shininess = 0;
391     mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
392     if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
393         mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
394     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
395         mat->setShininess(Material::FRONT, shininess->getFloatValue());
396     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
397         mat->setShininess(Material::BACK, shininess->getFloatValue());
398     Material::ColorMode colorMode = Material::OFF;
399     findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
400              colorMode);
401     mat->setColorMode(colorMode);
402     pass->setAttribute(mat);
403 }
404
405 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
406
407 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
408 {
409     {"dst-alpha", BlendFunc::DST_ALPHA},
410     {"dst-color", BlendFunc::DST_COLOR},
411     {"one", BlendFunc::ONE},
412     {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
413     {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
414     {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
415     {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
416     {"src-alpha", BlendFunc::SRC_ALPHA},
417     {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
418     {"src-color", BlendFunc::SRC_COLOR},
419     {"constant-color", BlendFunc::CONSTANT_COLOR},
420     {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
421     {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
422     {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
423     {"zero", BlendFunc::ZERO}
424 };
425 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
426
427 struct BlendBuilder : public PassAttributeBuilder
428 {
429     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
430                         const SGReaderWriterXMLOptions* options)
431     {
432         if (!isAttributeActive(effect, prop))
433             return;
434         // XXX Compatibility with early <blend> syntax; should go away
435         // before a release
436         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
437         if (!realProp)
438             return;
439         if (realProp->nChildren() == 0) {
440             pass->setMode(GL_BLEND, (realProp->getBoolValue()
441                                      ? StateAttribute::ON
442                                      : StateAttribute::OFF));
443             return;
444         }
445
446         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
447                                                              "mode");
448         // XXX When dynamic parameters are supported, this code should
449         // create the blend function even if the mode is off.
450         if (pmode && !pmode->getValue<bool>()) {
451             pass->setMode(GL_BLEND, StateAttribute::OFF);
452             return;
453         }
454         const SGPropertyNode* psource
455             = getEffectPropertyChild(effect, prop, "source");
456         const SGPropertyNode* pdestination
457             = getEffectPropertyChild(effect, prop, "destination");
458         const SGPropertyNode* psourceRGB
459             = getEffectPropertyChild(effect, prop, "source-rgb");
460         const SGPropertyNode* psourceAlpha
461             = getEffectPropertyChild(effect, prop, "source-alpha");
462         const SGPropertyNode* pdestRGB
463             = getEffectPropertyChild(effect, prop, "destination-rgb");
464         const SGPropertyNode* pdestAlpha
465             = getEffectPropertyChild(effect, prop, "destination-alpha");
466         BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
467         BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
468         if (psource)
469             findAttr(blendFuncModes, psource, sourceMode);
470         if (pdestination)
471             findAttr(blendFuncModes, pdestination, destMode);
472         if (psource && pdestination
473             && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
474             && sourceMode == BlendFunc::SRC_ALPHA
475             && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
476             pass->setAttributeAndModes(StateAttributeFactory::instance()
477                                        ->getStandardBlendFunc());
478             return;
479         }
480         BlendFunc* blendFunc = new BlendFunc;
481         if (psource)
482             blendFunc->setSource(sourceMode);
483         if (pdestination)
484             blendFunc->setDestination(destMode);
485         if (psourceRGB) {
486             BlendFunc::BlendFuncMode sourceRGBMode;
487             findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
488             blendFunc->setSourceRGB(sourceRGBMode);
489         }
490         if (pdestRGB) {
491             BlendFunc::BlendFuncMode destRGBMode;
492             findAttr(blendFuncModes, pdestRGB, destRGBMode);
493             blendFunc->setDestinationRGB(destRGBMode);
494         }
495         if (psourceAlpha) {
496             BlendFunc::BlendFuncMode sourceAlphaMode;
497             findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
498             blendFunc->setSourceAlpha(sourceAlphaMode);
499         }
500         if (pdestAlpha) {
501             BlendFunc::BlendFuncMode destAlphaMode;
502             findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
503             blendFunc->setDestinationAlpha(destAlphaMode);
504         }
505         pass->setAttributeAndModes(blendFunc);
506     }
507 };
508
509 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
510
511
512 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
513 {
514     {"never", Stencil::NEVER },
515     {"less", Stencil::LESS},
516     {"equal", Stencil::EQUAL},
517     {"less-or-equal", Stencil::LEQUAL},
518     {"greater", Stencil::GREATER},
519     {"not-equal", Stencil::NOTEQUAL},
520     {"greater-or-equal", Stencil::GEQUAL},
521     {"always", Stencil::ALWAYS}
522 };
523
524 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
525
526 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
527 {
528     {"keep", Stencil::KEEP},
529     {"zero", Stencil::ZERO},
530     {"replace", Stencil::REPLACE},
531     {"increase", Stencil::INCR},
532     {"decrease", Stencil::DECR},
533     {"invert", Stencil::INVERT},
534     {"increase-wrap", Stencil::INCR_WRAP},
535     {"decrease-wrap", Stencil::DECR_WRAP}
536 };
537
538 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
539
540 struct StencilBuilder : public PassAttributeBuilder
541 {
542     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
543                         const SGReaderWriterXMLOptions* options)
544     {
545         if (!isAttributeActive(effect, prop))
546             return;
547
548         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
549                                                              "mode");
550         if (pmode && !pmode->getValue<bool>()) {
551             pass->setMode(GL_STENCIL, StateAttribute::OFF);
552             return;
553         }
554         const SGPropertyNode* pfunction
555             = getEffectPropertyChild(effect, prop, "function");
556         const SGPropertyNode* pvalue
557             = getEffectPropertyChild(effect, prop, "value");
558         const SGPropertyNode* pmask
559             = getEffectPropertyChild(effect, prop, "mask");
560         const SGPropertyNode* psfail
561             = getEffectPropertyChild(effect, prop, "stencil-fail");
562         const SGPropertyNode* pzfail
563             = getEffectPropertyChild(effect, prop, "z-fail");
564         const SGPropertyNode* ppass
565             = getEffectPropertyChild(effect, prop, "pass");
566
567         Stencil::Function func = Stencil::ALWAYS;  // Always pass
568         int ref = 0;
569         unsigned int mask = ~0u;  // All bits on
570         Stencil::Operation sfailop = Stencil::KEEP;  // Keep the old values as default
571         Stencil::Operation zfailop = Stencil::KEEP;
572         Stencil::Operation passop = Stencil::KEEP;
573
574         ref_ptr<Stencil> stencilFunc = new Stencil;
575
576         if (pfunction)
577             findAttr(stencilFunction, pfunction, func);
578         if (pvalue)
579             ref = pvalue->getIntValue();
580         if (pmask) 
581             mask = pmask->getIntValue();
582
583         if (psfail)
584             findAttr(stencilOperation, psfail, sfailop);
585         if (pzfail)
586             findAttr(stencilOperation, pzfail, zfailop);
587         if (ppass)
588             findAttr(stencilOperation, ppass, passop);
589
590         // Set the stencil operation
591         stencilFunc->setFunction(func, ref, mask);
592
593         // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
594         stencilFunc->setOperation(sfailop, zfailop, passop);
595
596         // Add the operation to pass
597         pass->setAttributeAndModes(stencilFunc.get());
598     }
599 };
600
601 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
602
603
604 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
605 {
606     {"never", AlphaFunc::NEVER},
607     {"less", AlphaFunc::LESS},
608     {"equal", AlphaFunc::EQUAL},
609     {"lequal", AlphaFunc::LEQUAL},
610     {"greater", AlphaFunc::GREATER},
611     {"notequal", AlphaFunc::NOTEQUAL},
612     {"gequal", AlphaFunc::GEQUAL},
613     {"always", AlphaFunc::ALWAYS}
614 };
615 EffectPropertyMap<AlphaFunc::ComparisonFunction>
616 alphaComparison(alphaComparisonInit);
617
618 struct AlphaTestBuilder : public PassAttributeBuilder
619 {
620     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
621                         const SGReaderWriterXMLOptions* options)
622     {
623         if (!isAttributeActive(effect, prop))
624             return;
625         // XXX Compatibility with early <alpha-test> syntax; should go away
626         // before a release
627         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
628         if (!realProp)
629             return;
630         if (realProp->nChildren() == 0) {
631             pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
632                                      ? StateAttribute::ON
633                                      : StateAttribute::OFF));
634             return;
635         }
636
637         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
638                                                              "mode");
639         // XXX When dynamic parameters are supported, this code should
640         // create the blend function even if the mode is off.
641         if (pmode && !pmode->getValue<bool>()) {
642             pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
643             return;
644         }
645         const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
646                                                              "comparison");
647         const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
648                                                              "reference");
649         AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
650         float refValue = 1.0f;
651         if (pComp)
652             findAttr(alphaComparison, pComp, func);
653         if (pRef)
654             refValue = pRef->getValue<float>();
655         if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
656             pass->setAttributeAndModes(StateAttributeFactory::instance()
657                                        ->getStandardAlphaFunc());
658         } else {
659             AlphaFunc* alphaFunc = new AlphaFunc;
660             alphaFunc->setFunction(func);
661             alphaFunc->setReferenceValue(refValue);
662             pass->setAttributeAndModes(alphaFunc);
663         }
664     }
665 };
666
667 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
668
669 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
670
671 // Shader key, used both for shaders with relative and absolute names
672 typedef pair<string, Shader::Type> ShaderKey;
673
674 struct ProgramKey
675 {
676     typedef pair<string, int> AttribKey;
677     osgDB::FilePathList paths;
678     vector<ShaderKey> shaders;
679     vector<AttribKey> attributes;
680     struct EqualTo
681     {
682         bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
683         {
684             return (lhs.paths.size() == rhs.paths.size()
685                     && equal(lhs.paths.begin(), lhs.paths.end(),
686                              rhs.paths.begin())
687                     && lhs.shaders.size() == rhs.shaders.size()
688                     && equal (lhs.shaders.begin(), lhs.shaders.end(),
689                               rhs.shaders.begin())
690                     && lhs.attributes.size() == rhs.attributes.size()
691                     && equal(lhs.attributes.begin(), lhs.attributes.end(),
692                              rhs.attributes.begin()));
693         }
694     };
695 };
696
697 size_t hash_value(const ProgramKey& key)
698 {
699     size_t seed = 0;
700     boost::hash_range(seed, key.paths.begin(), key.paths.end());
701     boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
702     boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
703     return seed;
704 }
705
706 // XXX Should these be protected by a mutex? Probably
707
708 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
709                            boost::hash<ProgramKey>, ProgramKey::EqualTo>
710 ProgramMap;
711 ProgramMap programMap;
712
713 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
714 ShaderMap;
715 ShaderMap shaderMap;
716
717 void reload_shaders()
718 {
719     for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
720     {
721         Shader *shader = sitr->second.get();
722         string fileName = osgDB::findDataFile(sitr->first.first);
723         if (!fileName.empty()) {
724             shader->loadShaderSourceFromFile(fileName);
725         }
726     }
727 }
728
729 struct ShaderProgramBuilder : PassAttributeBuilder
730 {
731     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
732                         const SGReaderWriterXMLOptions* options);
733 };
734
735 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
736                                           const SGPropertyNode* prop,
737                                           const SGReaderWriterXMLOptions*
738                                           options)
739 {
740     using namespace boost;
741     if (!isAttributeActive(effect, prop))
742         return;
743     PropertyList pVertShaders = prop->getChildren("vertex-shader");
744     PropertyList pFragShaders = prop->getChildren("fragment-shader");
745     PropertyList pAttributes = prop->getChildren("attribute");
746     ProgramKey prgKey;
747     for (PropertyList::iterator itr = pVertShaders.begin(),
748              e = pVertShaders.end();
749          itr != e;
750          ++itr)
751         prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
752                                            Shader::VERTEX));
753     for (PropertyList::iterator itr = pFragShaders.begin(),
754              e = pFragShaders.end();
755          itr != e;
756          ++itr)
757         prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
758                                            Shader::FRAGMENT));
759     for (PropertyList::iterator itr = pAttributes.begin(),
760              e = pAttributes.end();
761          itr != e;
762          ++itr) {
763         const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
764                                                              "name");
765         const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
766                                                               "index");
767         if (!pName || ! pIndex)
768             throw BuilderException("malformed attribute property");
769         prgKey.attributes
770             .push_back(ProgramKey::AttribKey(pName->getStringValue(),
771                                              pIndex->getValue<int>()));
772     }
773     if (options)
774         prgKey.paths = options->getDatabasePathList();
775     Program* program = 0;
776     ProgramMap::iterator pitr = programMap.find(prgKey);
777     if (pitr != programMap.end()) {
778         program = pitr->second.get();
779     } else {
780         program = new Program;
781         // Add vertex shaders, then fragment shaders
782         PropertyList& pvec = pVertShaders;
783         Shader::Type stype = Shader::VERTEX;
784         for (int i = 0; i < 2; ++i) {
785             for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
786                  nameItr != e;
787                  ++nameItr) {
788                 string shaderName = (*nameItr)->getStringValue();
789                 string fileName = osgDB::findDataFile(shaderName, options);
790                 if (fileName.empty())
791                     throw BuilderException(string("couldn't find shader ") +
792                                            shaderName);
793                 ShaderKey skey(fileName, stype);
794                 ShaderMap::iterator sitr = shaderMap.find(skey);
795                 if (sitr != shaderMap.end()) {
796                     program->addShader(sitr->second.get());
797                 } else {
798                     ref_ptr<Shader> shader = new Shader(stype);
799                     if (shader->loadShaderSourceFromFile(fileName)) {
800                         program->addShader(shader.get());
801                         shaderMap.insert(ShaderMap::value_type(skey, shader));
802                     }
803                 }
804             }
805             pvec = pFragShaders;
806             stype = Shader::FRAGMENT;
807         }
808         BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
809             program->addBindAttribLocation(key.first, key.second);
810         }
811        programMap.insert(ProgramMap::value_type(prgKey, program));
812     }
813     pass->setAttributeAndModes(program);
814 }
815
816 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
817
818 EffectNameValue<Uniform::Type> uniformTypesInit[] =
819 {
820     {"float", Uniform::FLOAT},
821     {"float-vec3", Uniform::FLOAT_VEC3},
822     {"float-vec4", Uniform::FLOAT_VEC4},
823     {"sampler-1d", Uniform::SAMPLER_1D},
824     {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
825     {"sampler-2d", Uniform::SAMPLER_2D},
826     {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
827     {"sampler-3d", Uniform::SAMPLER_3D},
828     {"sampler-cube", Uniform::SAMPLER_CUBE}
829 };
830 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
831
832 struct UniformBuilder :public PassAttributeBuilder
833 {
834     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
835                         const SGReaderWriterXMLOptions* options)
836     {
837         if (!isAttributeActive(effect, prop))
838             return;
839         const SGPropertyNode* nameProp = prop->getChild("name");
840         const SGPropertyNode* typeProp = prop->getChild("type");
841         const SGPropertyNode* valProp = prop->getChild("value");
842         string name;
843         Uniform::Type uniformType = Uniform::FLOAT;
844         if (nameProp) {
845             name = nameProp->getStringValue();
846         } else {
847             SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
848             return;
849         }
850         if (!valProp) {
851             SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
852                    << name);
853             return;
854         }
855         if (!typeProp) {
856             props::Type propType = valProp->getType();
857             switch (propType) {
858             case props::FLOAT:
859             case props::DOUBLE:
860                 break;          // default float type;
861             case props::VEC3D:
862                 uniformType = Uniform::FLOAT_VEC3;
863                 break;
864             case props::VEC4D:
865                 uniformType = Uniform::FLOAT_VEC4;
866                 break;
867             default:
868                 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
869                        << name);
870                 return;
871             }
872         } else {
873             findAttr(uniformTypes, typeProp, uniformType);
874         }
875         ref_ptr<Uniform> uniform = new Uniform;
876         uniform->setName(name);
877         uniform->setType(uniformType);
878         switch (uniformType) {
879         case Uniform::FLOAT:
880             initFromParameters(effect, valProp, uniform.get(),
881                                static_cast<bool (Uniform::*)(float)>(&Uniform::set),
882                                options);
883             break;
884         case Uniform::FLOAT_VEC3:
885             initFromParameters(effect, valProp, uniform.get(),
886                                static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
887                                vec3Names, options);
888             break;
889         case Uniform::FLOAT_VEC4:
890             initFromParameters(effect, valProp, uniform.get(),
891                                static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
892                                vec4Names, options);
893             break;
894         case Uniform::SAMPLER_1D:
895         case Uniform::SAMPLER_2D:
896         case Uniform::SAMPLER_3D:
897         case Uniform::SAMPLER_1D_SHADOW:
898         case Uniform::SAMPLER_2D_SHADOW:
899         case Uniform::SAMPLER_CUBE:
900             initFromParameters(effect, valProp, uniform.get(),
901                                static_cast<bool (Uniform::*)(int)>(&Uniform::set),
902                                options);
903             break;
904         default: // avoid compiler warning
905             break;
906         }
907         pass->addUniform(uniform.get());
908     }
909 };
910
911 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
912
913 // Not sure what to do with "name". At one point I wanted to use it to
914 // order the passes, but I do support render bin and stuff too...
915
916 struct NameBuilder : public PassAttributeBuilder
917 {
918     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
919                         const SGReaderWriterXMLOptions* options)
920     {
921         // name can't use <use>
922         string name = prop->getStringValue();
923         if (!name.empty())
924             pass->setName(name);
925     }
926 };
927
928 InstallAttributeBuilder<NameBuilder> installName("name");
929
930 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
931 {
932     {"fill", PolygonMode::FILL},
933     {"line", PolygonMode::LINE},
934     {"point", PolygonMode::POINT}
935 };
936 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
937
938 struct PolygonModeBuilder : public PassAttributeBuilder
939 {
940     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
941                         const SGReaderWriterXMLOptions* options)
942     {
943         if (!isAttributeActive(effect, prop))
944             return;
945         const SGPropertyNode* frontProp
946             = getEffectPropertyChild(effect, prop, "front");
947         const SGPropertyNode* backProp
948             = getEffectPropertyChild(effect, prop, "back");
949         ref_ptr<PolygonMode> pmode = new PolygonMode;
950         PolygonMode::Mode frontMode = PolygonMode::FILL;
951         PolygonMode::Mode backMode = PolygonMode::FILL;
952         if (frontProp) {
953             findAttr(polygonModeModes, frontProp, frontMode);
954             pmode->setMode(PolygonMode::FRONT, frontMode);
955         }
956         if (backProp) {
957             findAttr(polygonModeModes, backProp, backMode);
958             pmode->setMode(PolygonMode::BACK, backMode);
959         }
960         pass->setAttribute(pmode.get());
961     }
962 };
963
964 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
965
966 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
967 {
968     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
969                         const SGReaderWriterXMLOptions* options)
970     {
971         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
972         if (!realProp)
973             return;
974         pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
975                       (realProp->getValue<bool>()
976                        ? StateAttribute::ON : StateAttribute::OFF));
977     }
978 };
979
980 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
981 installTwoSide("vertex-program-two-side");
982
983 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
984 {
985     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
986                         const SGReaderWriterXMLOptions* options)
987     {
988         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
989         if (!realProp)
990             return;
991         pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
992                       (realProp->getValue<bool>()
993                        ? StateAttribute::ON : StateAttribute::OFF));
994     }
995 };
996
997 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
998 installPointSize("vertex-program-point-size");
999
1000 EffectNameValue<Depth::Function> depthFunctionInit[] =
1001 {
1002     {"never", Depth::NEVER},
1003     {"less", Depth::LESS},
1004     {"equal", Depth::EQUAL},
1005     {"lequal", Depth::LEQUAL},
1006     {"greater", Depth::GREATER},
1007     {"notequal", Depth::NOTEQUAL},
1008     {"gequal", Depth::GEQUAL},
1009     {"always", Depth::ALWAYS}
1010 };
1011 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1012
1013 struct DepthBuilder : public PassAttributeBuilder
1014 {
1015     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1016                         const SGReaderWriterXMLOptions* options)
1017     {
1018         if (!isAttributeActive(effect, prop))
1019             return;
1020         ref_ptr<Depth> depth = new Depth;
1021         const SGPropertyNode* pfunc
1022             = getEffectPropertyChild(effect, prop, "function");
1023         if (pfunc) {
1024             Depth::Function func = Depth::LESS;
1025             findAttr(depthFunction, pfunc, func);
1026             depth->setFunction(func);
1027         }
1028         const SGPropertyNode* pnear
1029             = getEffectPropertyChild(effect, prop, "near");
1030         if (pnear)
1031             depth->setZNear(pnear->getValue<double>());
1032         const SGPropertyNode* pfar
1033             = getEffectPropertyChild(effect, prop, "far");
1034         if (pfar)
1035             depth->setZFar(pnear->getValue<double>());
1036         const SGPropertyNode* pmask
1037             = getEffectPropertyChild(effect, prop, "write-mask");
1038         if (pmask)
1039             depth->setWriteMask(pmask->getValue<bool>());
1040         pass->setAttribute(depth.get());
1041     }
1042 };
1043
1044 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1045
1046 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1047                     const SGReaderWriterXMLOptions* options)
1048 {
1049     Technique* tniq = new Technique;
1050     effect->techniques.push_back(tniq);
1051     const SGPropertyNode* predProp = prop->getChild("predicate");
1052     if (!predProp) {
1053         tniq->setAlwaysValid(true);
1054     } else {
1055         try {
1056             TechniquePredParser parser;
1057             parser.setTechnique(tniq);
1058             expression::BindingLayout& layout = parser.getBindingLayout();
1059             /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1060             SGExpressionb* validExp
1061                 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1062                                                            ->getChild(0)));
1063             if (validExp)
1064                 tniq->setValidExpression(validExp, layout);
1065             else
1066                 throw expression::ParseError("technique predicate is not a boolean expression");
1067         }
1068         catch (expression::ParseError& except)
1069         {
1070             SG_LOG(SG_INPUT, SG_ALERT,
1071                    "parsing technique predicate " << except.getMessage());
1072             tniq->setAlwaysValid(false);
1073         }
1074     }
1075     PropertyList passProps = prop->getChildren("pass");
1076     for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1077          itr != e;
1078          ++itr) {
1079         buildPass(effect, tniq, itr->ptr(), options);
1080     }
1081 }
1082
1083 // Specifically for .ac files...
1084 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1085 {
1086     SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1087     SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1088     Vec4f ambVal, difVal, specVal, emisVal;
1089     float shininess = 0.0f;
1090     const Material* mat = getStateAttribute<Material>(ss);
1091     if (mat) {
1092         ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1093         difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1094         specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1095         emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1096         shininess = mat->getShininess(Material::FRONT_AND_BACK);
1097         makeChild(matNode, "active")->setValue(true);
1098         makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1099         makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1100         makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1101         makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1102         makeChild(matNode, "shininess")->setValue(shininess);
1103         matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1104     } else {
1105         makeChild(matNode, "active")->setValue(false);
1106     }
1107     const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1108     string shadeModelString("smooth");
1109     if (sm) {
1110         ShadeModel::Mode smMode = sm->getMode();
1111         if (smMode == ShadeModel::FLAT)
1112             shadeModelString = "flat";
1113     }
1114     makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1115     string cullFaceString("off");
1116     const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1117     if (cullFace) {
1118         switch (cullFace->getMode()) {
1119         case CullFace::FRONT:
1120             cullFaceString = "front";
1121             break;
1122         case CullFace::BACK:
1123             cullFaceString = "back";
1124             break;
1125         case CullFace::FRONT_AND_BACK:
1126             cullFaceString = "front-back";
1127             break;
1128         default:
1129             break;
1130         }
1131     }
1132     makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1133     const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1134     SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1135     if (blendFunc) {
1136         string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1137         string destMode = findName(blendFuncModes, blendFunc->getDestination());
1138         makeChild(blendNode, "active")->setValue(true);
1139         makeChild(blendNode, "source")->setStringValue(sourceMode);
1140         makeChild(blendNode, "destination")->setStringValue(destMode);
1141         makeChild(blendNode, "mode")->setValue(true);
1142     } else {
1143         makeChild(blendNode, "active")->setValue(false);
1144     }
1145     string renderingHint = findName(renderingHints, ss->getRenderingHint());
1146     makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1147     makeTextureParameters(paramRoot, ss);
1148     return true;
1149 }
1150
1151 // Walk the techniques property tree, building techniques and
1152 // passes.
1153 bool Effect::realizeTechniques(const SGReaderWriterXMLOptions* options)
1154 {
1155     if (_isRealized)
1156         return true;
1157     PropertyList tniqList = root->getChildren("technique");
1158     for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1159          itr != e;
1160          ++itr)
1161         buildTechnique(this, *itr, options);
1162     _isRealized = true;
1163     return true;
1164 }
1165
1166 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1167 {
1168     EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1169     if (!eg)
1170         return;
1171     Effect* effect = eg->getEffect();
1172     if (!effect)
1173         return;
1174     SGPropertyNode* root = getPropertyRoot();
1175     for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1176              end = effect->_extraData.end();
1177          itr != end;
1178          ++itr) {
1179         InitializeWhenAdded* adder
1180             = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1181         if (adder)
1182             adder->initOnAdd(effect, root);
1183     }
1184 }
1185
1186 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1187                                       const Effect::Key& rhs) const
1188 {
1189     if (lhs.paths.size() != rhs.paths.size()
1190         || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1191         return false;
1192     if (lhs.unmerged.valid() && rhs.unmerged.valid())
1193         return props::Compare()(lhs.unmerged, rhs.unmerged);
1194     else
1195         return lhs.unmerged == rhs.unmerged;
1196 }
1197
1198 size_t hash_value(const Effect::Key& key)
1199 {
1200     size_t seed = 0;
1201     if (key.unmerged.valid())
1202         boost::hash_combine(seed, *key.unmerged);
1203     boost::hash_range(seed, key.paths.begin(), key.paths.end());
1204     return seed;
1205 }
1206
1207 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1208 {
1209     const Effect& effect = static_cast<const Effect&>(obj);
1210
1211     fw.indent() << "techniques " << effect.techniques.size() << "\n";
1212     BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1213         fw.writeObject(*technique);
1214     }
1215     return true;
1216 }
1217
1218 namespace
1219 {
1220 osgDB::RegisterDotOsgWrapperProxy effectProxy
1221 (
1222     new Effect,
1223     "simgear::Effect",
1224     "Object simgear::Effect",
1225     0,
1226     &Effect_writeLocalData
1227     );
1228 }
1229
1230 // Property expressions for technique predicates
1231 class PropertyExpression : public SGExpression<bool>
1232 {
1233 public:
1234     PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1235     
1236     void eval(bool& value, const expression::Binding*) const
1237     {
1238         value = _pnode->getValue<bool>();
1239     }
1240 protected:
1241     SGPropertyNode_ptr _pnode;
1242 };
1243
1244 class EffectPropertyListener : public SGPropertyChangeListener
1245 {
1246 public:
1247     EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1248     
1249     void valueChanged(SGPropertyNode* node)
1250     {
1251         _tniq->refreshValidity();
1252     }
1253 protected:
1254     osg::ref_ptr<Technique> _tniq;
1255 };
1256
1257 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1258                                      expression::Parser* parser)
1259 {
1260     SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1261                                                           true);
1262     PropertyExpression* pexp = new PropertyExpression(pnode);
1263     TechniquePredParser* predParser
1264         = dynamic_cast<TechniquePredParser*>(parser);
1265     if (predParser)
1266         pnode->addChangeListener(new EffectPropertyListener(predParser
1267                                                             ->getTechnique()));
1268     return pexp;
1269 }
1270
1271 expression::ExpParserRegistrar propertyRegistrar("property",
1272                                                  propertyExpressionParser);
1273
1274 }