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"
35 #include <boost/tr1/unordered_map.hpp>
37 #include <boost/bind.hpp>
38 #include <boost/foreach.hpp>
39 #include <boost/functional/hash.hpp>
40 #include <boost/tuple/tuple.hpp>
41 #include <boost/tuple/tuple_comparison.hpp>
43 #include <osg/AlphaFunc>
44 #include <osg/BlendFunc>
45 #include <osg/CullFace>
47 #include <osg/Drawable>
48 #include <osg/Material>
50 #include <osg/PolygonMode>
51 #include <osg/PolygonOffset>
53 #include <osg/Program>
54 #include <osg/Referenced>
55 #include <osg/RenderInfo>
56 #include <osg/ShadeModel>
57 #include <osg/StateSet>
58 #include <osg/Stencil>
60 #include <osg/Texture1D>
61 #include <osg/Texture2D>
62 #include <osg/Texture3D>
63 #include <osg/TextureRectangle>
64 #include <osg/Uniform>
66 #include <osgUtil/CullVisitor>
67 #include <osgDB/FileUtils>
68 #include <osgDB/Input>
69 #include <osgDB/ParameterOutput>
70 #include <osgDB/ReadFile>
71 #include <osgDB/Registry>
73 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
74 #include <simgear/scene/tgdb/userdata.hxx>
75 #include <simgear/scene/util/OsgMath.hxx>
76 #include <simgear/scene/util/SGSceneFeatures.hxx>
77 #include <simgear/scene/util/StateAttributeFactory.hxx>
78 #include <simgear/structure/OSGUtils.hxx>
79 #include <simgear/structure/SGExpression.hxx>
80 #include <simgear/props/vectorPropTemplates.hxx>
81 #include <simgear/threads/SGThread.hxx>
82 #include <simgear/threads/SGGuard.hxx>
88 using namespace osgUtil;
90 using namespace effect;
92 class UniformFactoryImpl {
94 ref_ptr<Uniform> getUniform( Effect * effect,
96 Uniform::Type uniformType,
97 SGConstPropertyNode_ptr valProp,
98 const SGReaderWriterOptions* options );
99 void updateListeners( SGPropertyNode* propRoot );
100 void addListener(DeferredPropertyListener* listener);
102 // Default names for vector property components
103 static const char* vec3Names[];
104 static const char* vec4Names[];
108 typedef boost::tuple<std::string, Uniform::Type, std::string, std::string> UniformCacheKey;
109 typedef boost::tuple<ref_ptr<Uniform>, SGPropertyChangeListener*> UniformCacheValue;
110 std::map<UniformCacheKey,ref_ptr<Uniform> > uniformCache;
112 typedef std::queue<DeferredPropertyListener*> DeferredListenerList;
113 DeferredListenerList deferredListenerList;
116 const char* UniformFactoryImpl::vec3Names[] = {"x", "y", "z"};
117 const char* UniformFactoryImpl::vec4Names[] = {"x", "y", "z", "w"};
119 ref_ptr<Uniform> UniformFactoryImpl::getUniform( Effect * effect,
121 Uniform::Type uniformType,
122 SGConstPropertyNode_ptr valProp,
123 const SGReaderWriterOptions* options )
125 SGGuard<SGMutex> scopeLock(_mutex);
126 std::string val = "0";
128 if (valProp->nChildren() == 0) {
129 // Completely static value
130 val = valProp->getStringValue();
132 // Value references <parameters> section of Effect
133 const SGPropertyNode* prop = getEffectPropertyNode(effect, valProp);
136 if (prop->nChildren() == 0) {
137 // Static value in parameters section
138 val = prop->getStringValue();
140 // Dynamic property value in parameters section
141 val = getGlobalProperty(prop, options);
144 SG_LOG(SG_GL,SG_DEBUG,"Invalid parameter " << valProp->getName() << " for uniform " << name << " in Effect ");
148 UniformCacheKey key = boost::make_tuple(name, uniformType, val, effect->getName());
149 ref_ptr<Uniform> uniform = uniformCache[key];
151 if (uniform.valid()) {
152 // We've got a hit to cache - simply return it
156 SG_LOG(SG_GL,SG_DEBUG,"new uniform " << name << " value " << uniformCache.size());
157 uniformCache[key] = uniform = new Uniform;
159 uniform->setName(name);
160 uniform->setType(uniformType);
161 switch (uniformType) {
163 initFromParameters(effect, valProp, uniform.get(),
164 static_cast<bool (Uniform::*)(bool)>(&Uniform::set),
168 initFromParameters(effect, valProp, uniform.get(),
169 static_cast<bool (Uniform::*)(float)>(&Uniform::set),
172 case Uniform::FLOAT_VEC3:
173 initFromParameters(effect, valProp, uniform.get(),
174 static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
177 case Uniform::FLOAT_VEC4:
178 initFromParameters(effect, valProp, uniform.get(),
179 static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
183 case Uniform::SAMPLER_1D:
184 case Uniform::SAMPLER_2D:
185 case Uniform::SAMPLER_3D:
186 case Uniform::SAMPLER_1D_SHADOW:
187 case Uniform::SAMPLER_2D_SHADOW:
188 case Uniform::SAMPLER_CUBE:
189 initFromParameters(effect, valProp, uniform.get(),
190 static_cast<bool (Uniform::*)(int)>(&Uniform::set),
193 default: // avoid compiler warning
194 SG_LOG(SG_ALL,SG_ALERT,"UNKNOWN Uniform type '" << uniformType << "'");
201 void UniformFactoryImpl::addListener(DeferredPropertyListener* listener)
204 // Uniform requires a property listener. Add it to the list to be
205 // created when the main thread gets to it.
206 deferredListenerList.push(listener);
210 void UniformFactoryImpl::updateListeners( SGPropertyNode* propRoot )
212 SGGuard<SGMutex> scopeLock(_mutex);
214 if (deferredListenerList.empty()) return;
216 SG_LOG(SG_GL,SG_DEBUG,"Adding " << deferredListenerList.size() << " listeners for effects.");
218 // Instantiate all queued listeners
219 while (! deferredListenerList.empty()) {
220 DeferredPropertyListener* listener = deferredListenerList.front();
221 listener->activate(propRoot);
222 deferredListenerList.pop();
226 typedef Singleton<UniformFactoryImpl> UniformFactory;
230 : _cache(0), _isRealized(false)
234 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
235 : osg::Object(rhs,copyop), root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
236 _isRealized(rhs._isRealized)
238 typedef vector<ref_ptr<Technique> > TechniqueList;
239 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
240 end = rhs.techniques.end();
243 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
245 generator = rhs.generator;
250 // Assume that the last technique is always valid.
251 StateSet* Effect::getDefaultStateSet()
253 Technique* tniq = techniques.back().get();
256 Pass* pass = tniq->passes.front().get();
260 int Effect::getGenerator(Effect::Generator what) const
262 std::map<Generator,int>::const_iterator it = generator.find(what);
263 if(it == generator.end()) return -1;
264 else return it->second;
267 // There should always be a valid technique in an effect.
269 Technique* Effect::chooseTechnique(RenderInfo* info)
271 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
273 if (technique->valid(info) == Technique::VALID)
274 return technique.get();
279 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
281 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
283 technique->resizeGLObjectBuffers(maxSize);
287 void Effect::releaseGLObjects(osg::State* state) const
289 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
291 technique->releaseGLObjects(state);
300 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
301 const SGReaderWriterOptions* options)
303 Pass* pass = new Pass;
304 tniq->passes.push_back(pass);
305 for (int i = 0; i < prop->nChildren(); ++i) {
306 const SGPropertyNode* attrProp = prop->getChild(i);
307 PassAttributeBuilder* builder
308 = PassAttributeBuilder::find(attrProp->getNameString());
310 builder->buildAttribute(effect, pass, attrProp, options);
312 SG_LOG(SG_INPUT, SG_ALERT,
313 "skipping unknown pass attribute " << attrProp->getName());
317 osg::Vec4f getColor(const SGPropertyNode* prop)
319 if (prop->nChildren() == 0) {
320 if (prop->getType() == props::VEC4D) {
321 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
322 } else if (prop->getType() == props::VEC3D) {
323 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
325 SG_LOG(SG_INPUT, SG_ALERT,
326 "invalid color property " << prop->getName() << " "
327 << prop->getStringValue());
328 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
332 static const char* colors[] = {"r", "g", "b"};
333 for (int i = 0; i < 3; ++i) {
334 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
335 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
337 const SGPropertyNode* alphaProp = prop->getChild("a");
338 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
343 struct LightingBuilder : public PassAttributeBuilder
345 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
346 const SGReaderWriterOptions* options);
349 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
350 const SGPropertyNode* prop,
351 const SGReaderWriterOptions* options)
353 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
356 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
357 : StateAttribute::OFF));
360 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
362 struct ShadeModelBuilder : public PassAttributeBuilder
364 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
365 const SGReaderWriterOptions* options)
367 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
370 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
371 string propVal = realProp->getStringValue();
372 if (propVal == "flat")
373 pass->setAttribute(attrFact->getFlatShadeModel());
374 else if (propVal == "smooth")
375 pass->setAttribute(attrFact->getSmoothShadeModel());
377 SG_LOG(SG_INPUT, SG_ALERT,
378 "invalid shade model property " << propVal);
382 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
384 struct CullFaceBuilder : PassAttributeBuilder
386 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
387 const SGReaderWriterOptions* options)
389 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
391 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
394 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
395 string propVal = realProp->getStringValue();
396 if (propVal == "front")
397 pass->setAttributeAndModes(attrFact->getCullFaceFront());
398 else if (propVal == "back")
399 pass->setAttributeAndModes(attrFact->getCullFaceBack());
400 else if (propVal == "front-back")
401 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
402 else if (propVal == "off")
403 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
405 SG_LOG(SG_INPUT, SG_ALERT,
406 "invalid cull face property " << propVal);
410 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
412 struct ColorMaskBuilder : PassAttributeBuilder
414 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
415 const SGReaderWriterOptions* options)
417 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
421 ColorMask *mask = new ColorMask;
422 Vec4 m = getColor(realProp);
423 mask->setMask(m.r() > 0.0, m.g() > 0.0, m.b() > 0.0, m.a() > 0.0);
424 pass->setAttributeAndModes(mask);
428 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
430 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
432 { "default", StateSet::DEFAULT_BIN },
433 { "opaque", StateSet::OPAQUE_BIN },
434 { "transparent", StateSet::TRANSPARENT_BIN }
437 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
439 struct HintBuilder : public PassAttributeBuilder
441 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
442 const SGReaderWriterOptions* options)
444 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
447 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
448 findAttr(renderingHints, realProp, renderingHint);
449 pass->setRenderingHint(renderingHint);
453 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
455 struct RenderBinBuilder : public PassAttributeBuilder
457 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
458 const SGReaderWriterOptions* options)
460 if (!isAttributeActive(effect, prop))
462 const SGPropertyNode* binProp = prop->getChild("bin-number");
463 binProp = getEffectPropertyNode(effect, binProp);
464 const SGPropertyNode* nameProp = prop->getChild("bin-name");
465 nameProp = getEffectPropertyNode(effect, nameProp);
466 if (binProp && nameProp) {
467 pass->setRenderBinDetails(binProp->getIntValue(),
468 nameProp->getStringValue());
471 SG_LOG(SG_INPUT, SG_ALERT,
472 "No render bin number specified in render bin section");
474 SG_LOG(SG_INPUT, SG_ALERT,
475 "No render bin name specified in render bin section");
480 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
482 struct MaterialBuilder : public PassAttributeBuilder
484 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
485 const SGReaderWriterOptions* options);
488 EffectNameValue<Material::ColorMode> colorModeInit[] =
490 { "ambient", Material::AMBIENT },
491 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
492 { "diffuse", Material::DIFFUSE },
493 { "emissive", Material::EMISSION },
494 { "specular", Material::SPECULAR },
495 { "off", Material::OFF }
497 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
499 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
500 const SGPropertyNode* prop,
501 const SGReaderWriterOptions* options)
503 if (!isAttributeActive(effect, prop))
505 Material* mat = new Material;
506 const SGPropertyNode* color = 0;
507 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
508 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
509 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
510 mat->setAmbient(Material::FRONT, getColor(color));
511 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
512 mat->setAmbient(Material::BACK, getColor(color));
513 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
514 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
515 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
516 mat->setDiffuse(Material::FRONT, getColor(color));
517 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
518 mat->setDiffuse(Material::BACK, getColor(color));
519 if ((color = getEffectPropertyChild(effect, prop, "specular")))
520 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
521 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
522 mat->setSpecular(Material::FRONT, getColor(color));
523 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
524 mat->setSpecular(Material::BACK, getColor(color));
525 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
526 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
527 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
528 mat->setEmission(Material::FRONT, getColor(color));
529 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
530 mat->setEmission(Material::BACK, getColor(color));
531 const SGPropertyNode* shininess = 0;
532 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
533 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
534 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
535 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
536 mat->setShininess(Material::FRONT, shininess->getFloatValue());
537 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
538 mat->setShininess(Material::BACK, shininess->getFloatValue());
539 Material::ColorMode colorMode = Material::OFF;
540 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
542 mat->setColorMode(colorMode);
543 pass->setAttribute(mat);
546 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
548 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
550 {"dst-alpha", BlendFunc::DST_ALPHA},
551 {"dst-color", BlendFunc::DST_COLOR},
552 {"one", BlendFunc::ONE},
553 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
554 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
555 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
556 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
557 {"src-alpha", BlendFunc::SRC_ALPHA},
558 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
559 {"src-color", BlendFunc::SRC_COLOR},
560 {"constant-color", BlendFunc::CONSTANT_COLOR},
561 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
562 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
563 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
564 {"zero", BlendFunc::ZERO}
566 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
568 struct BlendBuilder : public PassAttributeBuilder
570 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
571 const SGReaderWriterOptions* options)
573 if (!isAttributeActive(effect, prop))
575 // XXX Compatibility with early <blend> syntax; should go away
577 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
580 if (realProp->nChildren() == 0) {
581 pass->setMode(GL_BLEND, (realProp->getBoolValue()
583 : StateAttribute::OFF));
587 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
589 // XXX When dynamic parameters are supported, this code should
590 // create the blend function even if the mode is off.
591 if (pmode && !pmode->getValue<bool>()) {
592 pass->setMode(GL_BLEND, StateAttribute::OFF);
598 getEffectPropertyChild(effect, prop, "source"),
599 getEffectPropertyChild(effect, prop, "destination"),
600 getEffectPropertyChild(effect, prop, "source-rgb"),
601 getEffectPropertyChild(effect, prop, "destination-rgb"),
602 getEffectPropertyChild(effect, prop, "source-alpha"),
603 getEffectPropertyChild(effect, prop, "destination-alpha")
608 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
611 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
613 {"never", Stencil::NEVER },
614 {"less", Stencil::LESS},
615 {"equal", Stencil::EQUAL},
616 {"less-or-equal", Stencil::LEQUAL},
617 {"greater", Stencil::GREATER},
618 {"not-equal", Stencil::NOTEQUAL},
619 {"greater-or-equal", Stencil::GEQUAL},
620 {"always", Stencil::ALWAYS}
623 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
625 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
627 {"keep", Stencil::KEEP},
628 {"zero", Stencil::ZERO},
629 {"replace", Stencil::REPLACE},
630 {"increase", Stencil::INCR},
631 {"decrease", Stencil::DECR},
632 {"invert", Stencil::INVERT},
633 {"increase-wrap", Stencil::INCR_WRAP},
634 {"decrease-wrap", Stencil::DECR_WRAP}
637 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
639 struct StencilBuilder : public PassAttributeBuilder
641 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
642 const SGReaderWriterOptions* options)
644 if (!isAttributeActive(effect, prop))
647 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
649 if (pmode && !pmode->getValue<bool>()) {
650 pass->setMode(GL_STENCIL, StateAttribute::OFF);
653 const SGPropertyNode* pfunction
654 = getEffectPropertyChild(effect, prop, "function");
655 const SGPropertyNode* pvalue
656 = getEffectPropertyChild(effect, prop, "value");
657 const SGPropertyNode* pmask
658 = getEffectPropertyChild(effect, prop, "mask");
659 const SGPropertyNode* psfail
660 = getEffectPropertyChild(effect, prop, "stencil-fail");
661 const SGPropertyNode* pzfail
662 = getEffectPropertyChild(effect, prop, "z-fail");
663 const SGPropertyNode* ppass
664 = getEffectPropertyChild(effect, prop, "pass");
666 Stencil::Function func = Stencil::ALWAYS; // Always pass
668 unsigned int mask = ~0u; // All bits on
669 Stencil::Operation sfailop = Stencil::KEEP; // Keep the old values as default
670 Stencil::Operation zfailop = Stencil::KEEP;
671 Stencil::Operation passop = Stencil::KEEP;
673 ref_ptr<Stencil> stencilFunc = new Stencil;
676 findAttr(stencilFunction, pfunction, func);
678 ref = pvalue->getIntValue();
680 mask = pmask->getIntValue();
683 findAttr(stencilOperation, psfail, sfailop);
685 findAttr(stencilOperation, pzfail, zfailop);
687 findAttr(stencilOperation, ppass, passop);
689 // Set the stencil operation
690 stencilFunc->setFunction(func, ref, mask);
692 // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
693 stencilFunc->setOperation(sfailop, zfailop, passop);
695 // Add the operation to pass
696 pass->setAttributeAndModes(stencilFunc.get());
700 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
702 struct AlphaToCoverageBuilder : public PassAttributeBuilder
704 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
705 const SGReaderWriterOptions* options);
708 #ifndef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
709 #define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
712 void AlphaToCoverageBuilder::buildAttribute(Effect* effect, Pass* pass,
713 const SGPropertyNode* prop,
714 const SGReaderWriterOptions* options)
716 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
719 pass->setMode(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB, (realProp->getValue<bool>() ?
720 StateAttribute::ON : StateAttribute::OFF));
723 InstallAttributeBuilder<AlphaToCoverageBuilder> installAlphaToCoverage("alpha-to-coverage");
725 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
727 {"never", AlphaFunc::NEVER},
728 {"less", AlphaFunc::LESS},
729 {"equal", AlphaFunc::EQUAL},
730 {"lequal", AlphaFunc::LEQUAL},
731 {"greater", AlphaFunc::GREATER},
732 {"notequal", AlphaFunc::NOTEQUAL},
733 {"gequal", AlphaFunc::GEQUAL},
734 {"always", AlphaFunc::ALWAYS}
736 EffectPropertyMap<AlphaFunc::ComparisonFunction>
737 alphaComparison(alphaComparisonInit);
739 struct AlphaTestBuilder : public PassAttributeBuilder
741 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
742 const SGReaderWriterOptions* options)
744 if (!isAttributeActive(effect, prop))
746 // XXX Compatibility with early <alpha-test> syntax; should go away
748 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
751 if (realProp->nChildren() == 0) {
752 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
754 : StateAttribute::OFF));
758 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
760 // XXX When dynamic parameters are supported, this code should
761 // create the blend function even if the mode is off.
762 if (pmode && !pmode->getValue<bool>()) {
763 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
766 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
768 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
771 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
772 float refValue = 1.0f;
774 findAttr(alphaComparison, pComp, func);
776 refValue = pRef->getValue<float>();
777 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
778 pass->setAttributeAndModes(StateAttributeFactory::instance()
779 ->getStandardAlphaFunc());
781 AlphaFunc* alphaFunc = new AlphaFunc;
782 alphaFunc->setFunction(func);
783 alphaFunc->setReferenceValue(refValue);
784 pass->setAttributeAndModes(alphaFunc);
789 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
791 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
793 // Shader key, used both for shaders with relative and absolute names
794 typedef pair<string, int> ShaderKey;
796 inline ShaderKey makeShaderKey(SGPropertyNode_ptr& ptr, int shaderType)
798 return ShaderKey(ptr->getStringValue(), shaderType);
803 typedef pair<string, int> AttribKey;
804 osgDB::FilePathList paths;
805 vector<ShaderKey> shaders;
806 vector<AttribKey> attributes;
809 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
811 return (lhs.paths.size() == rhs.paths.size()
812 && equal(lhs.paths.begin(), lhs.paths.end(),
814 && lhs.shaders.size() == rhs.shaders.size()
815 && equal (lhs.shaders.begin(), lhs.shaders.end(),
817 && lhs.attributes.size() == rhs.attributes.size()
818 && equal(lhs.attributes.begin(), lhs.attributes.end(),
819 rhs.attributes.begin()));
824 size_t hash_value(const ProgramKey& key)
827 boost::hash_range(seed, key.paths.begin(), key.paths.end());
828 boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
829 boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
833 // XXX Should these be protected by a mutex? Probably
835 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
836 boost::hash<ProgramKey>, ProgramKey::EqualTo>
838 ProgramMap programMap;
839 ProgramMap resolvedProgramMap; // map with resolved shader file names
841 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
845 void reload_shaders()
847 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
849 Shader *shader = sitr->second.get();
850 string fileName = SGModelLib::findDataFile(sitr->first.first);
851 if (!fileName.empty()) {
852 shader->loadShaderSourceFromFile(fileName);
857 struct ShaderProgramBuilder : PassAttributeBuilder
859 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
860 const SGReaderWriterOptions* options);
864 EffectNameValue<GLint> geometryInputTypeInit[] =
866 {"points", GL_POINTS},
868 {"lines-adjacency", GL_LINES_ADJACENCY_EXT},
869 {"triangles", GL_TRIANGLES},
870 {"triangles-adjacency", GL_TRIANGLES_ADJACENCY_EXT},
872 EffectPropertyMap<GLint>
873 geometryInputType(geometryInputTypeInit);
876 EffectNameValue<GLint> geometryOutputTypeInit[] =
878 {"points", GL_POINTS},
879 {"line-strip", GL_LINE_STRIP},
880 {"triangle-strip", GL_TRIANGLE_STRIP}
882 EffectPropertyMap<GLint>
883 geometryOutputType(geometryOutputTypeInit);
885 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
886 const SGPropertyNode* prop,
887 const SGReaderWriterOptions*
890 using namespace boost;
891 if (!isAttributeActive(effect, prop))
893 PropertyList pVertShaders = prop->getChildren("vertex-shader");
894 PropertyList pGeomShaders = prop->getChildren("geometry-shader");
895 PropertyList pFragShaders = prop->getChildren("fragment-shader");
896 PropertyList pAttributes = prop->getChildren("attribute");
898 std::back_insert_iterator<vector<ShaderKey> > inserter(prgKey.shaders);
899 transform(pVertShaders.begin(), pVertShaders.end(), inserter,
900 boost::bind(makeShaderKey, _1, Shader::VERTEX));
901 transform(pGeomShaders.begin(), pGeomShaders.end(), inserter,
902 boost::bind(makeShaderKey, _1, Shader::GEOMETRY));
903 transform(pFragShaders.begin(), pFragShaders.end(), inserter,
904 boost::bind(makeShaderKey, _1, Shader::FRAGMENT));
905 for (PropertyList::iterator itr = pAttributes.begin(),
906 e = pAttributes.end();
909 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
911 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
913 if (!pName || ! pIndex)
914 throw BuilderException("malformed attribute property");
916 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
917 pIndex->getValue<int>()));
920 prgKey.paths = options->getDatabasePathList();
921 Program* program = 0;
922 ProgramMap::iterator pitr = programMap.find(prgKey);
923 if (pitr != programMap.end()) {
924 program = pitr->second.get();
925 pass->setAttributeAndModes(program);
928 // The program wasn't in the map using the load path passed in with
929 // the options, but it might have already been loaded using a
930 // different load path i.e., its shaders were found in the fg data
931 // directory. So, resolve the shaders' file names and look in the
932 // resolvedProgramMap for a program using those shaders.
933 ProgramKey resolvedKey;
934 resolvedKey.attributes = prgKey.attributes;
935 BOOST_FOREACH(const ShaderKey& shaderKey, prgKey.shaders)
937 const string& shaderName = shaderKey.first;
938 Shader::Type stype = (Shader::Type)shaderKey.second;
939 string fileName = SGModelLib::findDataFile(shaderName, options);
940 if (fileName.empty())
941 throw BuilderException(string("couldn't find shader ") +
943 resolvedKey.shaders.push_back(ShaderKey(fileName, stype));
945 ProgramMap::iterator resitr = resolvedProgramMap.find(resolvedKey);
946 if (resitr != resolvedProgramMap.end()) {
947 program = resitr->second.get();
948 programMap.insert(ProgramMap::value_type(prgKey, program));
949 pass->setAttributeAndModes(program);
952 program = new Program;
953 BOOST_FOREACH(const ShaderKey& skey, resolvedKey.shaders)
955 const string& fileName = skey.first;
956 Shader::Type stype = (Shader::Type)skey.second;
957 ShaderMap::iterator sitr = shaderMap.find(skey);
958 if (sitr != shaderMap.end()) {
959 program->addShader(sitr->second.get());
961 ref_ptr<Shader> shader = new Shader(stype);
962 shader->setName(fileName);
963 if (shader->loadShaderSourceFromFile(fileName)) {
964 program->addShader(shader.get());
965 shaderMap.insert(ShaderMap::value_type(skey, shader));
969 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
970 program->addBindAttribLocation(key.first, key.second);
972 const SGPropertyNode* pGeometryVerticesOut
973 = getEffectPropertyChild(effect, prop, "geometry-vertices-out");
974 if (pGeometryVerticesOut)
975 program->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT,
976 pGeometryVerticesOut->getIntValue());
977 const SGPropertyNode* pGeometryInputType
978 = getEffectPropertyChild(effect, prop, "geometry-input-type");
979 if (pGeometryInputType) {
981 findAttr(geometryInputType, pGeometryInputType->getStringValue(), type);
982 program->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT, type);
984 const SGPropertyNode* pGeometryOutputType
985 = getEffectPropertyChild(effect, prop, "geometry-output-type");
986 if (pGeometryOutputType) {
988 findAttr(geometryOutputType, pGeometryOutputType->getStringValue(),
990 program->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, type);
992 programMap.insert(ProgramMap::value_type(prgKey, program));
993 resolvedProgramMap.insert(ProgramMap::value_type(resolvedKey, program));
994 pass->setAttributeAndModes(program);
997 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
999 EffectNameValue<Uniform::Type> uniformTypesInit[] =
1001 {"bool", Uniform::BOOL},
1002 {"int", Uniform::INT},
1003 {"float", Uniform::FLOAT},
1004 {"float-vec3", Uniform::FLOAT_VEC3},
1005 {"float-vec4", Uniform::FLOAT_VEC4},
1006 {"sampler-1d", Uniform::SAMPLER_1D},
1007 {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
1008 {"sampler-2d", Uniform::SAMPLER_2D},
1009 {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
1010 {"sampler-3d", Uniform::SAMPLER_3D},
1011 {"sampler-cube", Uniform::SAMPLER_CUBE}
1013 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
1015 // Optimization hack for common uniforms.
1016 // XXX protect these with a mutex?
1018 ref_ptr<Uniform> texture0;
1019 ref_ptr<Uniform> colorMode[3];
1021 struct UniformBuilder :public PassAttributeBuilder
1023 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1024 const SGReaderWriterOptions* options)
1026 if (!texture0.valid()) {
1027 texture0 = new Uniform(Uniform::SAMPLER_2D, "texture");
1029 texture0->setDataVariance(Object::STATIC);
1030 for (int i = 0; i < 3; ++i) {
1031 colorMode[i] = new Uniform(Uniform::INT, "colorMode");
1032 colorMode[i]->set(i);
1033 colorMode[i]->setDataVariance(Object::STATIC);
1036 if (!isAttributeActive(effect, prop))
1038 SGConstPropertyNode_ptr nameProp = prop->getChild("name");
1039 SGConstPropertyNode_ptr typeProp = prop->getChild("type");
1040 SGConstPropertyNode_ptr positionedProp = prop->getChild("positioned");
1041 SGConstPropertyNode_ptr valProp = prop->getChild("value");
1043 Uniform::Type uniformType = Uniform::FLOAT;
1045 name = nameProp->getStringValue();
1047 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
1051 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
1056 props::Type propType = valProp->getType();
1059 uniformType = Uniform::BOOL;
1062 uniformType = Uniform::INT;
1066 break; // default float type;
1068 uniformType = Uniform::FLOAT_VEC3;
1071 uniformType = Uniform::FLOAT_VEC4;
1074 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
1079 findAttr(uniformTypes, typeProp, uniformType);
1081 ref_ptr<Uniform> uniform = UniformFactory::instance()->
1082 getUniform( effect, name, uniformType, valProp, options );
1084 // optimize common uniforms
1085 if (uniformType == Uniform::SAMPLER_2D || uniformType == Uniform::INT)
1088 uniform->get(val); // 'val' remains unchanged in case of error (Uniform is a non-scalar)
1089 if (uniformType == Uniform::SAMPLER_2D && val == 0
1090 && name == "texture") {
1092 } else if (uniformType == Uniform::INT && val >= 0 && val < 3
1093 && name == "colorMode") {
1094 uniform = colorMode[val];
1097 pass->addUniform(uniform.get());
1098 if (positionedProp && positionedProp->getBoolValue() && uniformType == Uniform::FLOAT_VEC4) {
1100 uniform->get(offset);
1101 pass->addPositionedUniform( name, offset );
1106 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
1108 // Not sure what to do with "name". At one point I wanted to use it to
1109 // order the passes, but I do support render bin and stuff too...
1110 // Clément de l'Hamaide 10/2014: "name" is now used in the UniformCacheKey
1112 struct NameBuilder : public PassAttributeBuilder
1114 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1115 const SGReaderWriterOptions* options)
1117 // name can't use <use>
1118 string name = prop->getStringValue();
1120 pass->setName(name);
1124 InstallAttributeBuilder<NameBuilder> installName("name");
1126 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
1128 {"fill", PolygonMode::FILL},
1129 {"line", PolygonMode::LINE},
1130 {"point", PolygonMode::POINT}
1132 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
1134 struct PolygonModeBuilder : public PassAttributeBuilder
1136 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1137 const SGReaderWriterOptions* options)
1139 if (!isAttributeActive(effect, prop))
1141 const SGPropertyNode* frontProp
1142 = getEffectPropertyChild(effect, prop, "front");
1143 const SGPropertyNode* backProp
1144 = getEffectPropertyChild(effect, prop, "back");
1145 ref_ptr<PolygonMode> pmode = new PolygonMode;
1146 PolygonMode::Mode frontMode = PolygonMode::FILL;
1147 PolygonMode::Mode backMode = PolygonMode::FILL;
1149 findAttr(polygonModeModes, frontProp, frontMode);
1150 pmode->setMode(PolygonMode::FRONT, frontMode);
1153 findAttr(polygonModeModes, backProp, backMode);
1154 pmode->setMode(PolygonMode::BACK, backMode);
1156 pass->setAttribute(pmode.get());
1160 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1162 struct PolygonOffsetBuilder : public PassAttributeBuilder
1164 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1165 const SGReaderWriterOptions* options)
1167 if (!isAttributeActive(effect, prop))
1170 const SGPropertyNode* factor
1171 = getEffectPropertyChild(effect, prop, "factor");
1172 const SGPropertyNode* units
1173 = getEffectPropertyChild(effect, prop, "units");
1175 ref_ptr<PolygonOffset> polyoffset = new PolygonOffset;
1177 polyoffset->setFactor(factor->getFloatValue());
1178 polyoffset->setUnits(units->getFloatValue());
1180 SG_LOG(SG_INPUT, SG_BULK,
1181 "Set PolygonOffset to " << polyoffset->getFactor() << polyoffset->getUnits() );
1183 pass->setAttributeAndModes(polyoffset.get(),
1184 StateAttribute::OVERRIDE|StateAttribute::ON);
1188 InstallAttributeBuilder<PolygonOffsetBuilder> installPolygonOffset("polygon-offset");
1190 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1192 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1193 const SGReaderWriterOptions* options)
1195 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1198 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1199 (realProp->getValue<bool>()
1200 ? StateAttribute::ON : StateAttribute::OFF));
1204 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1205 installTwoSide("vertex-program-two-side");
1207 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1209 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1210 const SGReaderWriterOptions* options)
1212 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1215 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1216 (realProp->getValue<bool>()
1217 ? StateAttribute::ON : StateAttribute::OFF));
1221 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1222 installPointSize("vertex-program-point-size");
1224 struct PointBuilder : public PassAttributeBuilder
1226 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1227 const SGReaderWriterOptions* options)
1229 float minsize = 1.0;
1230 float maxsize = 1.0;
1232 osg::Vec3f attenuation = osg::Vec3f(1.0, 1.0, 1.0);
1234 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1238 const SGPropertyNode* pminsize
1239 = getEffectPropertyChild(effect, prop, "min-size");
1240 const SGPropertyNode* pmaxsize
1241 = getEffectPropertyChild(effect, prop, "max-size");
1242 const SGPropertyNode* psize
1243 = getEffectPropertyChild(effect, prop, "size");
1244 const SGPropertyNode* pattenuation
1245 = getEffectPropertyChild(effect, prop, "attenuation");
1248 minsize = pminsize->getFloatValue();
1250 maxsize = pmaxsize->getFloatValue();
1252 size = psize->getFloatValue();
1254 attenuation = osg::Vec3f(pattenuation->getChild("x")->getFloatValue(),
1255 pattenuation->getChild("y")->getFloatValue(),
1256 pattenuation->getChild("z")->getFloatValue());
1258 osg::Point* point = new osg::Point;
1259 point->setMinSize(minsize);
1260 point->setMaxSize(maxsize);
1261 point->setSize(size);
1262 point->setDistanceAttenuation(attenuation);
1263 pass->setAttributeAndModes(point);
1267 InstallAttributeBuilder<PointBuilder>
1268 installPoint("point");
1270 EffectNameValue<Depth::Function> depthFunctionInit[] =
1272 {"never", Depth::NEVER},
1273 {"less", Depth::LESS},
1274 {"equal", Depth::EQUAL},
1275 {"lequal", Depth::LEQUAL},
1276 {"greater", Depth::GREATER},
1277 {"notequal", Depth::NOTEQUAL},
1278 {"gequal", Depth::GEQUAL},
1279 {"always", Depth::ALWAYS}
1281 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1283 struct DepthBuilder : public PassAttributeBuilder
1285 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1286 const SGReaderWriterOptions* options)
1288 if (!isAttributeActive(effect, prop))
1290 ref_ptr<Depth> depth = new Depth;
1291 const SGPropertyNode* pfunc
1292 = getEffectPropertyChild(effect, prop, "function");
1294 Depth::Function func = Depth::LESS;
1295 findAttr(depthFunction, pfunc, func);
1296 depth->setFunction(func);
1298 const SGPropertyNode* pnear
1299 = getEffectPropertyChild(effect, prop, "near");
1301 depth->setZNear(pnear->getValue<double>());
1302 const SGPropertyNode* pfar
1303 = getEffectPropertyChild(effect, prop, "far");
1305 depth->setZFar(pfar->getValue<double>());
1306 const SGPropertyNode* pmask
1307 = getEffectPropertyChild(effect, prop, "write-mask");
1309 depth->setWriteMask(pmask->getValue<bool>());
1310 const SGPropertyNode* penabled
1311 = getEffectPropertyChild(effect, prop, "enabled");
1312 bool enabled = ( penabled == 0 || penabled->getBoolValue() );
1313 pass->setAttributeAndModes(depth.get(), enabled ? osg::StateAttribute::ON : osg::StateAttribute::OFF);
1317 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1319 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1320 const SGReaderWriterOptions* options)
1322 Technique* tniq = new Technique;
1323 effect->techniques.push_back(tniq);
1324 const SGPropertyNode* predProp = prop->getChild("predicate");
1326 tniq->setAlwaysValid(true);
1329 TechniquePredParser parser;
1330 parser.setTechnique(tniq);
1331 expression::BindingLayout& layout = parser.getBindingLayout();
1332 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1333 SGExpressionb* validExp
1334 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1337 tniq->setValidExpression(validExp, layout);
1339 throw expression::ParseError("technique predicate is not a boolean expression");
1341 catch (expression::ParseError& except)
1343 SG_LOG(SG_INPUT, SG_ALERT,
1344 "parsing technique predicate " << except.getMessage());
1345 tniq->setAlwaysValid(false);
1348 PropertyList passProps = prop->getChildren("pass");
1349 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1352 buildPass(effect, tniq, itr->ptr(), options);
1356 // Specifically for .ac files...
1357 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1359 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1360 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1361 Vec4f ambVal, difVal, specVal, emisVal;
1362 float shininess = 0.0f;
1363 const Material* mat = getStateAttribute<Material>(ss);
1365 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1366 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1367 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1368 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1369 shininess = mat->getShininess(Material::FRONT_AND_BACK);
1370 makeChild(matNode, "active")->setValue(true);
1371 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1372 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1373 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1374 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1375 makeChild(matNode, "shininess")->setValue(shininess);
1376 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1378 makeChild(matNode, "active")->setValue(false);
1380 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1381 string shadeModelString("smooth");
1383 ShadeModel::Mode smMode = sm->getMode();
1384 if (smMode == ShadeModel::FLAT)
1385 shadeModelString = "flat";
1387 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1388 string cullFaceString("off");
1389 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1391 switch (cullFace->getMode()) {
1392 case CullFace::FRONT:
1393 cullFaceString = "front";
1395 case CullFace::BACK:
1396 cullFaceString = "back";
1398 case CullFace::FRONT_AND_BACK:
1399 cullFaceString = "front-back";
1405 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1406 // Macintosh ATI workaround
1407 bool vertexTwoSide = cullFaceString == "off";
1408 makeChild(paramRoot, "vertex-program-two-side")->setValue(vertexTwoSide);
1409 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1410 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1412 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1413 string destMode = findName(blendFuncModes, blendFunc->getDestination());
1414 makeChild(blendNode, "active")->setValue(true);
1415 makeChild(blendNode, "source")->setStringValue(sourceMode);
1416 makeChild(blendNode, "destination")->setStringValue(destMode);
1417 makeChild(blendNode, "mode")->setValue(true);
1419 makeChild(blendNode, "active")->setValue(false);
1421 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1422 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1423 makeTextureParameters(paramRoot, ss);
1427 // Walk the techniques property tree, building techniques and
1429 bool Effect::realizeTechniques(const SGReaderWriterOptions* options)
1433 PropertyList tniqList = root->getChildren("technique");
1434 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1437 buildTechnique(this, *itr, options);
1442 void Effect::addDeferredPropertyListener(DeferredPropertyListener* listener)
1444 UniformFactory::instance()->addListener(listener);
1447 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1449 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1452 Effect* effect = eg->getEffect();
1455 SGPropertyNode* root = getPropertyRoot();
1457 // Initialize all queued listeners
1458 UniformFactory::instance()->updateListeners(root);
1461 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1462 const Effect::Key& rhs) const
1464 if (lhs.paths.size() != rhs.paths.size()
1465 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1467 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1468 return props::Compare()(lhs.unmerged, rhs.unmerged);
1470 return lhs.unmerged == rhs.unmerged;
1473 size_t hash_value(const Effect::Key& key)
1476 if (key.unmerged.valid())
1477 boost::hash_combine(seed, *key.unmerged);
1478 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1482 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1484 const Effect& effect = static_cast<const Effect&>(obj);
1486 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1487 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1488 fw.writeObject(*technique);
1495 osgDB::RegisterDotOsgWrapperProxy effectProxy
1499 "Object simgear::Effect",
1501 &Effect_writeLocalData
1505 // Property expressions for technique predicates
1506 template<typename T>
1507 class PropertyExpression : public SGExpression<T>
1510 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode), _listener(NULL) {}
1512 ~PropertyExpression()
1517 void eval(T& value, const expression::Binding*) const
1519 value = _pnode->getValue<T>();
1522 void setListener(SGPropertyChangeListener* l)
1527 SGPropertyNode_ptr _pnode;
1528 SGPropertyChangeListener* _listener;
1531 class EffectPropertyListener : public SGPropertyChangeListener
1534 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1536 void valueChanged(SGPropertyNode* node)
1539 _tniq->refreshValidity();
1542 virtual ~EffectPropertyListener() { }
1545 osg::observer_ptr<Technique> _tniq;
1548 template<typename T>
1549 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1550 expression::Parser* parser)
1552 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1554 PropertyExpression<T>* pexp = new PropertyExpression<T>(pnode);
1555 TechniquePredParser* predParser
1556 = dynamic_cast<TechniquePredParser*>(parser);
1558 EffectPropertyListener* l = new EffectPropertyListener(predParser
1560 pexp->setListener(l);
1561 pnode->addChangeListener(l);
1566 expression::ExpParserRegistrar propertyRegistrar("property",
1567 propertyExpressionParser<bool>);
1569 expression::ExpParserRegistrar propvalueRegistrar("float-property",
1570 propertyExpressionParser<float>);