]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/Effect.cxx
Geometry shader support
[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
736 EffectNameValue<GLint> geometryInputTypeInit[] =
737 {
738     {"points", GL_POINTS},
739     {"lines", GL_LINES},
740     {"lines-adjacency", GL_LINES_ADJACENCY_EXT},
741     {"triangles", GL_TRIANGLES},
742     {"triangles-adjacency", GL_TRIANGLES_ADJACENCY_EXT},
743 };
744 EffectPropertyMap<GLint>
745 geometryInputType(geometryInputTypeInit);
746
747
748 EffectNameValue<GLint> geometryOutputTypeInit[] =
749 {
750     {"points", GL_POINTS},
751     {"line-strip", GL_LINE_STRIP},
752     {"triangle-strip", GL_TRIANGLE_STRIP}
753 };
754 EffectPropertyMap<GLint>
755 geometryOutputType(geometryOutputTypeInit);
756
757 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
758                                           const SGPropertyNode* prop,
759                                           const SGReaderWriterXMLOptions*
760                                           options)
761 {
762     using namespace boost;
763     if (!isAttributeActive(effect, prop))
764         return;
765     PropertyList pVertShaders = prop->getChildren("vertex-shader");
766     PropertyList pGeomShaders = prop->getChildren("geometry-shader");
767     PropertyList pFragShaders = prop->getChildren("fragment-shader");
768     PropertyList pAttributes = prop->getChildren("attribute");
769     ProgramKey prgKey;
770     for (PropertyList::iterator itr = pVertShaders.begin(),
771              e = pVertShaders.end();
772          itr != e;
773          ++itr)
774         prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
775                                            Shader::VERTEX));
776     for (PropertyList::iterator itr = pGeomShaders.begin(),
777              e = pGeomShaders.end();
778          itr != e;
779          ++itr)
780         prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
781                                            Shader::GEOMETRY));
782     for (PropertyList::iterator itr = pFragShaders.begin(),
783              e = pFragShaders.end();
784          itr != e;
785          ++itr)
786         prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
787                                            Shader::FRAGMENT));
788     for (PropertyList::iterator itr = pAttributes.begin(),
789              e = pAttributes.end();
790          itr != e;
791          ++itr) {
792         const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
793                                                              "name");
794         const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
795                                                               "index");
796         if (!pName || ! pIndex)
797             throw BuilderException("malformed attribute property");
798         prgKey.attributes
799             .push_back(ProgramKey::AttribKey(pName->getStringValue(),
800                                              pIndex->getValue<int>()));
801     }
802     if (options)
803         prgKey.paths = options->getDatabasePathList();
804     Program* program = 0;
805     ProgramMap::iterator pitr = programMap.find(prgKey);
806     if (pitr != programMap.end()) {
807         program = pitr->second.get();
808     } else {
809         program = new Program;
810         // Add vertex shaders, then fragment shaders
811         PropertyList& pvec = pVertShaders;
812         Shader::Type stype = Shader::VERTEX;
813         for (int i = 0; i < 3; ++i) {
814             for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
815                  nameItr != e;
816                  ++nameItr) {
817                 string shaderName = (*nameItr)->getStringValue();
818                 string fileName = osgDB::findDataFile(shaderName, options);
819                 if (fileName.empty())
820                     throw BuilderException(string("couldn't find shader ") +
821                                            shaderName);
822                 ShaderKey skey(fileName, stype);
823                 ShaderMap::iterator sitr = shaderMap.find(skey);
824                 if (sitr != shaderMap.end()) {
825                     program->addShader(sitr->second.get());
826                 } else {
827                     ref_ptr<Shader> shader = new Shader(stype);
828                     if (shader->loadShaderSourceFromFile(fileName)) {
829                         program->addShader(shader.get());
830                         shaderMap.insert(ShaderMap::value_type(skey, shader));
831                     }
832                 }
833             }
834             if (i == 0) {
835                 pvec = pGeomShaders;
836                 stype = Shader::GEOMETRY;
837             } else {
838                 pvec = pFragShaders;
839                 stype = Shader::FRAGMENT;
840             }
841         }
842         BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
843             program->addBindAttribLocation(key.first, key.second);
844         }
845         const SGPropertyNode* pGeometryVerticesOut = getEffectPropertyChild(effect, prop, "geometry-vertices-out");
846         if ( pGeometryVerticesOut ) {
847             program->setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, pGeometryVerticesOut->getIntValue() );
848         }
849         const SGPropertyNode* pGeometryInputType = getEffectPropertyChild(effect, prop, "geometry-input-type");
850         if ( pGeometryInputType ) {
851             GLint type;
852             findAttr( geometryInputType, pGeometryInputType->getStringValue(), type );
853             program->setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, type );
854         }
855         const SGPropertyNode* pGeometryOutputType = getEffectPropertyChild(effect, prop, "geometry-output-type");
856         if ( pGeometryOutputType ) {
857             GLint type;
858             findAttr( geometryOutputType, pGeometryOutputType->getStringValue(), type );
859             program->setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, type );
860         }
861
862         programMap.insert(ProgramMap::value_type(prgKey, program));
863     }
864     pass->setAttributeAndModes(program);
865 }
866
867 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
868
869 EffectNameValue<Uniform::Type> uniformTypesInit[] =
870 {
871     {"float", Uniform::FLOAT},
872     {"float-vec3", Uniform::FLOAT_VEC3},
873     {"float-vec4", Uniform::FLOAT_VEC4},
874     {"sampler-1d", Uniform::SAMPLER_1D},
875     {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
876     {"sampler-2d", Uniform::SAMPLER_2D},
877     {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
878     {"sampler-3d", Uniform::SAMPLER_3D},
879     {"sampler-cube", Uniform::SAMPLER_CUBE}
880 };
881 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
882
883 struct UniformBuilder :public PassAttributeBuilder
884 {
885     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
886                         const SGReaderWriterXMLOptions* options)
887     {
888         if (!isAttributeActive(effect, prop))
889             return;
890         const SGPropertyNode* nameProp = prop->getChild("name");
891         const SGPropertyNode* typeProp = prop->getChild("type");
892         const SGPropertyNode* valProp = prop->getChild("value");
893         string name;
894         Uniform::Type uniformType = Uniform::FLOAT;
895         if (nameProp) {
896             name = nameProp->getStringValue();
897         } else {
898             SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
899             return;
900         }
901         if (!valProp) {
902             SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
903                    << name);
904             return;
905         }
906         if (!typeProp) {
907             props::Type propType = valProp->getType();
908             switch (propType) {
909             case props::FLOAT:
910             case props::DOUBLE:
911                 break;          // default float type;
912             case props::VEC3D:
913                 uniformType = Uniform::FLOAT_VEC3;
914                 break;
915             case props::VEC4D:
916                 uniformType = Uniform::FLOAT_VEC4;
917                 break;
918             default:
919                 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
920                        << name);
921                 return;
922             }
923         } else {
924             findAttr(uniformTypes, typeProp, uniformType);
925         }
926         ref_ptr<Uniform> uniform = new Uniform;
927         uniform->setName(name);
928         uniform->setType(uniformType);
929         switch (uniformType) {
930         case Uniform::FLOAT:
931             initFromParameters(effect, valProp, uniform.get(),
932                                static_cast<bool (Uniform::*)(float)>(&Uniform::set),
933                                options);
934             break;
935         case Uniform::FLOAT_VEC3:
936             initFromParameters(effect, valProp, uniform.get(),
937                                static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
938                                vec3Names, options);
939             break;
940         case Uniform::FLOAT_VEC4:
941             initFromParameters(effect, valProp, uniform.get(),
942                                static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
943                                vec4Names, options);
944             break;
945         case Uniform::SAMPLER_1D:
946         case Uniform::SAMPLER_2D:
947         case Uniform::SAMPLER_3D:
948         case Uniform::SAMPLER_1D_SHADOW:
949         case Uniform::SAMPLER_2D_SHADOW:
950         case Uniform::SAMPLER_CUBE:
951             initFromParameters(effect, valProp, uniform.get(),
952                                static_cast<bool (Uniform::*)(int)>(&Uniform::set),
953                                options);
954             break;
955         default: // avoid compiler warning
956             break;
957         }
958         pass->addUniform(uniform.get());
959     }
960 };
961
962 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
963
964 // Not sure what to do with "name". At one point I wanted to use it to
965 // order the passes, but I do support render bin and stuff too...
966
967 struct NameBuilder : public PassAttributeBuilder
968 {
969     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
970                         const SGReaderWriterXMLOptions* options)
971     {
972         // name can't use <use>
973         string name = prop->getStringValue();
974         if (!name.empty())
975             pass->setName(name);
976     }
977 };
978
979 InstallAttributeBuilder<NameBuilder> installName("name");
980
981 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
982 {
983     {"fill", PolygonMode::FILL},
984     {"line", PolygonMode::LINE},
985     {"point", PolygonMode::POINT}
986 };
987 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
988
989 struct PolygonModeBuilder : public PassAttributeBuilder
990 {
991     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
992                         const SGReaderWriterXMLOptions* options)
993     {
994         if (!isAttributeActive(effect, prop))
995             return;
996         const SGPropertyNode* frontProp
997             = getEffectPropertyChild(effect, prop, "front");
998         const SGPropertyNode* backProp
999             = getEffectPropertyChild(effect, prop, "back");
1000         ref_ptr<PolygonMode> pmode = new PolygonMode;
1001         PolygonMode::Mode frontMode = PolygonMode::FILL;
1002         PolygonMode::Mode backMode = PolygonMode::FILL;
1003         if (frontProp) {
1004             findAttr(polygonModeModes, frontProp, frontMode);
1005             pmode->setMode(PolygonMode::FRONT, frontMode);
1006         }
1007         if (backProp) {
1008             findAttr(polygonModeModes, backProp, backMode);
1009             pmode->setMode(PolygonMode::BACK, backMode);
1010         }
1011         pass->setAttribute(pmode.get());
1012     }
1013 };
1014
1015 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1016
1017 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1018 {
1019     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1020                         const SGReaderWriterXMLOptions* options)
1021     {
1022         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1023         if (!realProp)
1024             return;
1025         pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1026                       (realProp->getValue<bool>()
1027                        ? StateAttribute::ON : StateAttribute::OFF));
1028     }
1029 };
1030
1031 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1032 installTwoSide("vertex-program-two-side");
1033
1034 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1035 {
1036     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1037                         const SGReaderWriterXMLOptions* options)
1038     {
1039         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1040         if (!realProp)
1041             return;
1042         pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1043                       (realProp->getValue<bool>()
1044                        ? StateAttribute::ON : StateAttribute::OFF));
1045     }
1046 };
1047
1048 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1049 installPointSize("vertex-program-point-size");
1050
1051 EffectNameValue<Depth::Function> depthFunctionInit[] =
1052 {
1053     {"never", Depth::NEVER},
1054     {"less", Depth::LESS},
1055     {"equal", Depth::EQUAL},
1056     {"lequal", Depth::LEQUAL},
1057     {"greater", Depth::GREATER},
1058     {"notequal", Depth::NOTEQUAL},
1059     {"gequal", Depth::GEQUAL},
1060     {"always", Depth::ALWAYS}
1061 };
1062 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1063
1064 struct DepthBuilder : public PassAttributeBuilder
1065 {
1066     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1067                         const SGReaderWriterXMLOptions* options)
1068     {
1069         if (!isAttributeActive(effect, prop))
1070             return;
1071         ref_ptr<Depth> depth = new Depth;
1072         const SGPropertyNode* pfunc
1073             = getEffectPropertyChild(effect, prop, "function");
1074         if (pfunc) {
1075             Depth::Function func = Depth::LESS;
1076             findAttr(depthFunction, pfunc, func);
1077             depth->setFunction(func);
1078         }
1079         const SGPropertyNode* pnear
1080             = getEffectPropertyChild(effect, prop, "near");
1081         if (pnear)
1082             depth->setZNear(pnear->getValue<double>());
1083         const SGPropertyNode* pfar
1084             = getEffectPropertyChild(effect, prop, "far");
1085         if (pfar)
1086             depth->setZFar(pnear->getValue<double>());
1087         const SGPropertyNode* pmask
1088             = getEffectPropertyChild(effect, prop, "write-mask");
1089         if (pmask)
1090             depth->setWriteMask(pmask->getValue<bool>());
1091         pass->setAttribute(depth.get());
1092     }
1093 };
1094
1095 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1096
1097 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1098                     const SGReaderWriterXMLOptions* options)
1099 {
1100     Technique* tniq = new Technique;
1101     effect->techniques.push_back(tniq);
1102     const SGPropertyNode* predProp = prop->getChild("predicate");
1103     if (!predProp) {
1104         tniq->setAlwaysValid(true);
1105     } else {
1106         try {
1107             TechniquePredParser parser;
1108             parser.setTechnique(tniq);
1109             expression::BindingLayout& layout = parser.getBindingLayout();
1110             /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1111             SGExpressionb* validExp
1112                 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1113                                                            ->getChild(0)));
1114             if (validExp)
1115                 tniq->setValidExpression(validExp, layout);
1116             else
1117                 throw expression::ParseError("technique predicate is not a boolean expression");
1118         }
1119         catch (expression::ParseError& except)
1120         {
1121             SG_LOG(SG_INPUT, SG_ALERT,
1122                    "parsing technique predicate " << except.getMessage());
1123             tniq->setAlwaysValid(false);
1124         }
1125     }
1126     PropertyList passProps = prop->getChildren("pass");
1127     for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1128          itr != e;
1129          ++itr) {
1130         buildPass(effect, tniq, itr->ptr(), options);
1131     }
1132 }
1133
1134 // Specifically for .ac files...
1135 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1136 {
1137     SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1138     SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1139     Vec4f ambVal, difVal, specVal, emisVal;
1140     float shininess = 0.0f;
1141     const Material* mat = getStateAttribute<Material>(ss);
1142     if (mat) {
1143         ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1144         difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1145         specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1146         emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1147         shininess = mat->getShininess(Material::FRONT_AND_BACK);
1148         makeChild(matNode, "active")->setValue(true);
1149         makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1150         makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1151         makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1152         makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1153         makeChild(matNode, "shininess")->setValue(shininess);
1154         matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1155     } else {
1156         makeChild(matNode, "active")->setValue(false);
1157     }
1158     const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1159     string shadeModelString("smooth");
1160     if (sm) {
1161         ShadeModel::Mode smMode = sm->getMode();
1162         if (smMode == ShadeModel::FLAT)
1163             shadeModelString = "flat";
1164     }
1165     makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1166     string cullFaceString("off");
1167     const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1168     if (cullFace) {
1169         switch (cullFace->getMode()) {
1170         case CullFace::FRONT:
1171             cullFaceString = "front";
1172             break;
1173         case CullFace::BACK:
1174             cullFaceString = "back";
1175             break;
1176         case CullFace::FRONT_AND_BACK:
1177             cullFaceString = "front-back";
1178             break;
1179         default:
1180             break;
1181         }
1182     }
1183     makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1184     const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1185     SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1186     if (blendFunc) {
1187         string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1188         string destMode = findName(blendFuncModes, blendFunc->getDestination());
1189         makeChild(blendNode, "active")->setValue(true);
1190         makeChild(blendNode, "source")->setStringValue(sourceMode);
1191         makeChild(blendNode, "destination")->setStringValue(destMode);
1192         makeChild(blendNode, "mode")->setValue(true);
1193     } else {
1194         makeChild(blendNode, "active")->setValue(false);
1195     }
1196     string renderingHint = findName(renderingHints, ss->getRenderingHint());
1197     makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1198     makeTextureParameters(paramRoot, ss);
1199     return true;
1200 }
1201
1202 // Walk the techniques property tree, building techniques and
1203 // passes.
1204 bool Effect::realizeTechniques(const SGReaderWriterXMLOptions* options)
1205 {
1206     if (_isRealized)
1207         return true;
1208     PropertyList tniqList = root->getChildren("technique");
1209     for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1210          itr != e;
1211          ++itr)
1212         buildTechnique(this, *itr, options);
1213     _isRealized = true;
1214     return true;
1215 }
1216
1217 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1218 {
1219     EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1220     if (!eg)
1221         return;
1222     Effect* effect = eg->getEffect();
1223     if (!effect)
1224         return;
1225     SGPropertyNode* root = getPropertyRoot();
1226     for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1227              end = effect->_extraData.end();
1228          itr != end;
1229          ++itr) {
1230         InitializeWhenAdded* adder
1231             = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1232         if (adder)
1233             adder->initOnAdd(effect, root);
1234     }
1235 }
1236
1237 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1238                                       const Effect::Key& rhs) const
1239 {
1240     if (lhs.paths.size() != rhs.paths.size()
1241         || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1242         return false;
1243     if (lhs.unmerged.valid() && rhs.unmerged.valid())
1244         return props::Compare()(lhs.unmerged, rhs.unmerged);
1245     else
1246         return lhs.unmerged == rhs.unmerged;
1247 }
1248
1249 size_t hash_value(const Effect::Key& key)
1250 {
1251     size_t seed = 0;
1252     if (key.unmerged.valid())
1253         boost::hash_combine(seed, *key.unmerged);
1254     boost::hash_range(seed, key.paths.begin(), key.paths.end());
1255     return seed;
1256 }
1257
1258 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1259 {
1260     const Effect& effect = static_cast<const Effect&>(obj);
1261
1262     fw.indent() << "techniques " << effect.techniques.size() << "\n";
1263     BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1264         fw.writeObject(*technique);
1265     }
1266     return true;
1267 }
1268
1269 namespace
1270 {
1271 osgDB::RegisterDotOsgWrapperProxy effectProxy
1272 (
1273     new Effect,
1274     "simgear::Effect",
1275     "Object simgear::Effect",
1276     0,
1277     &Effect_writeLocalData
1278     );
1279 }
1280
1281 // Property expressions for technique predicates
1282 class PropertyExpression : public SGExpression<bool>
1283 {
1284 public:
1285     PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1286     
1287     void eval(bool& value, const expression::Binding*) const
1288     {
1289         value = _pnode->getValue<bool>();
1290     }
1291 protected:
1292     SGPropertyNode_ptr _pnode;
1293 };
1294
1295 class EffectPropertyListener : public SGPropertyChangeListener
1296 {
1297 public:
1298     EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1299     
1300     void valueChanged(SGPropertyNode* node)
1301     {
1302         _tniq->refreshValidity();
1303     }
1304 protected:
1305     osg::ref_ptr<Technique> _tniq;
1306 };
1307
1308 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1309                                      expression::Parser* parser)
1310 {
1311     SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1312                                                           true);
1313     PropertyExpression* pexp = new PropertyExpression(pnode);
1314     TechniquePredParser* predParser
1315         = dynamic_cast<TechniquePredParser*>(parser);
1316     if (predParser)
1317         pnode->addChangeListener(new EffectPropertyListener(predParser
1318                                                             ->getTechnique()));
1319     return pexp;
1320 }
1321
1322 expression::ExpParserRegistrar propertyRegistrar("property",
1323                                                  propertyExpressionParser);
1324
1325 }