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"
33 #include <boost/tr1/unordered_map.hpp>
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>
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
43 #include <osg/CullFace>
45 #include <osg/Drawable>
46 #include <osg/Material>
48 #include <osg/PolygonMode>
49 #include <osg/PolygonOffset>
50 #include <osg/Program>
51 #include <osg/Referenced>
52 #include <osg/RenderInfo>
53 #include <osg/ShadeModel>
54 #include <osg/StateSet>
55 #include <osg/Stencil>
57 #include <osg/Texture1D>
58 #include <osg/Texture2D>
59 #include <osg/Texture3D>
60 #include <osg/TextureRectangle>
61 #include <osg/Uniform>
63 #include <osgUtil/CullVisitor>
64 #include <osgDB/FileUtils>
65 #include <osgDB/Input>
66 #include <osgDB/ParameterOutput>
67 #include <osgDB/ReadFile>
68 #include <osgDB/Registry>
70 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
71 #include <simgear/scene/tgdb/userdata.hxx>
72 #include <simgear/scene/util/OsgMath.hxx>
73 #include <simgear/scene/util/SGSceneFeatures.hxx>
74 #include <simgear/scene/util/StateAttributeFactory.hxx>
75 #include <simgear/structure/OSGUtils.hxx>
76 #include <simgear/structure/SGExpression.hxx>
77 #include <simgear/props/vectorPropTemplates.hxx>
84 using namespace osgUtil;
86 using namespace effect;
89 : _cache(0), _isRealized(false)
93 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
94 : osg::Object(rhs,copyop), root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
95 _isRealized(rhs._isRealized)
97 typedef vector<ref_ptr<Technique> > TechniqueList;
98 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
99 end = rhs.techniques.end();
102 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
104 generator = rhs.generator;
107 // Assume that the last technique is always valid.
108 StateSet* Effect::getDefaultStateSet()
110 Technique* tniq = techniques.back().get();
113 Pass* pass = tniq->passes.front().get();
117 int Effect::getGenerator(Effect::Generator what) const
119 std::map<Generator,int>::const_iterator it = generator.find(what);
120 if(it == generator.end()) return -1;
121 else return it->second;
124 // There should always be a valid technique in an effect.
126 Technique* Effect::chooseTechnique(RenderInfo* info)
128 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
130 if (technique->valid(info) == Technique::VALID)
131 return technique.get();
136 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
138 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
140 technique->resizeGLObjectBuffers(maxSize);
144 void Effect::releaseGLObjects(osg::State* state) const
146 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
148 technique->releaseGLObjects(state);
157 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
158 const SGReaderWriterOptions* options)
160 Pass* pass = new Pass;
161 tniq->passes.push_back(pass);
162 for (int i = 0; i < prop->nChildren(); ++i) {
163 const SGPropertyNode* attrProp = prop->getChild(i);
164 PassAttributeBuilder* builder
165 = PassAttributeBuilder::find(attrProp->getNameString());
167 builder->buildAttribute(effect, pass, attrProp, options);
169 SG_LOG(SG_INPUT, SG_ALERT,
170 "skipping unknown pass attribute " << attrProp->getName());
174 // Default names for vector property components
175 const char* vec3Names[] = {"x", "y", "z"};
176 const char* vec4Names[] = {"x", "y", "z", "w"};
178 osg::Vec4f getColor(const SGPropertyNode* prop)
180 if (prop->nChildren() == 0) {
181 if (prop->getType() == props::VEC4D) {
182 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
183 } else if (prop->getType() == props::VEC3D) {
184 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
186 SG_LOG(SG_INPUT, SG_ALERT,
187 "invalid color property " << prop->getName() << " "
188 << prop->getStringValue());
189 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
193 static const char* colors[] = {"r", "g", "b"};
194 for (int i = 0; i < 3; ++i) {
195 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
196 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
198 const SGPropertyNode* alphaProp = prop->getChild("a");
199 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
204 struct LightingBuilder : public PassAttributeBuilder
206 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
207 const SGReaderWriterOptions* options);
210 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
211 const SGPropertyNode* prop,
212 const SGReaderWriterOptions* options)
214 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
217 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
218 : StateAttribute::OFF));
221 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
223 struct ShadeModelBuilder : public PassAttributeBuilder
225 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
226 const SGReaderWriterOptions* options)
228 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
231 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
232 string propVal = realProp->getStringValue();
233 if (propVal == "flat")
234 pass->setAttribute(attrFact->getFlatShadeModel());
235 else if (propVal == "smooth")
236 pass->setAttribute(attrFact->getSmoothShadeModel());
238 SG_LOG(SG_INPUT, SG_ALERT,
239 "invalid shade model property " << propVal);
243 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
245 struct CullFaceBuilder : PassAttributeBuilder
247 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
248 const SGReaderWriterOptions* options)
250 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
252 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
255 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
256 string propVal = realProp->getStringValue();
257 if (propVal == "front")
258 pass->setAttributeAndModes(attrFact->getCullFaceFront());
259 else if (propVal == "back")
260 pass->setAttributeAndModes(attrFact->getCullFaceBack());
261 else if (propVal == "front-back")
262 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
263 else if (propVal == "off")
264 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
266 SG_LOG(SG_INPUT, SG_ALERT,
267 "invalid cull face property " << propVal);
271 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
273 struct ColorMaskBuilder : PassAttributeBuilder
275 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
276 const SGReaderWriterOptions* options)
278 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
282 ColorMask *mask = new ColorMask;
283 Vec4 m = getColor(realProp);
284 mask->setMask(m.r() > 0.0, m.g() > 0.0, m.b() > 0.0, m.a() > 0.0);
285 pass->setAttributeAndModes(mask);
289 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
291 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
293 { "default", StateSet::DEFAULT_BIN },
294 { "opaque", StateSet::OPAQUE_BIN },
295 { "transparent", StateSet::TRANSPARENT_BIN }
298 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
300 struct HintBuilder : public PassAttributeBuilder
302 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
303 const SGReaderWriterOptions* options)
305 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
308 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
309 findAttr(renderingHints, realProp, renderingHint);
310 pass->setRenderingHint(renderingHint);
314 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
316 struct RenderBinBuilder : public PassAttributeBuilder
318 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
319 const SGReaderWriterOptions* options)
321 if (!isAttributeActive(effect, prop))
323 const SGPropertyNode* binProp = prop->getChild("bin-number");
324 binProp = getEffectPropertyNode(effect, binProp);
325 const SGPropertyNode* nameProp = prop->getChild("bin-name");
326 nameProp = getEffectPropertyNode(effect, nameProp);
327 if (binProp && nameProp) {
328 pass->setRenderBinDetails(binProp->getIntValue(),
329 nameProp->getStringValue());
332 SG_LOG(SG_INPUT, SG_ALERT,
333 "No render bin number specified in render bin section");
335 SG_LOG(SG_INPUT, SG_ALERT,
336 "No render bin name specified in render bin section");
341 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
343 struct MaterialBuilder : public PassAttributeBuilder
345 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
346 const SGReaderWriterOptions* options);
349 EffectNameValue<Material::ColorMode> colorModeInit[] =
351 { "ambient", Material::AMBIENT },
352 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
353 { "diffuse", Material::DIFFUSE },
354 { "emissive", Material::EMISSION },
355 { "specular", Material::SPECULAR },
356 { "off", Material::OFF }
358 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
360 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
361 const SGPropertyNode* prop,
362 const SGReaderWriterOptions* options)
364 if (!isAttributeActive(effect, prop))
366 Material* mat = new Material;
367 const SGPropertyNode* color = 0;
368 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
369 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
370 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
371 mat->setAmbient(Material::FRONT, getColor(color));
372 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
373 mat->setAmbient(Material::BACK, getColor(color));
374 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
375 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
376 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
377 mat->setDiffuse(Material::FRONT, getColor(color));
378 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
379 mat->setDiffuse(Material::BACK, getColor(color));
380 if ((color = getEffectPropertyChild(effect, prop, "specular")))
381 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
382 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
383 mat->setSpecular(Material::FRONT, getColor(color));
384 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
385 mat->setSpecular(Material::BACK, getColor(color));
386 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
387 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
388 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
389 mat->setEmission(Material::FRONT, getColor(color));
390 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
391 mat->setEmission(Material::BACK, getColor(color));
392 const SGPropertyNode* shininess = 0;
393 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
394 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
395 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
396 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
397 mat->setShininess(Material::FRONT, shininess->getFloatValue());
398 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
399 mat->setShininess(Material::BACK, shininess->getFloatValue());
400 Material::ColorMode colorMode = Material::OFF;
401 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
403 mat->setColorMode(colorMode);
404 pass->setAttribute(mat);
407 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
409 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
411 {"dst-alpha", BlendFunc::DST_ALPHA},
412 {"dst-color", BlendFunc::DST_COLOR},
413 {"one", BlendFunc::ONE},
414 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
415 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
416 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
417 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
418 {"src-alpha", BlendFunc::SRC_ALPHA},
419 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
420 {"src-color", BlendFunc::SRC_COLOR},
421 {"constant-color", BlendFunc::CONSTANT_COLOR},
422 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
423 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
424 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
425 {"zero", BlendFunc::ZERO}
427 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
429 struct BlendBuilder : public PassAttributeBuilder
431 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
432 const SGReaderWriterOptions* options)
434 if (!isAttributeActive(effect, prop))
436 // XXX Compatibility with early <blend> syntax; should go away
438 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
441 if (realProp->nChildren() == 0) {
442 pass->setMode(GL_BLEND, (realProp->getBoolValue()
444 : StateAttribute::OFF));
448 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
450 // XXX When dynamic parameters are supported, this code should
451 // create the blend function even if the mode is off.
452 if (pmode && !pmode->getValue<bool>()) {
453 pass->setMode(GL_BLEND, StateAttribute::OFF);
456 const SGPropertyNode* psource
457 = getEffectPropertyChild(effect, prop, "source");
458 const SGPropertyNode* pdestination
459 = getEffectPropertyChild(effect, prop, "destination");
460 const SGPropertyNode* psourceRGB
461 = getEffectPropertyChild(effect, prop, "source-rgb");
462 const SGPropertyNode* psourceAlpha
463 = getEffectPropertyChild(effect, prop, "source-alpha");
464 const SGPropertyNode* pdestRGB
465 = getEffectPropertyChild(effect, prop, "destination-rgb");
466 const SGPropertyNode* pdestAlpha
467 = getEffectPropertyChild(effect, prop, "destination-alpha");
468 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
469 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
471 findAttr(blendFuncModes, psource, sourceMode);
473 findAttr(blendFuncModes, pdestination, destMode);
474 if (psource && pdestination
475 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
476 && sourceMode == BlendFunc::SRC_ALPHA
477 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
478 pass->setAttributeAndModes(StateAttributeFactory::instance()
479 ->getStandardBlendFunc());
482 BlendFunc* blendFunc = new BlendFunc;
484 blendFunc->setSource(sourceMode);
486 blendFunc->setDestination(destMode);
488 BlendFunc::BlendFuncMode sourceRGBMode;
489 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
490 blendFunc->setSourceRGB(sourceRGBMode);
493 BlendFunc::BlendFuncMode destRGBMode;
494 findAttr(blendFuncModes, pdestRGB, destRGBMode);
495 blendFunc->setDestinationRGB(destRGBMode);
498 BlendFunc::BlendFuncMode sourceAlphaMode;
499 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
500 blendFunc->setSourceAlpha(sourceAlphaMode);
503 BlendFunc::BlendFuncMode destAlphaMode;
504 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
505 blendFunc->setDestinationAlpha(destAlphaMode);
507 pass->setAttributeAndModes(blendFunc);
511 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
514 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
516 {"never", Stencil::NEVER },
517 {"less", Stencil::LESS},
518 {"equal", Stencil::EQUAL},
519 {"less-or-equal", Stencil::LEQUAL},
520 {"greater", Stencil::GREATER},
521 {"not-equal", Stencil::NOTEQUAL},
522 {"greater-or-equal", Stencil::GEQUAL},
523 {"always", Stencil::ALWAYS}
526 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
528 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
530 {"keep", Stencil::KEEP},
531 {"zero", Stencil::ZERO},
532 {"replace", Stencil::REPLACE},
533 {"increase", Stencil::INCR},
534 {"decrease", Stencil::DECR},
535 {"invert", Stencil::INVERT},
536 {"increase-wrap", Stencil::INCR_WRAP},
537 {"decrease-wrap", Stencil::DECR_WRAP}
540 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
542 struct StencilBuilder : public PassAttributeBuilder
544 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
545 const SGReaderWriterOptions* options)
547 if (!isAttributeActive(effect, prop))
550 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
552 if (pmode && !pmode->getValue<bool>()) {
553 pass->setMode(GL_STENCIL, StateAttribute::OFF);
556 const SGPropertyNode* pfunction
557 = getEffectPropertyChild(effect, prop, "function");
558 const SGPropertyNode* pvalue
559 = getEffectPropertyChild(effect, prop, "value");
560 const SGPropertyNode* pmask
561 = getEffectPropertyChild(effect, prop, "mask");
562 const SGPropertyNode* psfail
563 = getEffectPropertyChild(effect, prop, "stencil-fail");
564 const SGPropertyNode* pzfail
565 = getEffectPropertyChild(effect, prop, "z-fail");
566 const SGPropertyNode* ppass
567 = getEffectPropertyChild(effect, prop, "pass");
569 Stencil::Function func = Stencil::ALWAYS; // Always pass
571 unsigned int mask = ~0u; // All bits on
572 Stencil::Operation sfailop = Stencil::KEEP; // Keep the old values as default
573 Stencil::Operation zfailop = Stencil::KEEP;
574 Stencil::Operation passop = Stencil::KEEP;
576 ref_ptr<Stencil> stencilFunc = new Stencil;
579 findAttr(stencilFunction, pfunction, func);
581 ref = pvalue->getIntValue();
583 mask = pmask->getIntValue();
586 findAttr(stencilOperation, psfail, sfailop);
588 findAttr(stencilOperation, pzfail, zfailop);
590 findAttr(stencilOperation, ppass, passop);
592 // Set the stencil operation
593 stencilFunc->setFunction(func, ref, mask);
595 // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
596 stencilFunc->setOperation(sfailop, zfailop, passop);
598 // Add the operation to pass
599 pass->setAttributeAndModes(stencilFunc.get());
603 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
605 struct AlphaToCoverageBuilder : public PassAttributeBuilder
607 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
608 const SGReaderWriterOptions* options);
611 #ifndef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
612 #define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
615 void AlphaToCoverageBuilder::buildAttribute(Effect* effect, Pass* pass,
616 const SGPropertyNode* prop,
617 const SGReaderWriterOptions* options)
619 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
622 pass->setMode(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB, (realProp->getValue<bool>() ?
623 StateAttribute::ON : StateAttribute::OFF));
626 InstallAttributeBuilder<AlphaToCoverageBuilder> installAlphaToCoverage("alpha-to-coverage");
628 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
630 {"never", AlphaFunc::NEVER},
631 {"less", AlphaFunc::LESS},
632 {"equal", AlphaFunc::EQUAL},
633 {"lequal", AlphaFunc::LEQUAL},
634 {"greater", AlphaFunc::GREATER},
635 {"notequal", AlphaFunc::NOTEQUAL},
636 {"gequal", AlphaFunc::GEQUAL},
637 {"always", AlphaFunc::ALWAYS}
639 EffectPropertyMap<AlphaFunc::ComparisonFunction>
640 alphaComparison(alphaComparisonInit);
642 struct AlphaTestBuilder : public PassAttributeBuilder
644 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
645 const SGReaderWriterOptions* options)
647 if (!isAttributeActive(effect, prop))
649 // XXX Compatibility with early <alpha-test> syntax; should go away
651 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
654 if (realProp->nChildren() == 0) {
655 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
657 : StateAttribute::OFF));
661 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
663 // XXX When dynamic parameters are supported, this code should
664 // create the blend function even if the mode is off.
665 if (pmode && !pmode->getValue<bool>()) {
666 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
669 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
671 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
674 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
675 float refValue = 1.0f;
677 findAttr(alphaComparison, pComp, func);
679 refValue = pRef->getValue<float>();
680 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
681 pass->setAttributeAndModes(StateAttributeFactory::instance()
682 ->getStandardAlphaFunc());
684 AlphaFunc* alphaFunc = new AlphaFunc;
685 alphaFunc->setFunction(func);
686 alphaFunc->setReferenceValue(refValue);
687 pass->setAttributeAndModes(alphaFunc);
692 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
694 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
696 // Shader key, used both for shaders with relative and absolute names
697 typedef pair<string, int> ShaderKey;
699 inline ShaderKey makeShaderKey(SGPropertyNode_ptr& ptr, int shaderType)
701 return ShaderKey(ptr->getStringValue(), shaderType);
706 typedef pair<string, int> AttribKey;
707 osgDB::FilePathList paths;
708 vector<ShaderKey> shaders;
709 vector<AttribKey> attributes;
712 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
714 return (lhs.paths.size() == rhs.paths.size()
715 && equal(lhs.paths.begin(), lhs.paths.end(),
717 && lhs.shaders.size() == rhs.shaders.size()
718 && equal (lhs.shaders.begin(), lhs.shaders.end(),
720 && lhs.attributes.size() == rhs.attributes.size()
721 && equal(lhs.attributes.begin(), lhs.attributes.end(),
722 rhs.attributes.begin()));
727 size_t hash_value(const ProgramKey& key)
730 boost::hash_range(seed, key.paths.begin(), key.paths.end());
731 boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
732 boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
736 // XXX Should these be protected by a mutex? Probably
738 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
739 boost::hash<ProgramKey>, ProgramKey::EqualTo>
741 ProgramMap programMap;
742 ProgramMap resolvedProgramMap; // map with resolved shader file names
744 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
748 void reload_shaders()
750 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
752 Shader *shader = sitr->second.get();
753 string fileName = SGModelLib::findDataFile(sitr->first.first);
754 if (!fileName.empty()) {
755 shader->loadShaderSourceFromFile(fileName);
760 struct ShaderProgramBuilder : PassAttributeBuilder
762 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
763 const SGReaderWriterOptions* options);
767 EffectNameValue<GLint> geometryInputTypeInit[] =
769 {"points", GL_POINTS},
771 {"lines-adjacency", GL_LINES_ADJACENCY_EXT},
772 {"triangles", GL_TRIANGLES},
773 {"triangles-adjacency", GL_TRIANGLES_ADJACENCY_EXT},
775 EffectPropertyMap<GLint>
776 geometryInputType(geometryInputTypeInit);
779 EffectNameValue<GLint> geometryOutputTypeInit[] =
781 {"points", GL_POINTS},
782 {"line-strip", GL_LINE_STRIP},
783 {"triangle-strip", GL_TRIANGLE_STRIP}
785 EffectPropertyMap<GLint>
786 geometryOutputType(geometryOutputTypeInit);
788 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
789 const SGPropertyNode* prop,
790 const SGReaderWriterOptions*
793 using namespace boost;
794 if (!isAttributeActive(effect, prop))
796 PropertyList pVertShaders = prop->getChildren("vertex-shader");
797 PropertyList pGeomShaders = prop->getChildren("geometry-shader");
798 PropertyList pFragShaders = prop->getChildren("fragment-shader");
799 PropertyList pAttributes = prop->getChildren("attribute");
801 std::back_insert_iterator<vector<ShaderKey> > inserter(prgKey.shaders);
802 transform(pVertShaders.begin(), pVertShaders.end(), inserter,
803 boost::bind(makeShaderKey, _1, Shader::VERTEX));
804 transform(pGeomShaders.begin(), pGeomShaders.end(), inserter,
805 boost::bind(makeShaderKey, _1, Shader::GEOMETRY));
806 transform(pFragShaders.begin(), pFragShaders.end(), inserter,
807 boost::bind(makeShaderKey, _1, Shader::FRAGMENT));
808 for (PropertyList::iterator itr = pAttributes.begin(),
809 e = pAttributes.end();
812 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
814 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
816 if (!pName || ! pIndex)
817 throw BuilderException("malformed attribute property");
819 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
820 pIndex->getValue<int>()));
823 prgKey.paths = options->getDatabasePathList();
824 Program* program = 0;
825 ProgramMap::iterator pitr = programMap.find(prgKey);
826 if (pitr != programMap.end()) {
827 program = pitr->second.get();
828 pass->setAttributeAndModes(program);
831 // The program wasn't in the map using the load path passed in with
832 // the options, but it might have already been loaded using a
833 // different load path i.e., its shaders were found in the fg data
834 // directory. So, resolve the shaders' file names and look in the
835 // resolvedProgramMap for a program using those shaders.
836 ProgramKey resolvedKey;
837 resolvedKey.attributes = prgKey.attributes;
838 BOOST_FOREACH(const ShaderKey& shaderKey, prgKey.shaders)
840 const string& shaderName = shaderKey.first;
841 Shader::Type stype = (Shader::Type)shaderKey.second;
842 string fileName = SGModelLib::findDataFile(shaderName, options);
843 if (fileName.empty())
844 throw BuilderException(string("couldn't find shader ") +
846 resolvedKey.shaders.push_back(ShaderKey(fileName, stype));
848 ProgramMap::iterator resitr = resolvedProgramMap.find(resolvedKey);
849 if (resitr != resolvedProgramMap.end()) {
850 program = resitr->second.get();
851 programMap.insert(ProgramMap::value_type(prgKey, program));
852 pass->setAttributeAndModes(program);
855 program = new Program;
856 BOOST_FOREACH(const ShaderKey& skey, resolvedKey.shaders)
858 const string& fileName = skey.first;
859 Shader::Type stype = (Shader::Type)skey.second;
860 ShaderMap::iterator sitr = shaderMap.find(skey);
861 if (sitr != shaderMap.end()) {
862 program->addShader(sitr->second.get());
864 ref_ptr<Shader> shader = new Shader(stype);
865 shader->setName(fileName);
866 if (shader->loadShaderSourceFromFile(fileName)) {
867 program->addShader(shader.get());
868 shaderMap.insert(ShaderMap::value_type(skey, shader));
872 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
873 program->addBindAttribLocation(key.first, key.second);
875 const SGPropertyNode* pGeometryVerticesOut
876 = getEffectPropertyChild(effect, prop, "geometry-vertices-out");
877 if (pGeometryVerticesOut)
878 program->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT,
879 pGeometryVerticesOut->getIntValue());
880 const SGPropertyNode* pGeometryInputType
881 = getEffectPropertyChild(effect, prop, "geometry-input-type");
882 if (pGeometryInputType) {
884 findAttr(geometryInputType, pGeometryInputType->getStringValue(), type);
885 program->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT, type);
887 const SGPropertyNode* pGeometryOutputType
888 = getEffectPropertyChild(effect, prop, "geometry-output-type");
889 if (pGeometryOutputType) {
891 findAttr(geometryOutputType, pGeometryOutputType->getStringValue(),
893 program->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, type);
895 programMap.insert(ProgramMap::value_type(prgKey, program));
896 resolvedProgramMap.insert(ProgramMap::value_type(resolvedKey, program));
897 pass->setAttributeAndModes(program);
900 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
902 EffectNameValue<Uniform::Type> uniformTypesInit[] =
904 {"bool", Uniform::BOOL},
905 {"int", Uniform::INT},
906 {"float", Uniform::FLOAT},
907 {"float-vec3", Uniform::FLOAT_VEC3},
908 {"float-vec4", Uniform::FLOAT_VEC4},
909 {"sampler-1d", Uniform::SAMPLER_1D},
910 {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
911 {"sampler-2d", Uniform::SAMPLER_2D},
912 {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
913 {"sampler-3d", Uniform::SAMPLER_3D},
914 {"sampler-cube", Uniform::SAMPLER_CUBE}
916 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
918 // Optimization hack for common uniforms.
919 // XXX protect these with a mutex?
921 ref_ptr<Uniform> texture0;
922 ref_ptr<Uniform> colorMode[3];
924 struct UniformBuilder :public PassAttributeBuilder
926 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
927 const SGReaderWriterOptions* options)
929 if (!texture0.valid()) {
930 texture0 = new Uniform(Uniform::SAMPLER_2D, "texture");
932 texture0->setDataVariance(Object::STATIC);
933 for (int i = 0; i < 3; ++i) {
934 colorMode[i] = new Uniform(Uniform::INT, "colorMode");
935 colorMode[i]->set(i);
936 colorMode[i]->setDataVariance(Object::STATIC);
939 if (!isAttributeActive(effect, prop))
941 const SGPropertyNode* nameProp = prop->getChild("name");
942 const SGPropertyNode* typeProp = prop->getChild("type");
943 const SGPropertyNode* positionedProp = prop->getChild("positioned");
944 const SGPropertyNode* valProp = prop->getChild("value");
946 Uniform::Type uniformType = Uniform::FLOAT;
948 name = nameProp->getStringValue();
950 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
954 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
959 props::Type propType = valProp->getType();
962 uniformType = Uniform::BOOL;
965 uniformType = Uniform::INT;
969 break; // default float type;
971 uniformType = Uniform::FLOAT_VEC3;
974 uniformType = Uniform::FLOAT_VEC4;
977 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
982 findAttr(uniformTypes, typeProp, uniformType);
984 ref_ptr<Uniform> uniform = new Uniform;
985 uniform->setName(name);
986 uniform->setType(uniformType);
987 switch (uniformType) {
989 initFromParameters(effect, valProp, uniform.get(),
990 static_cast<bool (Uniform::*)(bool)>(&Uniform::set),
994 initFromParameters(effect, valProp, uniform.get(),
995 static_cast<bool (Uniform::*)(float)>(&Uniform::set),
998 case Uniform::FLOAT_VEC3:
999 initFromParameters(effect, valProp, uniform.get(),
1000 static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
1001 vec3Names, options);
1003 case Uniform::FLOAT_VEC4:
1004 initFromParameters(effect, valProp, uniform.get(),
1005 static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
1006 vec4Names, options);
1009 case Uniform::SAMPLER_1D:
1010 case Uniform::SAMPLER_2D:
1011 case Uniform::SAMPLER_3D:
1012 case Uniform::SAMPLER_1D_SHADOW:
1013 case Uniform::SAMPLER_2D_SHADOW:
1014 case Uniform::SAMPLER_CUBE:
1015 initFromParameters(effect, valProp, uniform.get(),
1016 static_cast<bool (Uniform::*)(int)>(&Uniform::set),
1019 default: // avoid compiler warning
1022 // optimize common uniforms
1023 if (uniformType == Uniform::SAMPLER_2D || uniformType == Uniform::INT)
1026 uniform->get(val); // 'val' remains unchanged in case of error (Uniform is a non-scalar)
1027 if (uniformType == Uniform::SAMPLER_2D && val == 0
1028 && name == "texture") {
1030 } else if (uniformType == Uniform::INT && val >= 0 && val < 3
1031 && name == "colorMode") {
1032 uniform = colorMode[val];
1035 pass->addUniform(uniform.get());
1036 if (positionedProp && positionedProp->getBoolValue() && uniformType == Uniform::FLOAT_VEC4) {
1038 uniform->get(offset);
1039 pass->addPositionedUniform( name, offset );
1044 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
1046 // Not sure what to do with "name". At one point I wanted to use it to
1047 // order the passes, but I do support render bin and stuff too...
1049 struct NameBuilder : public PassAttributeBuilder
1051 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1052 const SGReaderWriterOptions* options)
1054 // name can't use <use>
1055 string name = prop->getStringValue();
1057 pass->setName(name);
1061 InstallAttributeBuilder<NameBuilder> installName("name");
1063 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
1065 {"fill", PolygonMode::FILL},
1066 {"line", PolygonMode::LINE},
1067 {"point", PolygonMode::POINT}
1069 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
1071 struct PolygonModeBuilder : public PassAttributeBuilder
1073 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1074 const SGReaderWriterOptions* options)
1076 if (!isAttributeActive(effect, prop))
1078 const SGPropertyNode* frontProp
1079 = getEffectPropertyChild(effect, prop, "front");
1080 const SGPropertyNode* backProp
1081 = getEffectPropertyChild(effect, prop, "back");
1082 ref_ptr<PolygonMode> pmode = new PolygonMode;
1083 PolygonMode::Mode frontMode = PolygonMode::FILL;
1084 PolygonMode::Mode backMode = PolygonMode::FILL;
1086 findAttr(polygonModeModes, frontProp, frontMode);
1087 pmode->setMode(PolygonMode::FRONT, frontMode);
1090 findAttr(polygonModeModes, backProp, backMode);
1091 pmode->setMode(PolygonMode::BACK, backMode);
1093 pass->setAttribute(pmode.get());
1097 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1099 struct PolygonOffsetBuilder : public PassAttributeBuilder
1101 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1102 const SGReaderWriterOptions* options)
1104 if (!isAttributeActive(effect, prop))
1107 const SGPropertyNode* factor
1108 = getEffectPropertyChild(effect, prop, "factor");
1109 const SGPropertyNode* units
1110 = getEffectPropertyChild(effect, prop, "units");
1112 ref_ptr<PolygonOffset> polyoffset = new PolygonOffset;
1114 polyoffset->setFactor(factor->getFloatValue());
1115 polyoffset->setUnits(units->getFloatValue());
1117 SG_LOG(SG_INPUT, SG_BULK,
1118 "Set PolygonOffset to " << polyoffset->getFactor() << polyoffset->getUnits() );
1120 pass->setAttributeAndModes(polyoffset.get(),
1121 StateAttribute::OVERRIDE|StateAttribute::ON);
1125 InstallAttributeBuilder<PolygonOffsetBuilder> installPolygonOffset("polygon-offset");
1127 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1129 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1130 const SGReaderWriterOptions* options)
1132 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1135 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1136 (realProp->getValue<bool>()
1137 ? StateAttribute::ON : StateAttribute::OFF));
1141 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1142 installTwoSide("vertex-program-two-side");
1144 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1146 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1147 const SGReaderWriterOptions* options)
1149 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1152 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1153 (realProp->getValue<bool>()
1154 ? StateAttribute::ON : StateAttribute::OFF));
1158 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1159 installPointSize("vertex-program-point-size");
1161 EffectNameValue<Depth::Function> depthFunctionInit[] =
1163 {"never", Depth::NEVER},
1164 {"less", Depth::LESS},
1165 {"equal", Depth::EQUAL},
1166 {"lequal", Depth::LEQUAL},
1167 {"greater", Depth::GREATER},
1168 {"notequal", Depth::NOTEQUAL},
1169 {"gequal", Depth::GEQUAL},
1170 {"always", Depth::ALWAYS}
1172 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1174 struct DepthBuilder : public PassAttributeBuilder
1176 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1177 const SGReaderWriterOptions* options)
1179 if (!isAttributeActive(effect, prop))
1181 ref_ptr<Depth> depth = new Depth;
1182 const SGPropertyNode* pfunc
1183 = getEffectPropertyChild(effect, prop, "function");
1185 Depth::Function func = Depth::LESS;
1186 findAttr(depthFunction, pfunc, func);
1187 depth->setFunction(func);
1189 const SGPropertyNode* pnear
1190 = getEffectPropertyChild(effect, prop, "near");
1192 depth->setZNear(pnear->getValue<double>());
1193 const SGPropertyNode* pfar
1194 = getEffectPropertyChild(effect, prop, "far");
1196 depth->setZFar(pfar->getValue<double>());
1197 const SGPropertyNode* pmask
1198 = getEffectPropertyChild(effect, prop, "write-mask");
1200 depth->setWriteMask(pmask->getValue<bool>());
1201 const SGPropertyNode* penabled
1202 = getEffectPropertyChild(effect, prop, "enabled");
1203 bool enabled = ( penabled == 0 || penabled->getBoolValue() );
1204 pass->setAttributeAndModes(depth.get(), enabled ? osg::StateAttribute::ON : osg::StateAttribute::OFF);
1208 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1210 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1211 const SGReaderWriterOptions* options)
1213 Technique* tniq = new Technique;
1214 effect->techniques.push_back(tniq);
1215 const SGPropertyNode* predProp = prop->getChild("predicate");
1217 tniq->setAlwaysValid(true);
1220 TechniquePredParser parser;
1221 parser.setTechnique(tniq);
1222 expression::BindingLayout& layout = parser.getBindingLayout();
1223 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1224 SGExpressionb* validExp
1225 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1228 tniq->setValidExpression(validExp, layout);
1230 throw expression::ParseError("technique predicate is not a boolean expression");
1232 catch (expression::ParseError& except)
1234 SG_LOG(SG_INPUT, SG_ALERT,
1235 "parsing technique predicate " << except.getMessage());
1236 tniq->setAlwaysValid(false);
1239 PropertyList passProps = prop->getChildren("pass");
1240 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1243 buildPass(effect, tniq, itr->ptr(), options);
1247 // Specifically for .ac files...
1248 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1250 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1251 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1252 Vec4f ambVal, difVal, specVal, emisVal;
1253 float shininess = 0.0f;
1254 const Material* mat = getStateAttribute<Material>(ss);
1256 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1257 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1258 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1259 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1260 shininess = mat->getShininess(Material::FRONT_AND_BACK);
1261 makeChild(matNode, "active")->setValue(true);
1262 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1263 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1264 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1265 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1266 makeChild(matNode, "shininess")->setValue(shininess);
1267 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1269 makeChild(matNode, "active")->setValue(false);
1271 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1272 string shadeModelString("smooth");
1274 ShadeModel::Mode smMode = sm->getMode();
1275 if (smMode == ShadeModel::FLAT)
1276 shadeModelString = "flat";
1278 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1279 string cullFaceString("off");
1280 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1282 switch (cullFace->getMode()) {
1283 case CullFace::FRONT:
1284 cullFaceString = "front";
1286 case CullFace::BACK:
1287 cullFaceString = "back";
1289 case CullFace::FRONT_AND_BACK:
1290 cullFaceString = "front-back";
1296 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1297 // Macintosh ATI workaround
1298 bool vertexTwoSide = cullFaceString == "off";
1299 makeChild(paramRoot, "vertex-program-two-side")->setValue(vertexTwoSide);
1300 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1301 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1303 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1304 string destMode = findName(blendFuncModes, blendFunc->getDestination());
1305 makeChild(blendNode, "active")->setValue(true);
1306 makeChild(blendNode, "source")->setStringValue(sourceMode);
1307 makeChild(blendNode, "destination")->setStringValue(destMode);
1308 makeChild(blendNode, "mode")->setValue(true);
1310 makeChild(blendNode, "active")->setValue(false);
1312 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1313 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1314 makeTextureParameters(paramRoot, ss);
1318 // Walk the techniques property tree, building techniques and
1320 bool Effect::realizeTechniques(const SGReaderWriterOptions* options)
1324 PropertyList tniqList = root->getChildren("technique");
1325 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1328 buildTechnique(this, *itr, options);
1333 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1335 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1338 Effect* effect = eg->getEffect();
1341 SGPropertyNode* root = getPropertyRoot();
1342 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1343 end = effect->_extraData.end();
1346 InitializeWhenAdded* adder
1347 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1349 adder->initOnAdd(effect, root);
1353 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1354 const Effect::Key& rhs) const
1356 if (lhs.paths.size() != rhs.paths.size()
1357 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1359 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1360 return props::Compare()(lhs.unmerged, rhs.unmerged);
1362 return lhs.unmerged == rhs.unmerged;
1365 size_t hash_value(const Effect::Key& key)
1368 if (key.unmerged.valid())
1369 boost::hash_combine(seed, *key.unmerged);
1370 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1374 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1376 const Effect& effect = static_cast<const Effect&>(obj);
1378 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1379 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1380 fw.writeObject(*technique);
1387 osgDB::RegisterDotOsgWrapperProxy effectProxy
1391 "Object simgear::Effect",
1393 &Effect_writeLocalData
1397 // Property expressions for technique predicates
1398 template<typename T>
1399 class PropertyExpression : public SGExpression<T>
1402 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1404 void eval(T& value, const expression::Binding*) const
1406 value = _pnode->getValue<T>();
1409 SGPropertyNode_ptr _pnode;
1412 class EffectPropertyListener : public SGPropertyChangeListener
1415 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1417 void valueChanged(SGPropertyNode* node)
1420 _tniq->refreshValidity();
1423 osg::observer_ptr<Technique> _tniq;
1426 template<typename T>
1427 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1428 expression::Parser* parser)
1430 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1432 PropertyExpression<T>* pexp = new PropertyExpression<T>(pnode);
1433 TechniquePredParser* predParser
1434 = dynamic_cast<TechniquePredParser*>(parser);
1436 pnode->addChangeListener(new EffectPropertyListener(predParser
1441 expression::ExpParserRegistrar propertyRegistrar("property",
1442 propertyExpressionParser<bool>);
1444 expression::ExpParserRegistrar propvalueRegistrar("float-property",
1445 propertyExpressionParser<float>);