]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/Effect.cxx
Add bool and int uniform types for shaders, and vertex-program-two-sided
[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/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     {"bool", Uniform::BOOL},
872     {"int", Uniform::INT},
873     {"float", Uniform::FLOAT},
874     {"float-vec3", Uniform::FLOAT_VEC3},
875     {"float-vec4", Uniform::FLOAT_VEC4},
876     {"sampler-1d", Uniform::SAMPLER_1D},
877     {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
878     {"sampler-2d", Uniform::SAMPLER_2D},
879     {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
880     {"sampler-3d", Uniform::SAMPLER_3D},
881     {"sampler-cube", Uniform::SAMPLER_CUBE}
882 };
883 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
884
885 struct UniformBuilder :public PassAttributeBuilder
886 {
887     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
888                         const SGReaderWriterXMLOptions* options)
889     {
890         if (!isAttributeActive(effect, prop))
891             return;
892         const SGPropertyNode* nameProp = prop->getChild("name");
893         const SGPropertyNode* typeProp = prop->getChild("type");
894         const SGPropertyNode* valProp = prop->getChild("value");
895         string name;
896         Uniform::Type uniformType = Uniform::FLOAT;
897         if (nameProp) {
898             name = nameProp->getStringValue();
899         } else {
900             SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
901             return;
902         }
903         if (!valProp) {
904             SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
905                    << name);
906             return;
907         }
908         if (!typeProp) {
909             props::Type propType = valProp->getType();
910             switch (propType) {
911             case props::BOOL:
912                 uniformType = Uniform::BOOL;
913                 break;
914             case props::INT:
915                 uniformType = Uniform::INT;
916                 break;
917             case props::FLOAT:
918             case props::DOUBLE:
919                 break;          // default float type;
920             case props::VEC3D:
921                 uniformType = Uniform::FLOAT_VEC3;
922                 break;
923             case props::VEC4D:
924                 uniformType = Uniform::FLOAT_VEC4;
925                 break;
926             default:
927                 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
928                        << name);
929                 return;
930             }
931         } else {
932             findAttr(uniformTypes, typeProp, uniformType);
933         }
934         ref_ptr<Uniform> uniform = new Uniform;
935         uniform->setName(name);
936         uniform->setType(uniformType);
937         switch (uniformType) {
938         case Uniform::FLOAT:
939             initFromParameters(effect, valProp, uniform.get(),
940                                static_cast<bool (Uniform::*)(float)>(&Uniform::set),
941                                options);
942             break;
943         case Uniform::FLOAT_VEC3:
944             initFromParameters(effect, valProp, uniform.get(),
945                                static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
946                                vec3Names, options);
947             break;
948         case Uniform::FLOAT_VEC4:
949             initFromParameters(effect, valProp, uniform.get(),
950                                static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
951                                vec4Names, options);
952             break;
953         case Uniform::SAMPLER_1D:
954         case Uniform::SAMPLER_2D:
955         case Uniform::SAMPLER_3D:
956         case Uniform::SAMPLER_1D_SHADOW:
957         case Uniform::SAMPLER_2D_SHADOW:
958         case Uniform::SAMPLER_CUBE:
959             initFromParameters(effect, valProp, uniform.get(),
960                                static_cast<bool (Uniform::*)(int)>(&Uniform::set),
961                                options);
962             break;
963         default: // avoid compiler warning
964             break;
965         }
966         pass->addUniform(uniform.get());
967     }
968 };
969
970 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
971
972 // Not sure what to do with "name". At one point I wanted to use it to
973 // order the passes, but I do support render bin and stuff too...
974
975 struct NameBuilder : public PassAttributeBuilder
976 {
977     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
978                         const SGReaderWriterXMLOptions* options)
979     {
980         // name can't use <use>
981         string name = prop->getStringValue();
982         if (!name.empty())
983             pass->setName(name);
984     }
985 };
986
987 InstallAttributeBuilder<NameBuilder> installName("name");
988
989 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
990 {
991     {"fill", PolygonMode::FILL},
992     {"line", PolygonMode::LINE},
993     {"point", PolygonMode::POINT}
994 };
995 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
996
997 struct PolygonModeBuilder : public PassAttributeBuilder
998 {
999     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1000                         const SGReaderWriterXMLOptions* options)
1001     {
1002         if (!isAttributeActive(effect, prop))
1003             return;
1004         const SGPropertyNode* frontProp
1005             = getEffectPropertyChild(effect, prop, "front");
1006         const SGPropertyNode* backProp
1007             = getEffectPropertyChild(effect, prop, "back");
1008         ref_ptr<PolygonMode> pmode = new PolygonMode;
1009         PolygonMode::Mode frontMode = PolygonMode::FILL;
1010         PolygonMode::Mode backMode = PolygonMode::FILL;
1011         if (frontProp) {
1012             findAttr(polygonModeModes, frontProp, frontMode);
1013             pmode->setMode(PolygonMode::FRONT, frontMode);
1014         }
1015         if (backProp) {
1016             findAttr(polygonModeModes, backProp, backMode);
1017             pmode->setMode(PolygonMode::BACK, backMode);
1018         }
1019         pass->setAttribute(pmode.get());
1020     }
1021 };
1022
1023 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1024
1025 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1026 {
1027     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1028                         const SGReaderWriterXMLOptions* options)
1029     {
1030         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1031         if (!realProp)
1032             return;
1033         pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1034                       (realProp->getValue<bool>()
1035                        ? StateAttribute::ON : StateAttribute::OFF));
1036     }
1037 };
1038
1039 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1040 installTwoSide("vertex-program-two-side");
1041
1042 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1043 {
1044     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1045                         const SGReaderWriterXMLOptions* options)
1046     {
1047         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1048         if (!realProp)
1049             return;
1050         pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1051                       (realProp->getValue<bool>()
1052                        ? StateAttribute::ON : StateAttribute::OFF));
1053     }
1054 };
1055
1056 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1057 installPointSize("vertex-program-point-size");
1058
1059 EffectNameValue<Depth::Function> depthFunctionInit[] =
1060 {
1061     {"never", Depth::NEVER},
1062     {"less", Depth::LESS},
1063     {"equal", Depth::EQUAL},
1064     {"lequal", Depth::LEQUAL},
1065     {"greater", Depth::GREATER},
1066     {"notequal", Depth::NOTEQUAL},
1067     {"gequal", Depth::GEQUAL},
1068     {"always", Depth::ALWAYS}
1069 };
1070 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1071
1072 struct DepthBuilder : public PassAttributeBuilder
1073 {
1074     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1075                         const SGReaderWriterXMLOptions* options)
1076     {
1077         if (!isAttributeActive(effect, prop))
1078             return;
1079         ref_ptr<Depth> depth = new Depth;
1080         const SGPropertyNode* pfunc
1081             = getEffectPropertyChild(effect, prop, "function");
1082         if (pfunc) {
1083             Depth::Function func = Depth::LESS;
1084             findAttr(depthFunction, pfunc, func);
1085             depth->setFunction(func);
1086         }
1087         const SGPropertyNode* pnear
1088             = getEffectPropertyChild(effect, prop, "near");
1089         if (pnear)
1090             depth->setZNear(pnear->getValue<double>());
1091         const SGPropertyNode* pfar
1092             = getEffectPropertyChild(effect, prop, "far");
1093         if (pfar)
1094             depth->setZFar(pnear->getValue<double>());
1095         const SGPropertyNode* pmask
1096             = getEffectPropertyChild(effect, prop, "write-mask");
1097         if (pmask)
1098             depth->setWriteMask(pmask->getValue<bool>());
1099         pass->setAttribute(depth.get());
1100     }
1101 };
1102
1103 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1104
1105 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1106                     const SGReaderWriterXMLOptions* options)
1107 {
1108     Technique* tniq = new Technique;
1109     effect->techniques.push_back(tniq);
1110     const SGPropertyNode* predProp = prop->getChild("predicate");
1111     if (!predProp) {
1112         tniq->setAlwaysValid(true);
1113     } else {
1114         try {
1115             TechniquePredParser parser;
1116             parser.setTechnique(tniq);
1117             expression::BindingLayout& layout = parser.getBindingLayout();
1118             /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1119             SGExpressionb* validExp
1120                 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1121                                                            ->getChild(0)));
1122             if (validExp)
1123                 tniq->setValidExpression(validExp, layout);
1124             else
1125                 throw expression::ParseError("technique predicate is not a boolean expression");
1126         }
1127         catch (expression::ParseError& except)
1128         {
1129             SG_LOG(SG_INPUT, SG_ALERT,
1130                    "parsing technique predicate " << except.getMessage());
1131             tniq->setAlwaysValid(false);
1132         }
1133     }
1134     PropertyList passProps = prop->getChildren("pass");
1135     for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1136          itr != e;
1137          ++itr) {
1138         buildPass(effect, tniq, itr->ptr(), options);
1139     }
1140 }
1141
1142 // Specifically for .ac files...
1143 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1144 {
1145     SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1146     SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1147     Vec4f ambVal, difVal, specVal, emisVal;
1148     float shininess = 0.0f;
1149     const Material* mat = getStateAttribute<Material>(ss);
1150     if (mat) {
1151         ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1152         difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1153         specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1154         emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1155         shininess = mat->getShininess(Material::FRONT_AND_BACK);
1156         makeChild(matNode, "active")->setValue(true);
1157         makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1158         makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1159         makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1160         makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1161         makeChild(matNode, "shininess")->setValue(shininess);
1162         matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1163     } else {
1164         makeChild(matNode, "active")->setValue(false);
1165     }
1166     const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1167     string shadeModelString("smooth");
1168     if (sm) {
1169         ShadeModel::Mode smMode = sm->getMode();
1170         if (smMode == ShadeModel::FLAT)
1171             shadeModelString = "flat";
1172     }
1173     makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1174     string cullFaceString("off");
1175     const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1176     if (cullFace) {
1177         switch (cullFace->getMode()) {
1178         case CullFace::FRONT:
1179             cullFaceString = "front";
1180             break;
1181         case CullFace::BACK:
1182             cullFaceString = "back";
1183             break;
1184         case CullFace::FRONT_AND_BACK:
1185             cullFaceString = "front-back";
1186             break;
1187         default:
1188             break;
1189         }
1190     }
1191     makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1192     // Macintosh ATI workaround
1193     bool vertexTwoSide = cullFaceString == "off";
1194     makeChild(paramRoot, "vertex-program-two-side")->setValue(vertexTwoSide);
1195     const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1196     SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1197     if (blendFunc) {
1198         string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1199         string destMode = findName(blendFuncModes, blendFunc->getDestination());
1200         makeChild(blendNode, "active")->setValue(true);
1201         makeChild(blendNode, "source")->setStringValue(sourceMode);
1202         makeChild(blendNode, "destination")->setStringValue(destMode);
1203         makeChild(blendNode, "mode")->setValue(true);
1204     } else {
1205         makeChild(blendNode, "active")->setValue(false);
1206     }
1207     string renderingHint = findName(renderingHints, ss->getRenderingHint());
1208     makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1209     makeTextureParameters(paramRoot, ss);
1210     return true;
1211 }
1212
1213 // Walk the techniques property tree, building techniques and
1214 // passes.
1215 bool Effect::realizeTechniques(const SGReaderWriterXMLOptions* options)
1216 {
1217     if (_isRealized)
1218         return true;
1219     PropertyList tniqList = root->getChildren("technique");
1220     for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1221          itr != e;
1222          ++itr)
1223         buildTechnique(this, *itr, options);
1224     _isRealized = true;
1225     return true;
1226 }
1227
1228 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1229 {
1230     EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1231     if (!eg)
1232         return;
1233     Effect* effect = eg->getEffect();
1234     if (!effect)
1235         return;
1236     SGPropertyNode* root = getPropertyRoot();
1237     for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1238              end = effect->_extraData.end();
1239          itr != end;
1240          ++itr) {
1241         InitializeWhenAdded* adder
1242             = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1243         if (adder)
1244             adder->initOnAdd(effect, root);
1245     }
1246 }
1247
1248 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1249                                       const Effect::Key& rhs) const
1250 {
1251     if (lhs.paths.size() != rhs.paths.size()
1252         || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1253         return false;
1254     if (lhs.unmerged.valid() && rhs.unmerged.valid())
1255         return props::Compare()(lhs.unmerged, rhs.unmerged);
1256     else
1257         return lhs.unmerged == rhs.unmerged;
1258 }
1259
1260 size_t hash_value(const Effect::Key& key)
1261 {
1262     size_t seed = 0;
1263     if (key.unmerged.valid())
1264         boost::hash_combine(seed, *key.unmerged);
1265     boost::hash_range(seed, key.paths.begin(), key.paths.end());
1266     return seed;
1267 }
1268
1269 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1270 {
1271     const Effect& effect = static_cast<const Effect&>(obj);
1272
1273     fw.indent() << "techniques " << effect.techniques.size() << "\n";
1274     BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1275         fw.writeObject(*technique);
1276     }
1277     return true;
1278 }
1279
1280 namespace
1281 {
1282 osgDB::RegisterDotOsgWrapperProxy effectProxy
1283 (
1284     new Effect,
1285     "simgear::Effect",
1286     "Object simgear::Effect",
1287     0,
1288     &Effect_writeLocalData
1289     );
1290 }
1291
1292 // Property expressions for technique predicates
1293 template<typename T>
1294 class PropertyExpression : public SGExpression<T>
1295 {
1296 public:
1297     PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1298     
1299     void eval(T& value, const expression::Binding*) const
1300     {
1301         value = _pnode->getValue<T>();
1302     }
1303 protected:
1304     SGPropertyNode_ptr _pnode;
1305 };
1306
1307 class EffectPropertyListener : public SGPropertyChangeListener
1308 {
1309 public:
1310     EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1311     
1312     void valueChanged(SGPropertyNode* node)
1313     {
1314         _tniq->refreshValidity();
1315     }
1316 protected:
1317     osg::ref_ptr<Technique> _tniq;
1318 };
1319
1320 template<typename T>
1321 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1322                                      expression::Parser* parser)
1323 {
1324     SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1325                                                           true);
1326     PropertyExpression<T>* pexp = new PropertyExpression<T>(pnode);
1327     TechniquePredParser* predParser
1328         = dynamic_cast<TechniquePredParser*>(parser);
1329     if (predParser)
1330         pnode->addChangeListener(new EffectPropertyListener(predParser
1331                                                             ->getTechnique()));
1332     return pexp;
1333 }
1334
1335 expression::ExpParserRegistrar propertyRegistrar("property",
1336                                                  propertyExpressionParser<bool>);
1337
1338 expression::ExpParserRegistrar propvalueRegistrar("float-property",
1339                                                  propertyExpressionParser<float>);
1340
1341 }