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