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