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/model/SGReaderWriterXMLOptions.hxx>
71 #include <simgear/scene/tgdb/userdata.hxx>
72 #include <simgear/scene/util/SGSceneFeatures.hxx>
73 #include <simgear/scene/util/StateAttributeFactory.hxx>
74 #include <simgear/structure/OSGUtils.hxx>
75 #include <simgear/structure/SGExpression.hxx>
83 using namespace osgUtil;
85 using namespace effect;
88 : _cache(0), _isRealized(false)
92 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
93 : root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
94 _isRealized(rhs._isRealized)
96 typedef vector<ref_ptr<Technique> > TechniqueList;
97 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
98 end = rhs.techniques.end();
101 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
103 generator = rhs.generator;
106 // Assume that the last technique is always valid.
107 StateSet* Effect::getDefaultStateSet()
109 Technique* tniq = techniques.back().get();
112 Pass* pass = tniq->passes.front().get();
116 int Effect::getGenerator(Effect::Generator what) const
118 std::map<Generator,int>::const_iterator it = generator.find(what);
119 if(it == generator.end()) return -1;
120 else return it->second;
123 // There should always be a valid technique in an effect.
125 Technique* Effect::chooseTechnique(RenderInfo* info)
127 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
129 if (technique->valid(info) == Technique::VALID)
130 return technique.get();
135 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
137 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
139 technique->resizeGLObjectBuffers(maxSize);
143 void Effect::releaseGLObjects(osg::State* state) const
145 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
147 technique->releaseGLObjects(state);
156 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
157 const SGReaderWriterXMLOptions* options)
159 Pass* pass = new Pass;
160 tniq->passes.push_back(pass);
161 for (int i = 0; i < prop->nChildren(); ++i) {
162 const SGPropertyNode* attrProp = prop->getChild(i);
163 PassAttributeBuilder* builder
164 = PassAttributeBuilder::find(attrProp->getNameString());
166 builder->buildAttribute(effect, pass, attrProp, options);
168 SG_LOG(SG_INPUT, SG_ALERT,
169 "skipping unknown pass attribute " << attrProp->getName());
173 // Default names for vector property components
174 const char* vec3Names[] = {"x", "y", "z"};
175 const char* vec4Names[] = {"x", "y", "z", "w"};
177 osg::Vec4f getColor(const SGPropertyNode* prop)
179 if (prop->nChildren() == 0) {
180 if (prop->getType() == props::VEC4D) {
181 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
182 } else if (prop->getType() == props::VEC3D) {
183 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
185 SG_LOG(SG_INPUT, SG_ALERT,
186 "invalid color property " << prop->getName() << " "
187 << prop->getStringValue());
188 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
192 static const char* colors[] = {"r", "g", "b"};
193 for (int i = 0; i < 3; ++i) {
194 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
195 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
197 const SGPropertyNode* alphaProp = prop->getChild("a");
198 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
203 struct LightingBuilder : public PassAttributeBuilder
205 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
206 const SGReaderWriterXMLOptions* options);
209 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
210 const SGPropertyNode* prop,
211 const SGReaderWriterXMLOptions* options)
213 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
216 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
217 : StateAttribute::OFF));
220 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
222 struct ShadeModelBuilder : public PassAttributeBuilder
224 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
225 const SGReaderWriterXMLOptions* options)
227 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
230 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
231 string propVal = realProp->getStringValue();
232 if (propVal == "flat")
233 pass->setAttribute(attrFact->getFlatShadeModel());
234 else if (propVal == "smooth")
235 pass->setAttribute(attrFact->getSmoothShadeModel());
237 SG_LOG(SG_INPUT, SG_ALERT,
238 "invalid shade model property " << propVal);
242 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
244 struct CullFaceBuilder : PassAttributeBuilder
246 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
247 const SGReaderWriterXMLOptions* options)
249 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
251 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
254 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
255 string propVal = realProp->getStringValue();
256 if (propVal == "front")
257 pass->setAttributeAndModes(attrFact->getCullFaceFront());
258 else if (propVal == "back")
259 pass->setAttributeAndModes(attrFact->getCullFaceBack());
260 else if (propVal == "front-back")
261 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
262 else if (propVal == "off")
263 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
265 SG_LOG(SG_INPUT, SG_ALERT,
266 "invalid cull face property " << propVal);
270 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
272 struct ColorMaskBuilder : PassAttributeBuilder
274 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
275 const SGReaderWriterXMLOptions* options)
277 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
281 ColorMask *mask = new ColorMask;
282 Vec4 m = getColor(realProp);
283 mask->setMask(m.r() > 0.0, m.g() > 0.0, m.b() > 0.0, m.a() > 0.0);
284 pass->setAttributeAndModes(mask);
288 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
290 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
292 { "default", StateSet::DEFAULT_BIN },
293 { "opaque", StateSet::OPAQUE_BIN },
294 { "transparent", StateSet::TRANSPARENT_BIN }
297 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
299 struct HintBuilder : public PassAttributeBuilder
301 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
302 const SGReaderWriterXMLOptions* options)
304 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
307 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
308 findAttr(renderingHints, realProp, renderingHint);
309 pass->setRenderingHint(renderingHint);
313 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
315 struct RenderBinBuilder : public PassAttributeBuilder
317 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
318 const SGReaderWriterXMLOptions* options)
320 if (!isAttributeActive(effect, prop))
322 const SGPropertyNode* binProp = prop->getChild("bin-number");
323 binProp = getEffectPropertyNode(effect, binProp);
324 const SGPropertyNode* nameProp = prop->getChild("bin-name");
325 nameProp = getEffectPropertyNode(effect, nameProp);
326 if (binProp && nameProp) {
327 pass->setRenderBinDetails(binProp->getIntValue(),
328 nameProp->getStringValue());
331 SG_LOG(SG_INPUT, SG_ALERT,
332 "No render bin number specified in render bin section");
334 SG_LOG(SG_INPUT, SG_ALERT,
335 "No render bin name specified in render bin section");
340 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
342 struct MaterialBuilder : public PassAttributeBuilder
344 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
345 const SGReaderWriterXMLOptions* options);
348 EffectNameValue<Material::ColorMode> colorModeInit[] =
350 { "ambient", Material::AMBIENT },
351 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
352 { "diffuse", Material::DIFFUSE },
353 { "emissive", Material::EMISSION },
354 { "specular", Material::SPECULAR },
355 { "off", Material::OFF }
357 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
359 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
360 const SGPropertyNode* prop,
361 const SGReaderWriterXMLOptions* options)
363 if (!isAttributeActive(effect, prop))
365 Material* mat = new Material;
366 const SGPropertyNode* color = 0;
367 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
368 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
369 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
370 mat->setAmbient(Material::FRONT, getColor(color));
371 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
372 mat->setAmbient(Material::BACK, getColor(color));
373 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
374 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
375 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
376 mat->setDiffuse(Material::FRONT, getColor(color));
377 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
378 mat->setDiffuse(Material::BACK, getColor(color));
379 if ((color = getEffectPropertyChild(effect, prop, "specular")))
380 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
381 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
382 mat->setSpecular(Material::FRONT, getColor(color));
383 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
384 mat->setSpecular(Material::BACK, getColor(color));
385 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
386 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
387 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
388 mat->setEmission(Material::FRONT, getColor(color));
389 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
390 mat->setEmission(Material::BACK, getColor(color));
391 const SGPropertyNode* shininess = 0;
392 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
393 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
394 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
395 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
396 mat->setShininess(Material::FRONT, shininess->getFloatValue());
397 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
398 mat->setShininess(Material::BACK, shininess->getFloatValue());
399 Material::ColorMode colorMode = Material::OFF;
400 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
402 mat->setColorMode(colorMode);
403 pass->setAttribute(mat);
406 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
408 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
410 {"dst-alpha", BlendFunc::DST_ALPHA},
411 {"dst-color", BlendFunc::DST_COLOR},
412 {"one", BlendFunc::ONE},
413 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
414 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
415 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
416 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
417 {"src-alpha", BlendFunc::SRC_ALPHA},
418 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
419 {"src-color", BlendFunc::SRC_COLOR},
420 {"constant-color", BlendFunc::CONSTANT_COLOR},
421 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
422 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
423 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
424 {"zero", BlendFunc::ZERO}
426 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
428 struct BlendBuilder : public PassAttributeBuilder
430 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
431 const SGReaderWriterXMLOptions* options)
433 if (!isAttributeActive(effect, prop))
435 // XXX Compatibility with early <blend> syntax; should go away
437 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
440 if (realProp->nChildren() == 0) {
441 pass->setMode(GL_BLEND, (realProp->getBoolValue()
443 : StateAttribute::OFF));
447 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
449 // XXX When dynamic parameters are supported, this code should
450 // create the blend function even if the mode is off.
451 if (pmode && !pmode->getValue<bool>()) {
452 pass->setMode(GL_BLEND, StateAttribute::OFF);
455 const SGPropertyNode* psource
456 = getEffectPropertyChild(effect, prop, "source");
457 const SGPropertyNode* pdestination
458 = getEffectPropertyChild(effect, prop, "destination");
459 const SGPropertyNode* psourceRGB
460 = getEffectPropertyChild(effect, prop, "source-rgb");
461 const SGPropertyNode* psourceAlpha
462 = getEffectPropertyChild(effect, prop, "source-alpha");
463 const SGPropertyNode* pdestRGB
464 = getEffectPropertyChild(effect, prop, "destination-rgb");
465 const SGPropertyNode* pdestAlpha
466 = getEffectPropertyChild(effect, prop, "destination-alpha");
467 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
468 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
470 findAttr(blendFuncModes, psource, sourceMode);
472 findAttr(blendFuncModes, pdestination, destMode);
473 if (psource && pdestination
474 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
475 && sourceMode == BlendFunc::SRC_ALPHA
476 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
477 pass->setAttributeAndModes(StateAttributeFactory::instance()
478 ->getStandardBlendFunc());
481 BlendFunc* blendFunc = new BlendFunc;
483 blendFunc->setSource(sourceMode);
485 blendFunc->setDestination(destMode);
487 BlendFunc::BlendFuncMode sourceRGBMode;
488 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
489 blendFunc->setSourceRGB(sourceRGBMode);
492 BlendFunc::BlendFuncMode destRGBMode;
493 findAttr(blendFuncModes, pdestRGB, destRGBMode);
494 blendFunc->setDestinationRGB(destRGBMode);
497 BlendFunc::BlendFuncMode sourceAlphaMode;
498 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
499 blendFunc->setSourceAlpha(sourceAlphaMode);
502 BlendFunc::BlendFuncMode destAlphaMode;
503 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
504 blendFunc->setDestinationAlpha(destAlphaMode);
506 pass->setAttributeAndModes(blendFunc);
510 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
513 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
515 {"never", Stencil::NEVER },
516 {"less", Stencil::LESS},
517 {"equal", Stencil::EQUAL},
518 {"less-or-equal", Stencil::LEQUAL},
519 {"greater", Stencil::GREATER},
520 {"not-equal", Stencil::NOTEQUAL},
521 {"greater-or-equal", Stencil::GEQUAL},
522 {"always", Stencil::ALWAYS}
525 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
527 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
529 {"keep", Stencil::KEEP},
530 {"zero", Stencil::ZERO},
531 {"replace", Stencil::REPLACE},
532 {"increase", Stencil::INCR},
533 {"decrease", Stencil::DECR},
534 {"invert", Stencil::INVERT},
535 {"increase-wrap", Stencil::INCR_WRAP},
536 {"decrease-wrap", Stencil::DECR_WRAP}
539 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
541 struct StencilBuilder : public PassAttributeBuilder
543 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
544 const SGReaderWriterXMLOptions* options)
546 if (!isAttributeActive(effect, prop))
549 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
551 if (pmode && !pmode->getValue<bool>()) {
552 pass->setMode(GL_STENCIL, StateAttribute::OFF);
555 const SGPropertyNode* pfunction
556 = getEffectPropertyChild(effect, prop, "function");
557 const SGPropertyNode* pvalue
558 = getEffectPropertyChild(effect, prop, "value");
559 const SGPropertyNode* pmask
560 = getEffectPropertyChild(effect, prop, "mask");
561 const SGPropertyNode* psfail
562 = getEffectPropertyChild(effect, prop, "stencil-fail");
563 const SGPropertyNode* pzfail
564 = getEffectPropertyChild(effect, prop, "z-fail");
565 const SGPropertyNode* ppass
566 = getEffectPropertyChild(effect, prop, "pass");
568 Stencil::Function func = Stencil::ALWAYS; // Always pass
570 unsigned int mask = ~0u; // All bits on
571 Stencil::Operation sfailop = Stencil::KEEP; // Keep the old values as default
572 Stencil::Operation zfailop = Stencil::KEEP;
573 Stencil::Operation passop = Stencil::KEEP;
575 ref_ptr<Stencil> stencilFunc = new Stencil;
578 findAttr(stencilFunction, pfunction, func);
580 ref = pvalue->getIntValue();
582 mask = pmask->getIntValue();
585 findAttr(stencilOperation, psfail, sfailop);
587 findAttr(stencilOperation, pzfail, zfailop);
589 findAttr(stencilOperation, ppass, passop);
591 // Set the stencil operation
592 stencilFunc->setFunction(func, ref, mask);
594 // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
595 stencilFunc->setOperation(sfailop, zfailop, passop);
597 // Add the operation to pass
598 pass->setAttributeAndModes(stencilFunc.get());
602 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
605 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
607 {"never", AlphaFunc::NEVER},
608 {"less", AlphaFunc::LESS},
609 {"equal", AlphaFunc::EQUAL},
610 {"lequal", AlphaFunc::LEQUAL},
611 {"greater", AlphaFunc::GREATER},
612 {"notequal", AlphaFunc::NOTEQUAL},
613 {"gequal", AlphaFunc::GEQUAL},
614 {"always", AlphaFunc::ALWAYS}
616 EffectPropertyMap<AlphaFunc::ComparisonFunction>
617 alphaComparison(alphaComparisonInit);
619 struct AlphaTestBuilder : public PassAttributeBuilder
621 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
622 const SGReaderWriterXMLOptions* options)
624 if (!isAttributeActive(effect, prop))
626 // XXX Compatibility with early <alpha-test> syntax; should go away
628 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
631 if (realProp->nChildren() == 0) {
632 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
634 : StateAttribute::OFF));
638 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
640 // XXX When dynamic parameters are supported, this code should
641 // create the blend function even if the mode is off.
642 if (pmode && !pmode->getValue<bool>()) {
643 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
646 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
648 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
650 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
651 float refValue = 1.0f;
653 findAttr(alphaComparison, pComp, func);
655 refValue = pRef->getValue<float>();
656 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
657 pass->setAttributeAndModes(StateAttributeFactory::instance()
658 ->getStandardAlphaFunc());
660 AlphaFunc* alphaFunc = new AlphaFunc;
661 alphaFunc->setFunction(func);
662 alphaFunc->setReferenceValue(refValue);
663 pass->setAttributeAndModes(alphaFunc);
668 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
670 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
672 // Shader key, used both for shaders with relative and absolute names
673 typedef pair<string, Shader::Type> ShaderKey;
675 inline ShaderKey makeShaderKey(SGPropertyNode_ptr& ptr, Shader::Type shaderType)
677 return ShaderKey(ptr->getStringValue(), shaderType);
682 typedef pair<string, int> AttribKey;
683 osgDB::FilePathList paths;
684 vector<ShaderKey> shaders;
685 vector<AttribKey> attributes;
688 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
690 return (lhs.paths.size() == rhs.paths.size()
691 && equal(lhs.paths.begin(), lhs.paths.end(),
693 && lhs.shaders.size() == rhs.shaders.size()
694 && equal (lhs.shaders.begin(), lhs.shaders.end(),
696 && lhs.attributes.size() == rhs.attributes.size()
697 && equal(lhs.attributes.begin(), lhs.attributes.end(),
698 rhs.attributes.begin()));
703 size_t hash_value(const ProgramKey& key)
706 boost::hash_range(seed, key.paths.begin(), key.paths.end());
707 boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
708 boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
712 // XXX Should these be protected by a mutex? Probably
714 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
715 boost::hash<ProgramKey>, ProgramKey::EqualTo>
717 ProgramMap programMap;
718 ProgramMap resolvedProgramMap; // map with resolved shader file names
720 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
724 void reload_shaders()
726 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
728 Shader *shader = sitr->second.get();
729 string fileName = SGModelLib::findDataFile(sitr->first.first);
730 if (!fileName.empty()) {
731 shader->loadShaderSourceFromFile(fileName);
736 struct ShaderProgramBuilder : PassAttributeBuilder
738 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
739 const SGReaderWriterXMLOptions* options);
743 EffectNameValue<GLint> geometryInputTypeInit[] =
745 {"points", GL_POINTS},
747 {"lines-adjacency", GL_LINES_ADJACENCY_EXT},
748 {"triangles", GL_TRIANGLES},
749 {"triangles-adjacency", GL_TRIANGLES_ADJACENCY_EXT},
751 EffectPropertyMap<GLint>
752 geometryInputType(geometryInputTypeInit);
755 EffectNameValue<GLint> geometryOutputTypeInit[] =
757 {"points", GL_POINTS},
758 {"line-strip", GL_LINE_STRIP},
759 {"triangle-strip", GL_TRIANGLE_STRIP}
761 EffectPropertyMap<GLint>
762 geometryOutputType(geometryOutputTypeInit);
764 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
765 const SGPropertyNode* prop,
766 const SGReaderWriterXMLOptions*
769 using namespace boost;
770 if (!isAttributeActive(effect, prop))
772 PropertyList pVertShaders = prop->getChildren("vertex-shader");
773 PropertyList pGeomShaders = prop->getChildren("geometry-shader");
774 PropertyList pFragShaders = prop->getChildren("fragment-shader");
775 PropertyList pAttributes = prop->getChildren("attribute");
777 std::back_insert_iterator<vector<ShaderKey> > inserter(prgKey.shaders);
778 transform(pVertShaders.begin(), pVertShaders.end(), inserter,
779 boost::bind(makeShaderKey, _1, Shader::VERTEX));
780 transform(pGeomShaders.begin(), pGeomShaders.end(), inserter,
781 boost::bind(makeShaderKey, _1, Shader::GEOMETRY));
782 transform(pFragShaders.begin(), pFragShaders.end(), inserter,
783 boost::bind(makeShaderKey, _1, Shader::FRAGMENT));
784 for (PropertyList::iterator itr = pAttributes.begin(),
785 e = pAttributes.end();
788 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
790 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
792 if (!pName || ! pIndex)
793 throw BuilderException("malformed attribute property");
795 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
796 pIndex->getValue<int>()));
799 prgKey.paths = options->getDatabasePathList();
800 Program* program = 0;
801 ProgramMap::iterator pitr = programMap.find(prgKey);
802 if (pitr != programMap.end()) {
803 program = pitr->second.get();
804 pass->setAttributeAndModes(program);
807 // The program wasn't in the map using the load path passed in with
808 // the options, but it might have already been loaded using a
809 // different load path i.e., its shaders were found in the fg data
810 // directory. So, resolve the shaders' file names and look in the
811 // resolvedProgramMap for a program using those shaders.
812 ProgramKey resolvedKey;
813 resolvedKey.attributes = prgKey.attributes;
814 BOOST_FOREACH(const ShaderKey& shaderKey, prgKey.shaders)
816 const string& shaderName = shaderKey.first;
817 Shader::Type stype = shaderKey.second;
818 string fileName = SGModelLib::findDataFile(shaderName, options);
819 if (fileName.empty())
820 throw BuilderException(string("couldn't find shader ") +
822 resolvedKey.shaders.push_back(ShaderKey(fileName, stype));
824 ProgramMap::iterator resitr = resolvedProgramMap.find(resolvedKey);
825 if (resitr != resolvedProgramMap.end()) {
826 program = resitr->second.get();
827 programMap.insert(ProgramMap::value_type(prgKey, program));
828 pass->setAttributeAndModes(program);
831 program = new Program;
832 BOOST_FOREACH(const ShaderKey& skey, resolvedKey.shaders)
834 const string& fileName = skey.first;
835 Shader::Type stype = skey.second;
836 ShaderMap::iterator sitr = shaderMap.find(skey);
837 if (sitr != shaderMap.end()) {
838 program->addShader(sitr->second.get());
840 ref_ptr<Shader> shader = new Shader(stype);
841 if (shader->loadShaderSourceFromFile(fileName)) {
842 program->addShader(shader.get());
843 shaderMap.insert(ShaderMap::value_type(skey, shader));
847 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
848 program->addBindAttribLocation(key.first, key.second);
850 const SGPropertyNode* pGeometryVerticesOut
851 = getEffectPropertyChild(effect, prop, "geometry-vertices-out");
852 if (pGeometryVerticesOut)
853 program->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT,
854 pGeometryVerticesOut->getIntValue());
855 const SGPropertyNode* pGeometryInputType
856 = getEffectPropertyChild(effect, prop, "geometry-input-type");
857 if (pGeometryInputType) {
859 findAttr(geometryInputType, pGeometryInputType->getStringValue(), type);
860 program->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT, type);
862 const SGPropertyNode* pGeometryOutputType
863 = getEffectPropertyChild(effect, prop, "geometry-output-type");
864 if (pGeometryOutputType) {
866 findAttr(geometryOutputType, pGeometryOutputType->getStringValue(),
868 program->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, type);
870 programMap.insert(ProgramMap::value_type(prgKey, program));
871 resolvedProgramMap.insert(ProgramMap::value_type(resolvedKey, program));
872 pass->setAttributeAndModes(program);
875 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
877 EffectNameValue<Uniform::Type> uniformTypesInit[] =
879 {"bool", Uniform::BOOL},
880 {"int", Uniform::INT},
881 {"float", Uniform::FLOAT},
882 {"float-vec3", Uniform::FLOAT_VEC3},
883 {"float-vec4", Uniform::FLOAT_VEC4},
884 {"sampler-1d", Uniform::SAMPLER_1D},
885 {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
886 {"sampler-2d", Uniform::SAMPLER_2D},
887 {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
888 {"sampler-3d", Uniform::SAMPLER_3D},
889 {"sampler-cube", Uniform::SAMPLER_CUBE}
891 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
893 // Optimization hack for common uniforms.
894 // XXX protect these with a mutex?
896 ref_ptr<Uniform> texture0;
897 ref_ptr<Uniform> colorMode[3];
899 struct UniformBuilder :public PassAttributeBuilder
901 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
902 const SGReaderWriterXMLOptions* options)
904 if (!texture0.valid()) {
905 texture0 = new Uniform(Uniform::SAMPLER_2D, "texture");
907 texture0->setDataVariance(Object::STATIC);
908 for (int i = 0; i < 3; ++i) {
909 colorMode[i] = new Uniform(Uniform::INT, "colorMode");
910 colorMode[i]->set(i);
911 colorMode[i]->setDataVariance(Object::STATIC);
914 if (!isAttributeActive(effect, prop))
916 const SGPropertyNode* nameProp = prop->getChild("name");
917 const SGPropertyNode* typeProp = prop->getChild("type");
918 const SGPropertyNode* valProp = prop->getChild("value");
920 Uniform::Type uniformType = Uniform::FLOAT;
922 name = nameProp->getStringValue();
924 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
928 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
933 props::Type propType = valProp->getType();
936 uniformType = Uniform::BOOL;
939 uniformType = Uniform::INT;
943 break; // default float type;
945 uniformType = Uniform::FLOAT_VEC3;
948 uniformType = Uniform::FLOAT_VEC4;
951 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
956 findAttr(uniformTypes, typeProp, uniformType);
958 ref_ptr<Uniform> uniform = new Uniform;
959 uniform->setName(name);
960 uniform->setType(uniformType);
961 switch (uniformType) {
963 initFromParameters(effect, valProp, uniform.get(),
964 static_cast<bool (Uniform::*)(float)>(&Uniform::set),
967 case Uniform::FLOAT_VEC3:
968 initFromParameters(effect, valProp, uniform.get(),
969 static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
972 case Uniform::FLOAT_VEC4:
973 initFromParameters(effect, valProp, uniform.get(),
974 static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
978 case Uniform::SAMPLER_1D:
979 case Uniform::SAMPLER_2D:
980 case Uniform::SAMPLER_3D:
981 case Uniform::SAMPLER_1D_SHADOW:
982 case Uniform::SAMPLER_2D_SHADOW:
983 case Uniform::SAMPLER_CUBE:
984 initFromParameters(effect, valProp, uniform.get(),
985 static_cast<bool (Uniform::*)(int)>(&Uniform::set),
988 default: // avoid compiler warning
991 // optimize common uniforms
992 if (uniformType == Uniform::SAMPLER_2D || uniformType == Uniform::INT)
996 if (uniformType == Uniform::SAMPLER_2D && val == 0
997 && name == "texture") {
999 } else if (uniformType == Uniform::INT && val >= 0 && val < 3
1000 && name == "colorMode") {
1001 uniform = colorMode[val];
1004 pass->addUniform(uniform.get());
1008 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
1010 // Not sure what to do with "name". At one point I wanted to use it to
1011 // order the passes, but I do support render bin and stuff too...
1013 struct NameBuilder : public PassAttributeBuilder
1015 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1016 const SGReaderWriterXMLOptions* options)
1018 // name can't use <use>
1019 string name = prop->getStringValue();
1021 pass->setName(name);
1025 InstallAttributeBuilder<NameBuilder> installName("name");
1027 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
1029 {"fill", PolygonMode::FILL},
1030 {"line", PolygonMode::LINE},
1031 {"point", PolygonMode::POINT}
1033 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
1035 struct PolygonModeBuilder : public PassAttributeBuilder
1037 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1038 const SGReaderWriterXMLOptions* options)
1040 if (!isAttributeActive(effect, prop))
1042 const SGPropertyNode* frontProp
1043 = getEffectPropertyChild(effect, prop, "front");
1044 const SGPropertyNode* backProp
1045 = getEffectPropertyChild(effect, prop, "back");
1046 ref_ptr<PolygonMode> pmode = new PolygonMode;
1047 PolygonMode::Mode frontMode = PolygonMode::FILL;
1048 PolygonMode::Mode backMode = PolygonMode::FILL;
1050 findAttr(polygonModeModes, frontProp, frontMode);
1051 pmode->setMode(PolygonMode::FRONT, frontMode);
1054 findAttr(polygonModeModes, backProp, backMode);
1055 pmode->setMode(PolygonMode::BACK, backMode);
1057 pass->setAttribute(pmode.get());
1061 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1063 struct PolygonOffsetBuilder : public PassAttributeBuilder
1065 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1066 const SGReaderWriterXMLOptions* options)
1068 if (!isAttributeActive(effect, prop))
1071 const SGPropertyNode* factor
1072 = getEffectPropertyChild(effect, prop, "factor");
1073 const SGPropertyNode* units
1074 = getEffectPropertyChild(effect, prop, "units");
1076 ref_ptr<PolygonOffset> polyoffset = new PolygonOffset;
1078 polyoffset->setFactor(factor->getFloatValue());
1079 polyoffset->setUnits(units->getFloatValue());
1081 SG_LOG(SG_INPUT, SG_BULK,
1082 "Set PolygonOffset to " << polyoffset->getFactor() << polyoffset->getUnits() );
1084 pass->setAttributeAndModes(polyoffset.get(),
1085 StateAttribute::OVERRIDE|StateAttribute::ON);
1089 InstallAttributeBuilder<PolygonOffsetBuilder> installPolygonOffset("polygon-offset");
1091 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1093 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1094 const SGReaderWriterXMLOptions* options)
1096 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1099 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1100 (realProp->getValue<bool>()
1101 ? StateAttribute::ON : StateAttribute::OFF));
1105 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1106 installTwoSide("vertex-program-two-side");
1108 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1110 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1111 const SGReaderWriterXMLOptions* options)
1113 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1116 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1117 (realProp->getValue<bool>()
1118 ? StateAttribute::ON : StateAttribute::OFF));
1122 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1123 installPointSize("vertex-program-point-size");
1125 EffectNameValue<Depth::Function> depthFunctionInit[] =
1127 {"never", Depth::NEVER},
1128 {"less", Depth::LESS},
1129 {"equal", Depth::EQUAL},
1130 {"lequal", Depth::LEQUAL},
1131 {"greater", Depth::GREATER},
1132 {"notequal", Depth::NOTEQUAL},
1133 {"gequal", Depth::GEQUAL},
1134 {"always", Depth::ALWAYS}
1136 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1138 struct DepthBuilder : public PassAttributeBuilder
1140 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1141 const SGReaderWriterXMLOptions* options)
1143 if (!isAttributeActive(effect, prop))
1145 ref_ptr<Depth> depth = new Depth;
1146 const SGPropertyNode* pfunc
1147 = getEffectPropertyChild(effect, prop, "function");
1149 Depth::Function func = Depth::LESS;
1150 findAttr(depthFunction, pfunc, func);
1151 depth->setFunction(func);
1153 const SGPropertyNode* pnear
1154 = getEffectPropertyChild(effect, prop, "near");
1156 depth->setZNear(pnear->getValue<double>());
1157 const SGPropertyNode* pfar
1158 = getEffectPropertyChild(effect, prop, "far");
1160 depth->setZFar(pnear->getValue<double>());
1161 const SGPropertyNode* pmask
1162 = getEffectPropertyChild(effect, prop, "write-mask");
1164 depth->setWriteMask(pmask->getValue<bool>());
1165 pass->setAttribute(depth.get());
1169 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1171 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1172 const SGReaderWriterXMLOptions* options)
1174 Technique* tniq = new Technique;
1175 effect->techniques.push_back(tniq);
1176 const SGPropertyNode* predProp = prop->getChild("predicate");
1178 tniq->setAlwaysValid(true);
1181 TechniquePredParser parser;
1182 parser.setTechnique(tniq);
1183 expression::BindingLayout& layout = parser.getBindingLayout();
1184 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1185 SGExpressionb* validExp
1186 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1189 tniq->setValidExpression(validExp, layout);
1191 throw expression::ParseError("technique predicate is not a boolean expression");
1193 catch (expression::ParseError& except)
1195 SG_LOG(SG_INPUT, SG_ALERT,
1196 "parsing technique predicate " << except.getMessage());
1197 tniq->setAlwaysValid(false);
1200 PropertyList passProps = prop->getChildren("pass");
1201 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1204 buildPass(effect, tniq, itr->ptr(), options);
1208 // Specifically for .ac files...
1209 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1211 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1212 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1213 Vec4f ambVal, difVal, specVal, emisVal;
1214 float shininess = 0.0f;
1215 const Material* mat = getStateAttribute<Material>(ss);
1217 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1218 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1219 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1220 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1221 shininess = mat->getShininess(Material::FRONT_AND_BACK);
1222 makeChild(matNode, "active")->setValue(true);
1223 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1224 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1225 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1226 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1227 makeChild(matNode, "shininess")->setValue(shininess);
1228 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1230 makeChild(matNode, "active")->setValue(false);
1232 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1233 string shadeModelString("smooth");
1235 ShadeModel::Mode smMode = sm->getMode();
1236 if (smMode == ShadeModel::FLAT)
1237 shadeModelString = "flat";
1239 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1240 string cullFaceString("off");
1241 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1243 switch (cullFace->getMode()) {
1244 case CullFace::FRONT:
1245 cullFaceString = "front";
1247 case CullFace::BACK:
1248 cullFaceString = "back";
1250 case CullFace::FRONT_AND_BACK:
1251 cullFaceString = "front-back";
1257 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1258 // Macintosh ATI workaround
1259 bool vertexTwoSide = cullFaceString == "off";
1260 makeChild(paramRoot, "vertex-program-two-side")->setValue(vertexTwoSide);
1261 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1262 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1264 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1265 string destMode = findName(blendFuncModes, blendFunc->getDestination());
1266 makeChild(blendNode, "active")->setValue(true);
1267 makeChild(blendNode, "source")->setStringValue(sourceMode);
1268 makeChild(blendNode, "destination")->setStringValue(destMode);
1269 makeChild(blendNode, "mode")->setValue(true);
1271 makeChild(blendNode, "active")->setValue(false);
1273 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1274 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1275 makeTextureParameters(paramRoot, ss);
1279 // Walk the techniques property tree, building techniques and
1281 bool Effect::realizeTechniques(const SGReaderWriterXMLOptions* options)
1285 PropertyList tniqList = root->getChildren("technique");
1286 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1289 buildTechnique(this, *itr, options);
1294 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1296 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1299 Effect* effect = eg->getEffect();
1302 SGPropertyNode* root = getPropertyRoot();
1303 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1304 end = effect->_extraData.end();
1307 InitializeWhenAdded* adder
1308 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1310 adder->initOnAdd(effect, root);
1314 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1315 const Effect::Key& rhs) const
1317 if (lhs.paths.size() != rhs.paths.size()
1318 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1320 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1321 return props::Compare()(lhs.unmerged, rhs.unmerged);
1323 return lhs.unmerged == rhs.unmerged;
1326 size_t hash_value(const Effect::Key& key)
1329 if (key.unmerged.valid())
1330 boost::hash_combine(seed, *key.unmerged);
1331 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1335 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1337 const Effect& effect = static_cast<const Effect&>(obj);
1339 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1340 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1341 fw.writeObject(*technique);
1348 osgDB::RegisterDotOsgWrapperProxy effectProxy
1352 "Object simgear::Effect",
1354 &Effect_writeLocalData
1358 // Property expressions for technique predicates
1359 template<typename T>
1360 class PropertyExpression : public SGExpression<T>
1363 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1365 void eval(T& value, const expression::Binding*) const
1367 value = _pnode->getValue<T>();
1370 SGPropertyNode_ptr _pnode;
1373 class EffectPropertyListener : public SGPropertyChangeListener
1376 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1378 void valueChanged(SGPropertyNode* node)
1380 _tniq->refreshValidity();
1383 osg::ref_ptr<Technique> _tniq;
1386 template<typename T>
1387 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1388 expression::Parser* parser)
1390 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1392 PropertyExpression<T>* pexp = new PropertyExpression<T>(pnode);
1393 TechniquePredParser* predParser
1394 = dynamic_cast<TechniquePredParser*>(parser);
1396 pnode->addChangeListener(new EffectPropertyListener(predParser
1401 expression::ExpParserRegistrar propertyRegistrar("property",
1402 propertyExpressionParser<bool>);
1404 expression::ExpParserRegistrar propvalueRegistrar("float-property",
1405 propertyExpressionParser<float>);