1 // Copyright (C) 2008 - 2010 Tim Moore timoore33@gmail.com
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.
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.
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.
18 # include <simgear_config.h>
22 #include "EffectBuilder.hxx"
23 #include "EffectGeode.hxx"
24 #include "Technique.hxx"
26 #include "TextureBuilder.hxx"
27 #include "parseBlendFunc.hxx"
34 #include <boost/tr1/unordered_map.hpp>
36 #include <boost/bind.hpp>
37 #include <boost/foreach.hpp>
38 #include <boost/functional/hash.hpp>
39 #include <boost/tuple/tuple.hpp>
40 #include <boost/tuple/tuple_comparison.hpp>
42 #include <osg/AlphaFunc>
43 #include <osg/BlendFunc>
44 #include <osg/CullFace>
46 #include <osg/Drawable>
47 #include <osg/Material>
49 #include <osg/PolygonMode>
50 #include <osg/PolygonOffset>
52 #include <osg/Program>
53 #include <osg/Referenced>
54 #include <osg/RenderInfo>
55 #include <osg/ShadeModel>
56 #include <osg/StateSet>
57 #include <osg/Stencil>
59 #include <osg/Texture1D>
60 #include <osg/Texture2D>
61 #include <osg/Texture3D>
62 #include <osg/TextureRectangle>
63 #include <osg/Uniform>
65 #include <osgUtil/CullVisitor>
66 #include <osgDB/FileUtils>
67 #include <osgDB/Input>
68 #include <osgDB/ParameterOutput>
69 #include <osgDB/ReadFile>
70 #include <osgDB/Registry>
72 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
73 #include <simgear/scene/tgdb/userdata.hxx>
74 #include <simgear/scene/util/OsgMath.hxx>
75 #include <simgear/scene/util/SGSceneFeatures.hxx>
76 #include <simgear/scene/util/StateAttributeFactory.hxx>
77 #include <simgear/structure/OSGUtils.hxx>
78 #include <simgear/structure/SGExpression.hxx>
79 #include <simgear/props/vectorPropTemplates.hxx>
86 using namespace osgUtil;
88 using namespace effect;
91 : _cache(0), _isRealized(false)
95 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
96 : osg::Object(rhs,copyop), root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
97 _isRealized(rhs._isRealized)
99 typedef vector<ref_ptr<Technique> > TechniqueList;
100 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
101 end = rhs.techniques.end();
104 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
106 generator = rhs.generator;
109 // Assume that the last technique is always valid.
110 StateSet* Effect::getDefaultStateSet()
112 Technique* tniq = techniques.back().get();
115 Pass* pass = tniq->passes.front().get();
119 int Effect::getGenerator(Effect::Generator what) const
121 std::map<Generator,int>::const_iterator it = generator.find(what);
122 if(it == generator.end()) return -1;
123 else return it->second;
126 // There should always be a valid technique in an effect.
128 Technique* Effect::chooseTechnique(RenderInfo* info)
130 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
132 if (technique->valid(info) == Technique::VALID)
133 return technique.get();
138 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
140 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
142 technique->resizeGLObjectBuffers(maxSize);
146 void Effect::releaseGLObjects(osg::State* state) const
148 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
150 technique->releaseGLObjects(state);
159 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
160 const SGReaderWriterOptions* options)
162 Pass* pass = new Pass;
163 tniq->passes.push_back(pass);
164 for (int i = 0; i < prop->nChildren(); ++i) {
165 const SGPropertyNode* attrProp = prop->getChild(i);
166 PassAttributeBuilder* builder
167 = PassAttributeBuilder::find(attrProp->getNameString());
169 builder->buildAttribute(effect, pass, attrProp, options);
171 SG_LOG(SG_INPUT, SG_ALERT,
172 "skipping unknown pass attribute " << attrProp->getName());
176 // Default names for vector property components
177 const char* vec3Names[] = {"x", "y", "z"};
178 const char* vec4Names[] = {"x", "y", "z", "w"};
180 osg::Vec4f getColor(const SGPropertyNode* prop)
182 if (prop->nChildren() == 0) {
183 if (prop->getType() == props::VEC4D) {
184 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
185 } else if (prop->getType() == props::VEC3D) {
186 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
188 SG_LOG(SG_INPUT, SG_ALERT,
189 "invalid color property " << prop->getName() << " "
190 << prop->getStringValue());
191 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
195 static const char* colors[] = {"r", "g", "b"};
196 for (int i = 0; i < 3; ++i) {
197 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
198 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
200 const SGPropertyNode* alphaProp = prop->getChild("a");
201 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
206 struct LightingBuilder : public PassAttributeBuilder
208 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
209 const SGReaderWriterOptions* options);
212 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
213 const SGPropertyNode* prop,
214 const SGReaderWriterOptions* options)
216 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
219 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
220 : StateAttribute::OFF));
223 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
225 struct ShadeModelBuilder : public PassAttributeBuilder
227 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
228 const SGReaderWriterOptions* options)
230 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
233 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
234 string propVal = realProp->getStringValue();
235 if (propVal == "flat")
236 pass->setAttribute(attrFact->getFlatShadeModel());
237 else if (propVal == "smooth")
238 pass->setAttribute(attrFact->getSmoothShadeModel());
240 SG_LOG(SG_INPUT, SG_ALERT,
241 "invalid shade model property " << propVal);
245 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
247 struct CullFaceBuilder : PassAttributeBuilder
249 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
250 const SGReaderWriterOptions* options)
252 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
254 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
257 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
258 string propVal = realProp->getStringValue();
259 if (propVal == "front")
260 pass->setAttributeAndModes(attrFact->getCullFaceFront());
261 else if (propVal == "back")
262 pass->setAttributeAndModes(attrFact->getCullFaceBack());
263 else if (propVal == "front-back")
264 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
265 else if (propVal == "off")
266 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
268 SG_LOG(SG_INPUT, SG_ALERT,
269 "invalid cull face property " << propVal);
273 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
275 struct ColorMaskBuilder : PassAttributeBuilder
277 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
278 const SGReaderWriterOptions* options)
280 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
284 ColorMask *mask = new ColorMask;
285 Vec4 m = getColor(realProp);
286 mask->setMask(m.r() > 0.0, m.g() > 0.0, m.b() > 0.0, m.a() > 0.0);
287 pass->setAttributeAndModes(mask);
291 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
293 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
295 { "default", StateSet::DEFAULT_BIN },
296 { "opaque", StateSet::OPAQUE_BIN },
297 { "transparent", StateSet::TRANSPARENT_BIN }
300 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
302 struct HintBuilder : public PassAttributeBuilder
304 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
305 const SGReaderWriterOptions* options)
307 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
310 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
311 findAttr(renderingHints, realProp, renderingHint);
312 pass->setRenderingHint(renderingHint);
316 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
318 struct RenderBinBuilder : public PassAttributeBuilder
320 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
321 const SGReaderWriterOptions* options)
323 if (!isAttributeActive(effect, prop))
325 const SGPropertyNode* binProp = prop->getChild("bin-number");
326 binProp = getEffectPropertyNode(effect, binProp);
327 const SGPropertyNode* nameProp = prop->getChild("bin-name");
328 nameProp = getEffectPropertyNode(effect, nameProp);
329 if (binProp && nameProp) {
330 pass->setRenderBinDetails(binProp->getIntValue(),
331 nameProp->getStringValue());
334 SG_LOG(SG_INPUT, SG_ALERT,
335 "No render bin number specified in render bin section");
337 SG_LOG(SG_INPUT, SG_ALERT,
338 "No render bin name specified in render bin section");
343 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
345 struct MaterialBuilder : public PassAttributeBuilder
347 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
348 const SGReaderWriterOptions* options);
351 EffectNameValue<Material::ColorMode> colorModeInit[] =
353 { "ambient", Material::AMBIENT },
354 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
355 { "diffuse", Material::DIFFUSE },
356 { "emissive", Material::EMISSION },
357 { "specular", Material::SPECULAR },
358 { "off", Material::OFF }
360 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
362 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
363 const SGPropertyNode* prop,
364 const SGReaderWriterOptions* options)
366 if (!isAttributeActive(effect, prop))
368 Material* mat = new Material;
369 const SGPropertyNode* color = 0;
370 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
371 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
372 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
373 mat->setAmbient(Material::FRONT, getColor(color));
374 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
375 mat->setAmbient(Material::BACK, getColor(color));
376 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
377 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
378 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
379 mat->setDiffuse(Material::FRONT, getColor(color));
380 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
381 mat->setDiffuse(Material::BACK, getColor(color));
382 if ((color = getEffectPropertyChild(effect, prop, "specular")))
383 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
384 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
385 mat->setSpecular(Material::FRONT, getColor(color));
386 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
387 mat->setSpecular(Material::BACK, getColor(color));
388 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
389 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
390 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
391 mat->setEmission(Material::FRONT, getColor(color));
392 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
393 mat->setEmission(Material::BACK, getColor(color));
394 const SGPropertyNode* shininess = 0;
395 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
396 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
397 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
398 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
399 mat->setShininess(Material::FRONT, shininess->getFloatValue());
400 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
401 mat->setShininess(Material::BACK, shininess->getFloatValue());
402 Material::ColorMode colorMode = Material::OFF;
403 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
405 mat->setColorMode(colorMode);
406 pass->setAttribute(mat);
409 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
411 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
413 {"dst-alpha", BlendFunc::DST_ALPHA},
414 {"dst-color", BlendFunc::DST_COLOR},
415 {"one", BlendFunc::ONE},
416 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
417 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
418 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
419 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
420 {"src-alpha", BlendFunc::SRC_ALPHA},
421 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
422 {"src-color", BlendFunc::SRC_COLOR},
423 {"constant-color", BlendFunc::CONSTANT_COLOR},
424 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
425 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
426 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
427 {"zero", BlendFunc::ZERO}
429 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
431 struct BlendBuilder : public PassAttributeBuilder
433 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
434 const SGReaderWriterOptions* options)
436 if (!isAttributeActive(effect, prop))
438 // XXX Compatibility with early <blend> syntax; should go away
440 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
443 if (realProp->nChildren() == 0) {
444 pass->setMode(GL_BLEND, (realProp->getBoolValue()
446 : StateAttribute::OFF));
450 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
452 // XXX When dynamic parameters are supported, this code should
453 // create the blend function even if the mode is off.
454 if (pmode && !pmode->getValue<bool>()) {
455 pass->setMode(GL_BLEND, StateAttribute::OFF);
461 getEffectPropertyChild(effect, prop, "source"),
462 getEffectPropertyChild(effect, prop, "destination"),
463 getEffectPropertyChild(effect, prop, "source-rgb"),
464 getEffectPropertyChild(effect, prop, "destination-rgb"),
465 getEffectPropertyChild(effect, prop, "source-alpha"),
466 getEffectPropertyChild(effect, prop, "destination-alpha")
471 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
474 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
476 {"never", Stencil::NEVER },
477 {"less", Stencil::LESS},
478 {"equal", Stencil::EQUAL},
479 {"less-or-equal", Stencil::LEQUAL},
480 {"greater", Stencil::GREATER},
481 {"not-equal", Stencil::NOTEQUAL},
482 {"greater-or-equal", Stencil::GEQUAL},
483 {"always", Stencil::ALWAYS}
486 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
488 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
490 {"keep", Stencil::KEEP},
491 {"zero", Stencil::ZERO},
492 {"replace", Stencil::REPLACE},
493 {"increase", Stencil::INCR},
494 {"decrease", Stencil::DECR},
495 {"invert", Stencil::INVERT},
496 {"increase-wrap", Stencil::INCR_WRAP},
497 {"decrease-wrap", Stencil::DECR_WRAP}
500 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
502 struct StencilBuilder : public PassAttributeBuilder
504 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
505 const SGReaderWriterOptions* options)
507 if (!isAttributeActive(effect, prop))
510 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
512 if (pmode && !pmode->getValue<bool>()) {
513 pass->setMode(GL_STENCIL, StateAttribute::OFF);
516 const SGPropertyNode* pfunction
517 = getEffectPropertyChild(effect, prop, "function");
518 const SGPropertyNode* pvalue
519 = getEffectPropertyChild(effect, prop, "value");
520 const SGPropertyNode* pmask
521 = getEffectPropertyChild(effect, prop, "mask");
522 const SGPropertyNode* psfail
523 = getEffectPropertyChild(effect, prop, "stencil-fail");
524 const SGPropertyNode* pzfail
525 = getEffectPropertyChild(effect, prop, "z-fail");
526 const SGPropertyNode* ppass
527 = getEffectPropertyChild(effect, prop, "pass");
529 Stencil::Function func = Stencil::ALWAYS; // Always pass
531 unsigned int mask = ~0u; // All bits on
532 Stencil::Operation sfailop = Stencil::KEEP; // Keep the old values as default
533 Stencil::Operation zfailop = Stencil::KEEP;
534 Stencil::Operation passop = Stencil::KEEP;
536 ref_ptr<Stencil> stencilFunc = new Stencil;
539 findAttr(stencilFunction, pfunction, func);
541 ref = pvalue->getIntValue();
543 mask = pmask->getIntValue();
546 findAttr(stencilOperation, psfail, sfailop);
548 findAttr(stencilOperation, pzfail, zfailop);
550 findAttr(stencilOperation, ppass, passop);
552 // Set the stencil operation
553 stencilFunc->setFunction(func, ref, mask);
555 // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
556 stencilFunc->setOperation(sfailop, zfailop, passop);
558 // Add the operation to pass
559 pass->setAttributeAndModes(stencilFunc.get());
563 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
565 struct AlphaToCoverageBuilder : public PassAttributeBuilder
567 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
568 const SGReaderWriterOptions* options);
571 #ifndef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
572 #define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
575 void AlphaToCoverageBuilder::buildAttribute(Effect* effect, Pass* pass,
576 const SGPropertyNode* prop,
577 const SGReaderWriterOptions* options)
579 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
582 pass->setMode(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB, (realProp->getValue<bool>() ?
583 StateAttribute::ON : StateAttribute::OFF));
586 InstallAttributeBuilder<AlphaToCoverageBuilder> installAlphaToCoverage("alpha-to-coverage");
588 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
590 {"never", AlphaFunc::NEVER},
591 {"less", AlphaFunc::LESS},
592 {"equal", AlphaFunc::EQUAL},
593 {"lequal", AlphaFunc::LEQUAL},
594 {"greater", AlphaFunc::GREATER},
595 {"notequal", AlphaFunc::NOTEQUAL},
596 {"gequal", AlphaFunc::GEQUAL},
597 {"always", AlphaFunc::ALWAYS}
599 EffectPropertyMap<AlphaFunc::ComparisonFunction>
600 alphaComparison(alphaComparisonInit);
602 struct AlphaTestBuilder : public PassAttributeBuilder
604 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
605 const SGReaderWriterOptions* options)
607 if (!isAttributeActive(effect, prop))
609 // XXX Compatibility with early <alpha-test> syntax; should go away
611 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
614 if (realProp->nChildren() == 0) {
615 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
617 : StateAttribute::OFF));
621 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
623 // XXX When dynamic parameters are supported, this code should
624 // create the blend function even if the mode is off.
625 if (pmode && !pmode->getValue<bool>()) {
626 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
629 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
631 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
634 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
635 float refValue = 1.0f;
637 findAttr(alphaComparison, pComp, func);
639 refValue = pRef->getValue<float>();
640 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
641 pass->setAttributeAndModes(StateAttributeFactory::instance()
642 ->getStandardAlphaFunc());
644 AlphaFunc* alphaFunc = new AlphaFunc;
645 alphaFunc->setFunction(func);
646 alphaFunc->setReferenceValue(refValue);
647 pass->setAttributeAndModes(alphaFunc);
652 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
654 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
656 // Shader key, used both for shaders with relative and absolute names
657 typedef pair<string, int> ShaderKey;
659 inline ShaderKey makeShaderKey(SGPropertyNode_ptr& ptr, int shaderType)
661 return ShaderKey(ptr->getStringValue(), shaderType);
666 typedef pair<string, int> AttribKey;
667 osgDB::FilePathList paths;
668 vector<ShaderKey> shaders;
669 vector<AttribKey> attributes;
672 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
674 return (lhs.paths.size() == rhs.paths.size()
675 && equal(lhs.paths.begin(), lhs.paths.end(),
677 && lhs.shaders.size() == rhs.shaders.size()
678 && equal (lhs.shaders.begin(), lhs.shaders.end(),
680 && lhs.attributes.size() == rhs.attributes.size()
681 && equal(lhs.attributes.begin(), lhs.attributes.end(),
682 rhs.attributes.begin()));
687 size_t hash_value(const ProgramKey& key)
690 boost::hash_range(seed, key.paths.begin(), key.paths.end());
691 boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
692 boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
696 // XXX Should these be protected by a mutex? Probably
698 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
699 boost::hash<ProgramKey>, ProgramKey::EqualTo>
701 ProgramMap programMap;
702 ProgramMap resolvedProgramMap; // map with resolved shader file names
704 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
708 void reload_shaders()
710 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
712 Shader *shader = sitr->second.get();
713 string fileName = SGModelLib::findDataFile(sitr->first.first);
714 if (!fileName.empty()) {
715 shader->loadShaderSourceFromFile(fileName);
720 struct ShaderProgramBuilder : PassAttributeBuilder
722 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
723 const SGReaderWriterOptions* options);
727 EffectNameValue<GLint> geometryInputTypeInit[] =
729 {"points", GL_POINTS},
731 {"lines-adjacency", GL_LINES_ADJACENCY_EXT},
732 {"triangles", GL_TRIANGLES},
733 {"triangles-adjacency", GL_TRIANGLES_ADJACENCY_EXT},
735 EffectPropertyMap<GLint>
736 geometryInputType(geometryInputTypeInit);
739 EffectNameValue<GLint> geometryOutputTypeInit[] =
741 {"points", GL_POINTS},
742 {"line-strip", GL_LINE_STRIP},
743 {"triangle-strip", GL_TRIANGLE_STRIP}
745 EffectPropertyMap<GLint>
746 geometryOutputType(geometryOutputTypeInit);
748 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
749 const SGPropertyNode* prop,
750 const SGReaderWriterOptions*
753 using namespace boost;
754 if (!isAttributeActive(effect, prop))
756 PropertyList pVertShaders = prop->getChildren("vertex-shader");
757 PropertyList pGeomShaders = prop->getChildren("geometry-shader");
758 PropertyList pFragShaders = prop->getChildren("fragment-shader");
759 PropertyList pAttributes = prop->getChildren("attribute");
761 std::back_insert_iterator<vector<ShaderKey> > inserter(prgKey.shaders);
762 transform(pVertShaders.begin(), pVertShaders.end(), inserter,
763 boost::bind(makeShaderKey, _1, Shader::VERTEX));
764 transform(pGeomShaders.begin(), pGeomShaders.end(), inserter,
765 boost::bind(makeShaderKey, _1, Shader::GEOMETRY));
766 transform(pFragShaders.begin(), pFragShaders.end(), inserter,
767 boost::bind(makeShaderKey, _1, Shader::FRAGMENT));
768 for (PropertyList::iterator itr = pAttributes.begin(),
769 e = pAttributes.end();
772 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
774 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
776 if (!pName || ! pIndex)
777 throw BuilderException("malformed attribute property");
779 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
780 pIndex->getValue<int>()));
783 prgKey.paths = options->getDatabasePathList();
784 Program* program = 0;
785 ProgramMap::iterator pitr = programMap.find(prgKey);
786 if (pitr != programMap.end()) {
787 program = pitr->second.get();
788 pass->setAttributeAndModes(program);
791 // The program wasn't in the map using the load path passed in with
792 // the options, but it might have already been loaded using a
793 // different load path i.e., its shaders were found in the fg data
794 // directory. So, resolve the shaders' file names and look in the
795 // resolvedProgramMap for a program using those shaders.
796 ProgramKey resolvedKey;
797 resolvedKey.attributes = prgKey.attributes;
798 BOOST_FOREACH(const ShaderKey& shaderKey, prgKey.shaders)
800 const string& shaderName = shaderKey.first;
801 Shader::Type stype = (Shader::Type)shaderKey.second;
802 string fileName = SGModelLib::findDataFile(shaderName, options);
803 if (fileName.empty())
804 throw BuilderException(string("couldn't find shader ") +
806 resolvedKey.shaders.push_back(ShaderKey(fileName, stype));
808 ProgramMap::iterator resitr = resolvedProgramMap.find(resolvedKey);
809 if (resitr != resolvedProgramMap.end()) {
810 program = resitr->second.get();
811 programMap.insert(ProgramMap::value_type(prgKey, program));
812 pass->setAttributeAndModes(program);
815 program = new Program;
816 BOOST_FOREACH(const ShaderKey& skey, resolvedKey.shaders)
818 const string& fileName = skey.first;
819 Shader::Type stype = (Shader::Type)skey.second;
820 ShaderMap::iterator sitr = shaderMap.find(skey);
821 if (sitr != shaderMap.end()) {
822 program->addShader(sitr->second.get());
824 ref_ptr<Shader> shader = new Shader(stype);
825 shader->setName(fileName);
826 if (shader->loadShaderSourceFromFile(fileName)) {
827 program->addShader(shader.get());
828 shaderMap.insert(ShaderMap::value_type(skey, shader));
832 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
833 program->addBindAttribLocation(key.first, key.second);
835 const SGPropertyNode* pGeometryVerticesOut
836 = getEffectPropertyChild(effect, prop, "geometry-vertices-out");
837 if (pGeometryVerticesOut)
838 program->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT,
839 pGeometryVerticesOut->getIntValue());
840 const SGPropertyNode* pGeometryInputType
841 = getEffectPropertyChild(effect, prop, "geometry-input-type");
842 if (pGeometryInputType) {
844 findAttr(geometryInputType, pGeometryInputType->getStringValue(), type);
845 program->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT, type);
847 const SGPropertyNode* pGeometryOutputType
848 = getEffectPropertyChild(effect, prop, "geometry-output-type");
849 if (pGeometryOutputType) {
851 findAttr(geometryOutputType, pGeometryOutputType->getStringValue(),
853 program->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, type);
855 programMap.insert(ProgramMap::value_type(prgKey, program));
856 resolvedProgramMap.insert(ProgramMap::value_type(resolvedKey, program));
857 pass->setAttributeAndModes(program);
860 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
862 EffectNameValue<Uniform::Type> uniformTypesInit[] =
864 {"bool", Uniform::BOOL},
865 {"int", Uniform::INT},
866 {"float", Uniform::FLOAT},
867 {"float-vec3", Uniform::FLOAT_VEC3},
868 {"float-vec4", Uniform::FLOAT_VEC4},
869 {"sampler-1d", Uniform::SAMPLER_1D},
870 {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
871 {"sampler-2d", Uniform::SAMPLER_2D},
872 {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
873 {"sampler-3d", Uniform::SAMPLER_3D},
874 {"sampler-cube", Uniform::SAMPLER_CUBE}
876 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
878 // Optimization hack for common uniforms.
879 // XXX protect these with a mutex?
881 ref_ptr<Uniform> texture0;
882 ref_ptr<Uniform> colorMode[3];
884 struct UniformBuilder :public PassAttributeBuilder
886 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
887 const SGReaderWriterOptions* options)
889 if (!texture0.valid()) {
890 texture0 = new Uniform(Uniform::SAMPLER_2D, "texture");
892 texture0->setDataVariance(Object::STATIC);
893 for (int i = 0; i < 3; ++i) {
894 colorMode[i] = new Uniform(Uniform::INT, "colorMode");
895 colorMode[i]->set(i);
896 colorMode[i]->setDataVariance(Object::STATIC);
899 if (!isAttributeActive(effect, prop))
901 const SGPropertyNode* nameProp = prop->getChild("name");
902 const SGPropertyNode* typeProp = prop->getChild("type");
903 const SGPropertyNode* positionedProp = prop->getChild("positioned");
904 const SGPropertyNode* valProp = prop->getChild("value");
906 Uniform::Type uniformType = Uniform::FLOAT;
908 name = nameProp->getStringValue();
910 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
914 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
919 props::Type propType = valProp->getType();
922 uniformType = Uniform::BOOL;
925 uniformType = Uniform::INT;
929 break; // default float type;
931 uniformType = Uniform::FLOAT_VEC3;
934 uniformType = Uniform::FLOAT_VEC4;
937 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
942 findAttr(uniformTypes, typeProp, uniformType);
944 ref_ptr<Uniform> uniform = new Uniform;
945 uniform->setName(name);
946 uniform->setType(uniformType);
947 switch (uniformType) {
949 initFromParameters(effect, valProp, uniform.get(),
950 static_cast<bool (Uniform::*)(bool)>(&Uniform::set),
954 initFromParameters(effect, valProp, uniform.get(),
955 static_cast<bool (Uniform::*)(float)>(&Uniform::set),
958 case Uniform::FLOAT_VEC3:
959 initFromParameters(effect, valProp, uniform.get(),
960 static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
963 case Uniform::FLOAT_VEC4:
964 initFromParameters(effect, valProp, uniform.get(),
965 static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
969 case Uniform::SAMPLER_1D:
970 case Uniform::SAMPLER_2D:
971 case Uniform::SAMPLER_3D:
972 case Uniform::SAMPLER_1D_SHADOW:
973 case Uniform::SAMPLER_2D_SHADOW:
974 case Uniform::SAMPLER_CUBE:
975 initFromParameters(effect, valProp, uniform.get(),
976 static_cast<bool (Uniform::*)(int)>(&Uniform::set),
979 default: // avoid compiler warning
982 // optimize common uniforms
983 if (uniformType == Uniform::SAMPLER_2D || uniformType == Uniform::INT)
986 uniform->get(val); // 'val' remains unchanged in case of error (Uniform is a non-scalar)
987 if (uniformType == Uniform::SAMPLER_2D && val == 0
988 && name == "texture") {
990 } else if (uniformType == Uniform::INT && val >= 0 && val < 3
991 && name == "colorMode") {
992 uniform = colorMode[val];
995 pass->addUniform(uniform.get());
996 if (positionedProp && positionedProp->getBoolValue() && uniformType == Uniform::FLOAT_VEC4) {
998 uniform->get(offset);
999 pass->addPositionedUniform( name, offset );
1004 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
1006 // Not sure what to do with "name". At one point I wanted to use it to
1007 // order the passes, but I do support render bin and stuff too...
1009 struct NameBuilder : public PassAttributeBuilder
1011 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1012 const SGReaderWriterOptions* options)
1014 // name can't use <use>
1015 string name = prop->getStringValue();
1017 pass->setName(name);
1021 InstallAttributeBuilder<NameBuilder> installName("name");
1023 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
1025 {"fill", PolygonMode::FILL},
1026 {"line", PolygonMode::LINE},
1027 {"point", PolygonMode::POINT}
1029 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
1031 struct PolygonModeBuilder : public PassAttributeBuilder
1033 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1034 const SGReaderWriterOptions* options)
1036 if (!isAttributeActive(effect, prop))
1038 const SGPropertyNode* frontProp
1039 = getEffectPropertyChild(effect, prop, "front");
1040 const SGPropertyNode* backProp
1041 = getEffectPropertyChild(effect, prop, "back");
1042 ref_ptr<PolygonMode> pmode = new PolygonMode;
1043 PolygonMode::Mode frontMode = PolygonMode::FILL;
1044 PolygonMode::Mode backMode = PolygonMode::FILL;
1046 findAttr(polygonModeModes, frontProp, frontMode);
1047 pmode->setMode(PolygonMode::FRONT, frontMode);
1050 findAttr(polygonModeModes, backProp, backMode);
1051 pmode->setMode(PolygonMode::BACK, backMode);
1053 pass->setAttribute(pmode.get());
1057 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1059 struct PolygonOffsetBuilder : public PassAttributeBuilder
1061 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1062 const SGReaderWriterOptions* options)
1064 if (!isAttributeActive(effect, prop))
1067 const SGPropertyNode* factor
1068 = getEffectPropertyChild(effect, prop, "factor");
1069 const SGPropertyNode* units
1070 = getEffectPropertyChild(effect, prop, "units");
1072 ref_ptr<PolygonOffset> polyoffset = new PolygonOffset;
1074 polyoffset->setFactor(factor->getFloatValue());
1075 polyoffset->setUnits(units->getFloatValue());
1077 SG_LOG(SG_INPUT, SG_BULK,
1078 "Set PolygonOffset to " << polyoffset->getFactor() << polyoffset->getUnits() );
1080 pass->setAttributeAndModes(polyoffset.get(),
1081 StateAttribute::OVERRIDE|StateAttribute::ON);
1085 InstallAttributeBuilder<PolygonOffsetBuilder> installPolygonOffset("polygon-offset");
1087 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1089 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1090 const SGReaderWriterOptions* options)
1092 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1095 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1096 (realProp->getValue<bool>()
1097 ? StateAttribute::ON : StateAttribute::OFF));
1101 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1102 installTwoSide("vertex-program-two-side");
1104 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1106 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1107 const SGReaderWriterOptions* options)
1109 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1112 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1113 (realProp->getValue<bool>()
1114 ? StateAttribute::ON : StateAttribute::OFF));
1118 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1119 installPointSize("vertex-program-point-size");
1121 struct PointBuilder : public PassAttributeBuilder
1123 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1124 const SGReaderWriterOptions* options)
1126 float minsize = 1.0;
1127 float maxsize = 1.0;
1129 osg::Vec3f attenuation = osg::Vec3f(1.0, 1.0, 1.0);
1131 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1135 const SGPropertyNode* pminsize
1136 = getEffectPropertyChild(effect, prop, "min-size");
1137 const SGPropertyNode* pmaxsize
1138 = getEffectPropertyChild(effect, prop, "max-size");
1139 const SGPropertyNode* psize
1140 = getEffectPropertyChild(effect, prop, "size");
1141 const SGPropertyNode* pattenuation
1142 = getEffectPropertyChild(effect, prop, "attenuation");
1145 minsize = pminsize->getFloatValue();
1147 maxsize = pmaxsize->getFloatValue();
1149 size = psize->getFloatValue();
1151 attenuation = osg::Vec3f(pattenuation->getChild("x")->getFloatValue(),
1152 pattenuation->getChild("y")->getFloatValue(),
1153 pattenuation->getChild("z")->getFloatValue());
1155 osg::Point* point = new osg::Point;
1156 point->setMinSize(minsize);
1157 point->setMaxSize(maxsize);
1158 point->setSize(size);
1159 point->setDistanceAttenuation(attenuation);
1160 pass->setAttributeAndModes(point);
1164 InstallAttributeBuilder<PointBuilder>
1165 installPoint("point");
1167 EffectNameValue<Depth::Function> depthFunctionInit[] =
1169 {"never", Depth::NEVER},
1170 {"less", Depth::LESS},
1171 {"equal", Depth::EQUAL},
1172 {"lequal", Depth::LEQUAL},
1173 {"greater", Depth::GREATER},
1174 {"notequal", Depth::NOTEQUAL},
1175 {"gequal", Depth::GEQUAL},
1176 {"always", Depth::ALWAYS}
1178 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1180 struct DepthBuilder : public PassAttributeBuilder
1182 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1183 const SGReaderWriterOptions* options)
1185 if (!isAttributeActive(effect, prop))
1187 ref_ptr<Depth> depth = new Depth;
1188 const SGPropertyNode* pfunc
1189 = getEffectPropertyChild(effect, prop, "function");
1191 Depth::Function func = Depth::LESS;
1192 findAttr(depthFunction, pfunc, func);
1193 depth->setFunction(func);
1195 const SGPropertyNode* pnear
1196 = getEffectPropertyChild(effect, prop, "near");
1198 depth->setZNear(pnear->getValue<double>());
1199 const SGPropertyNode* pfar
1200 = getEffectPropertyChild(effect, prop, "far");
1202 depth->setZFar(pfar->getValue<double>());
1203 const SGPropertyNode* pmask
1204 = getEffectPropertyChild(effect, prop, "write-mask");
1206 depth->setWriteMask(pmask->getValue<bool>());
1207 const SGPropertyNode* penabled
1208 = getEffectPropertyChild(effect, prop, "enabled");
1209 bool enabled = ( penabled == 0 || penabled->getBoolValue() );
1210 pass->setAttributeAndModes(depth.get(), enabled ? osg::StateAttribute::ON : osg::StateAttribute::OFF);
1214 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1216 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1217 const SGReaderWriterOptions* options)
1219 Technique* tniq = new Technique;
1220 effect->techniques.push_back(tniq);
1221 const SGPropertyNode* predProp = prop->getChild("predicate");
1223 tniq->setAlwaysValid(true);
1226 TechniquePredParser parser;
1227 parser.setTechnique(tniq);
1228 expression::BindingLayout& layout = parser.getBindingLayout();
1229 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1230 SGExpressionb* validExp
1231 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1234 tniq->setValidExpression(validExp, layout);
1236 throw expression::ParseError("technique predicate is not a boolean expression");
1238 catch (expression::ParseError& except)
1240 SG_LOG(SG_INPUT, SG_ALERT,
1241 "parsing technique predicate " << except.getMessage());
1242 tniq->setAlwaysValid(false);
1245 PropertyList passProps = prop->getChildren("pass");
1246 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1249 buildPass(effect, tniq, itr->ptr(), options);
1253 // Specifically for .ac files...
1254 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1256 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1257 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1258 Vec4f ambVal, difVal, specVal, emisVal;
1259 float shininess = 0.0f;
1260 const Material* mat = getStateAttribute<Material>(ss);
1262 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1263 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1264 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1265 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1266 shininess = mat->getShininess(Material::FRONT_AND_BACK);
1267 makeChild(matNode, "active")->setValue(true);
1268 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1269 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1270 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1271 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1272 makeChild(matNode, "shininess")->setValue(shininess);
1273 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1275 makeChild(matNode, "active")->setValue(false);
1277 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1278 string shadeModelString("smooth");
1280 ShadeModel::Mode smMode = sm->getMode();
1281 if (smMode == ShadeModel::FLAT)
1282 shadeModelString = "flat";
1284 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1285 string cullFaceString("off");
1286 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1288 switch (cullFace->getMode()) {
1289 case CullFace::FRONT:
1290 cullFaceString = "front";
1292 case CullFace::BACK:
1293 cullFaceString = "back";
1295 case CullFace::FRONT_AND_BACK:
1296 cullFaceString = "front-back";
1302 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1303 // Macintosh ATI workaround
1304 bool vertexTwoSide = cullFaceString == "off";
1305 makeChild(paramRoot, "vertex-program-two-side")->setValue(vertexTwoSide);
1306 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1307 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1309 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1310 string destMode = findName(blendFuncModes, blendFunc->getDestination());
1311 makeChild(blendNode, "active")->setValue(true);
1312 makeChild(blendNode, "source")->setStringValue(sourceMode);
1313 makeChild(blendNode, "destination")->setStringValue(destMode);
1314 makeChild(blendNode, "mode")->setValue(true);
1316 makeChild(blendNode, "active")->setValue(false);
1318 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1319 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1320 makeTextureParameters(paramRoot, ss);
1324 // Walk the techniques property tree, building techniques and
1326 bool Effect::realizeTechniques(const SGReaderWriterOptions* options)
1330 PropertyList tniqList = root->getChildren("technique");
1331 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1334 buildTechnique(this, *itr, options);
1339 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1341 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1344 Effect* effect = eg->getEffect();
1347 SGPropertyNode* root = getPropertyRoot();
1348 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1349 end = effect->_extraData.end();
1352 InitializeWhenAdded* adder
1353 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1355 adder->initOnAdd(effect, root);
1359 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1360 const Effect::Key& rhs) const
1362 if (lhs.paths.size() != rhs.paths.size()
1363 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1365 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1366 return props::Compare()(lhs.unmerged, rhs.unmerged);
1368 return lhs.unmerged == rhs.unmerged;
1371 size_t hash_value(const Effect::Key& key)
1374 if (key.unmerged.valid())
1375 boost::hash_combine(seed, *key.unmerged);
1376 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1380 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1382 const Effect& effect = static_cast<const Effect&>(obj);
1384 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1385 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1386 fw.writeObject(*technique);
1393 osgDB::RegisterDotOsgWrapperProxy effectProxy
1397 "Object simgear::Effect",
1399 &Effect_writeLocalData
1403 // Property expressions for technique predicates
1404 template<typename T>
1405 class PropertyExpression : public SGExpression<T>
1408 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode), _listener(NULL) {}
1410 ~PropertyExpression()
1415 void eval(T& value, const expression::Binding*) const
1417 value = _pnode->getValue<T>();
1420 void setListener(SGPropertyChangeListener* l)
1425 SGPropertyNode_ptr _pnode;
1426 SGPropertyChangeListener* _listener;
1429 class EffectPropertyListener : public SGPropertyChangeListener
1432 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1434 void valueChanged(SGPropertyNode* node)
1437 _tniq->refreshValidity();
1440 virtual ~EffectPropertyListener() { }
1443 osg::observer_ptr<Technique> _tniq;
1446 template<typename T>
1447 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1448 expression::Parser* parser)
1450 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1452 PropertyExpression<T>* pexp = new PropertyExpression<T>(pnode);
1453 TechniquePredParser* predParser
1454 = dynamic_cast<TechniquePredParser*>(parser);
1456 EffectPropertyListener* l = new EffectPropertyListener(predParser
1458 pexp->setListener(l);
1459 pnode->addChangeListener(l);
1464 expression::ExpParserRegistrar propertyRegistrar("property",
1465 propertyExpressionParser<bool>);
1467 expression::ExpParserRegistrar propvalueRegistrar("float-property",
1468 propertyExpressionParser<float>);