1 // Copyright (C) 2008 - 2009 Tim Moore timoore@redhat.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/Program>
50 #include <osg/Referenced>
51 #include <osg/RenderInfo>
52 #include <osg/ShadeModel>
53 #include <osg/StateSet>
54 #include <osg/Stencil>
56 #include <osg/Texture1D>
57 #include <osg/Texture2D>
58 #include <osg/Texture3D>
59 #include <osg/TextureRectangle>
60 #include <osg/Uniform>
62 #include <osgUtil/CullVisitor>
63 #include <osgDB/FileUtils>
64 #include <osgDB/Input>
65 #include <osgDB/ParameterOutput>
66 #include <osgDB/ReadFile>
67 #include <osgDB/Registry>
69 #include <simgear/scene/tgdb/userdata.hxx>
70 #include <simgear/scene/util/SGSceneFeatures.hxx>
71 #include <simgear/scene/util/StateAttributeFactory.hxx>
72 #include <simgear/structure/OSGUtils.hxx>
73 #include <simgear/structure/SGExpression.hxx>
81 using namespace osgUtil;
83 using namespace effect;
86 : _cache(0), _isRealized(false)
90 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
91 : root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
92 _isRealized(rhs._isRealized)
94 typedef vector<ref_ptr<Technique> > TechniqueList;
95 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
96 end = rhs.techniques.end();
99 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
102 // Assume that the last technique is always valid.
103 StateSet* Effect::getDefaultStateSet()
105 Technique* tniq = techniques.back().get();
108 Pass* pass = tniq->passes.front().get();
112 // There should always be a valid technique in an effect.
114 Technique* Effect::chooseTechnique(RenderInfo* info)
116 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
118 if (technique->valid(info) == Technique::VALID)
119 return technique.get();
124 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
126 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
128 technique->resizeGLObjectBuffers(maxSize);
132 void Effect::releaseGLObjects(osg::State* state) const
134 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
136 technique->releaseGLObjects(state);
145 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
146 const osgDB::ReaderWriter::Options* options)
148 Pass* pass = new Pass;
149 tniq->passes.push_back(pass);
150 for (int i = 0; i < prop->nChildren(); ++i) {
151 const SGPropertyNode* attrProp = prop->getChild(i);
152 PassAttributeBuilder* builder
153 = PassAttributeBuilder::find(attrProp->getNameString());
155 builder->buildAttribute(effect, pass, attrProp, options);
157 SG_LOG(SG_INPUT, SG_ALERT,
158 "skipping unknown pass attribute " << attrProp->getName());
162 osg::Vec4f getColor(const SGPropertyNode* prop)
164 if (prop->nChildren() == 0) {
165 if (prop->getType() == props::VEC4D) {
166 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
167 } else if (prop->getType() == props::VEC3D) {
168 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
170 SG_LOG(SG_INPUT, SG_ALERT,
171 "invalid color property " << prop->getName() << " "
172 << prop->getStringValue());
173 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
177 static const char* colors[] = {"r", "g", "b"};
178 for (int i = 0; i < 3; ++i) {
179 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
180 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
182 const SGPropertyNode* alphaProp = prop->getChild("a");
183 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
188 struct LightingBuilder : public PassAttributeBuilder
190 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
191 const osgDB::ReaderWriter::Options* options);
194 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
195 const SGPropertyNode* prop,
196 const osgDB::ReaderWriter::Options* options)
198 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
201 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
202 : StateAttribute::OFF));
205 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
207 struct ShadeModelBuilder : public PassAttributeBuilder
209 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
210 const osgDB::ReaderWriter::Options* options)
212 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
215 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
216 string propVal = realProp->getStringValue();
217 if (propVal == "flat")
218 pass->setAttribute(attrFact->getFlatShadeModel());
219 else if (propVal == "smooth")
220 pass->setAttribute(attrFact->getSmoothShadeModel());
222 SG_LOG(SG_INPUT, SG_ALERT,
223 "invalid shade model property " << propVal);
227 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
229 struct CullFaceBuilder : PassAttributeBuilder
231 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
232 const osgDB::ReaderWriter::Options* options)
234 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
236 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
239 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
240 string propVal = realProp->getStringValue();
241 if (propVal == "front")
242 pass->setAttributeAndModes(attrFact->getCullFaceFront());
243 else if (propVal == "back")
244 pass->setAttributeAndModes(attrFact->getCullFaceBack());
245 else if (propVal == "front-back")
246 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
247 else if (propVal == "off")
248 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
250 SG_LOG(SG_INPUT, SG_ALERT,
251 "invalid cull face property " << propVal);
255 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
257 struct ColorMaskBuilder : PassAttributeBuilder
259 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
260 const osgDB::ReaderWriter::Options* options)
262 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
266 ColorMask *mask = new ColorMask;
267 Vec4 m = getColor(realProp);
268 mask->setMask(m.r(), m.g(), m.b(), m.a());
269 pass->setAttributeAndModes(mask);
273 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
275 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
277 { "default", StateSet::DEFAULT_BIN },
278 { "opaque", StateSet::OPAQUE_BIN },
279 { "transparent", StateSet::TRANSPARENT_BIN }
282 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
284 struct HintBuilder : public PassAttributeBuilder
286 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
287 const osgDB::ReaderWriter::Options* options)
289 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
292 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
293 findAttr(renderingHints, realProp, renderingHint);
294 pass->setRenderingHint(renderingHint);
298 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
300 struct RenderBinBuilder : public PassAttributeBuilder
302 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
303 const osgDB::ReaderWriter::Options* options)
305 if (!isAttributeActive(effect, prop))
307 const SGPropertyNode* binProp = prop->getChild("bin-number");
308 binProp = getEffectPropertyNode(effect, binProp);
309 const SGPropertyNode* nameProp = prop->getChild("bin-name");
310 nameProp = getEffectPropertyNode(effect, nameProp);
311 if (binProp && nameProp) {
312 pass->setRenderBinDetails(binProp->getIntValue(),
313 nameProp->getStringValue());
316 SG_LOG(SG_INPUT, SG_ALERT,
317 "No render bin number specified in render bin section");
319 SG_LOG(SG_INPUT, SG_ALERT,
320 "No render bin name specified in render bin section");
325 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
327 struct MaterialBuilder : public PassAttributeBuilder
329 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
330 const osgDB::ReaderWriter::Options* options);
333 EffectNameValue<Material::ColorMode> colorModeInit[] =
335 { "ambient", Material::AMBIENT },
336 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
337 { "diffuse", Material::DIFFUSE },
338 { "emissive", Material::EMISSION },
339 { "specular", Material::SPECULAR },
340 { "off", Material::OFF }
342 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
344 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
345 const SGPropertyNode* prop,
346 const osgDB::ReaderWriter::Options* options)
348 if (!isAttributeActive(effect, prop))
350 Material* mat = new Material;
351 const SGPropertyNode* color = 0;
352 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
353 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
354 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
355 mat->setAmbient(Material::FRONT, getColor(color));
356 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
357 mat->setAmbient(Material::BACK, getColor(color));
358 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
359 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
360 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
361 mat->setDiffuse(Material::FRONT, getColor(color));
362 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
363 mat->setDiffuse(Material::BACK, getColor(color));
364 if ((color = getEffectPropertyChild(effect, prop, "specular")))
365 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
366 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
367 mat->setSpecular(Material::FRONT, getColor(color));
368 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
369 mat->setSpecular(Material::BACK, getColor(color));
370 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
371 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
372 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
373 mat->setEmission(Material::FRONT, getColor(color));
374 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
375 mat->setEmission(Material::BACK, getColor(color));
376 const SGPropertyNode* shininess = 0;
377 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
378 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
379 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
380 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
381 mat->setShininess(Material::FRONT, shininess->getFloatValue());
382 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
383 mat->setShininess(Material::BACK, shininess->getFloatValue());
384 Material::ColorMode colorMode = Material::OFF;
385 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
387 mat->setColorMode(colorMode);
388 pass->setAttribute(mat);
391 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
393 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
395 {"dst-alpha", BlendFunc::DST_ALPHA},
396 {"dst-color", BlendFunc::DST_COLOR},
397 {"one", BlendFunc::ONE},
398 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
399 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
400 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
401 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
402 {"src-alpha", BlendFunc::SRC_ALPHA},
403 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
404 {"src-color", BlendFunc::SRC_COLOR},
405 {"constant-color", BlendFunc::CONSTANT_COLOR},
406 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
407 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
408 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
409 {"zero", BlendFunc::ZERO}
411 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
413 struct BlendBuilder : public PassAttributeBuilder
415 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
416 const osgDB::ReaderWriter::Options* options)
418 if (!isAttributeActive(effect, prop))
420 // XXX Compatibility with early <blend> syntax; should go away
422 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
425 if (realProp->nChildren() == 0) {
426 pass->setMode(GL_BLEND, (realProp->getBoolValue()
428 : StateAttribute::OFF));
432 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
434 // XXX When dynamic parameters are supported, this code should
435 // create the blend function even if the mode is off.
436 if (pmode && !pmode->getValue<bool>()) {
437 pass->setMode(GL_BLEND, StateAttribute::OFF);
440 const SGPropertyNode* psource
441 = getEffectPropertyChild(effect, prop, "source");
442 const SGPropertyNode* pdestination
443 = getEffectPropertyChild(effect, prop, "destination");
444 const SGPropertyNode* psourceRGB
445 = getEffectPropertyChild(effect, prop, "source-rgb");
446 const SGPropertyNode* psourceAlpha
447 = getEffectPropertyChild(effect, prop, "source-alpha");
448 const SGPropertyNode* pdestRGB
449 = getEffectPropertyChild(effect, prop, "destination-rgb");
450 const SGPropertyNode* pdestAlpha
451 = getEffectPropertyChild(effect, prop, "destination-alpha");
452 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
453 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
455 findAttr(blendFuncModes, psource, sourceMode);
457 findAttr(blendFuncModes, pdestination, destMode);
458 if (psource && pdestination
459 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
460 && sourceMode == BlendFunc::SRC_ALPHA
461 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
462 pass->setAttributeAndModes(StateAttributeFactory::instance()
463 ->getStandardBlendFunc());
466 BlendFunc* blendFunc = new BlendFunc;
468 blendFunc->setSource(sourceMode);
470 blendFunc->setDestination(destMode);
472 BlendFunc::BlendFuncMode sourceRGBMode;
473 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
474 blendFunc->setSourceRGB(sourceRGBMode);
477 BlendFunc::BlendFuncMode destRGBMode;
478 findAttr(blendFuncModes, pdestRGB, destRGBMode);
479 blendFunc->setDestinationRGB(destRGBMode);
482 BlendFunc::BlendFuncMode sourceAlphaMode;
483 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
484 blendFunc->setSourceAlpha(sourceAlphaMode);
487 BlendFunc::BlendFuncMode destAlphaMode;
488 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
489 blendFunc->setDestinationAlpha(destAlphaMode);
491 pass->setAttributeAndModes(blendFunc);
495 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
498 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
500 {"never", Stencil::NEVER },
501 {"less", Stencil::LESS},
502 {"equal", Stencil::EQUAL},
503 {"less-or-equal", Stencil::LEQUAL},
504 {"greater", Stencil::GREATER},
505 {"not-equal", Stencil::NOTEQUAL},
506 {"greater-or-equal", Stencil::GEQUAL},
507 {"always", Stencil::ALWAYS}
510 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
512 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
514 {"keep", Stencil::KEEP},
515 {"zero", Stencil::ZERO},
516 {"replace", Stencil::REPLACE},
517 {"increase", Stencil::INCR},
518 {"decrease", Stencil::DECR},
519 {"invert", Stencil::INVERT},
520 {"increase-wrap", Stencil::INCR_WRAP},
521 {"decrease-wrap", Stencil::DECR_WRAP}
524 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
526 struct StencilBuilder : public PassAttributeBuilder
528 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
529 const osgDB::ReaderWriter::Options* options)
531 if (!isAttributeActive(effect, prop))
534 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
536 if (pmode && !pmode->getValue<bool>()) {
537 pass->setMode(GL_STENCIL, StateAttribute::OFF);
540 const SGPropertyNode* pfunction
541 = getEffectPropertyChild(effect, prop, "function");
542 const SGPropertyNode* pvalue
543 = getEffectPropertyChild(effect, prop, "value");
544 const SGPropertyNode* pmask
545 = getEffectPropertyChild(effect, prop, "mask");
546 const SGPropertyNode* psfail
547 = getEffectPropertyChild(effect, prop, "stencil-fail");
548 const SGPropertyNode* pzfail
549 = getEffectPropertyChild(effect, prop, "z-fail");
550 const SGPropertyNode* ppass
551 = getEffectPropertyChild(effect, prop, "pass");
553 Stencil::Function func = Stencil::ALWAYS; // Always pass
555 unsigned int mask = ~0u; // All bits on
556 Stencil::Operation sfailop = Stencil::KEEP; // Keep the old values as default
557 Stencil::Operation zfailop = Stencil::KEEP;
558 Stencil::Operation passop = Stencil::KEEP;
560 ref_ptr<Stencil> stencilFunc = new Stencil;
563 findAttr(stencilFunction, pfunction, func);
565 ref = pvalue->getIntValue();
567 mask = pmask->getIntValue();
570 findAttr(stencilOperation, psfail, sfailop);
572 findAttr(stencilOperation, pzfail, zfailop);
574 findAttr(stencilOperation, ppass, passop);
576 // Set the stencil operation
577 stencilFunc->setFunction(func, ref, mask);
579 // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
580 stencilFunc->setOperation(sfailop, zfailop, passop);
582 // Add the operation to pass
583 pass->setAttributeAndModes(stencilFunc.get());
587 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
590 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
592 {"never", AlphaFunc::NEVER},
593 {"less", AlphaFunc::LESS},
594 {"equal", AlphaFunc::EQUAL},
595 {"lequal", AlphaFunc::LEQUAL},
596 {"greater", AlphaFunc::GREATER},
597 {"notequal", AlphaFunc::NOTEQUAL},
598 {"gequal", AlphaFunc::GEQUAL},
599 {"always", AlphaFunc::ALWAYS}
601 EffectPropertyMap<AlphaFunc::ComparisonFunction>
602 alphaComparison(alphaComparisonInit);
604 struct AlphaTestBuilder : public PassAttributeBuilder
606 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
607 const osgDB::ReaderWriter::Options* options)
609 if (!isAttributeActive(effect, prop))
611 // XXX Compatibility with early <alpha-test> syntax; should go away
613 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
616 if (realProp->nChildren() == 0) {
617 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
619 : StateAttribute::OFF));
623 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
625 // XXX When dynamic parameters are supported, this code should
626 // create the blend function even if the mode is off.
627 if (pmode && !pmode->getValue<bool>()) {
628 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
631 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
633 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
635 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
636 float refValue = 1.0f;
638 findAttr(alphaComparison, pComp, func);
640 refValue = pRef->getValue<float>();
641 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
642 pass->setAttributeAndModes(StateAttributeFactory::instance()
643 ->getStandardAlphaFunc());
645 AlphaFunc* alphaFunc = new AlphaFunc;
646 alphaFunc->setFunction(func);
647 alphaFunc->setReferenceValue(refValue);
648 pass->setAttributeAndModes(alphaFunc);
653 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
655 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
657 // Shader key, used both for shaders with relative and absolute names
658 typedef pair<string, Shader::Type> ShaderKey;
662 typedef pair<string, int> AttribKey;
663 osgDB::FilePathList paths;
664 vector<ShaderKey> shaders;
665 vector<AttribKey> attributes;
668 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
670 return (lhs.paths.size() == rhs.paths.size()
671 && equal(lhs.paths.begin(), lhs.paths.end(),
673 && lhs.shaders.size() == rhs.shaders.size()
674 && equal (lhs.shaders.begin(), lhs.shaders.end(),
676 && lhs.attributes.size() == rhs.attributes.size()
677 && equal(lhs.attributes.begin(), lhs.attributes.end(),
678 rhs.attributes.begin()));
683 size_t hash_value(const ProgramKey& key)
686 boost::hash_range(seed, key.paths.begin(), key.paths.end());
687 boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
688 boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
692 // XXX Should these be protected by a mutex? Probably
694 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
695 boost::hash<ProgramKey>, ProgramKey::EqualTo>
697 ProgramMap programMap;
699 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
703 void reload_shaders()
705 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
707 Shader *shader = sitr->second.get();
708 string fileName = osgDB::findDataFile(sitr->first.first);
709 if (!fileName.empty()) {
710 shader->loadShaderSourceFromFile(fileName);
715 struct ShaderProgramBuilder : PassAttributeBuilder
717 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
718 const osgDB::ReaderWriter::Options* options);
721 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
722 const SGPropertyNode* prop,
723 const osgDB::ReaderWriter::Options*
726 using namespace boost;
727 if (!isAttributeActive(effect, prop))
729 PropertyList pVertShaders = prop->getChildren("vertex-shader");
730 PropertyList pFragShaders = prop->getChildren("fragment-shader");
731 PropertyList pAttributes = prop->getChildren("attribute");
733 for (PropertyList::iterator itr = pVertShaders.begin(),
734 e = pVertShaders.end();
737 prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
739 for (PropertyList::iterator itr = pFragShaders.begin(),
740 e = pFragShaders.end();
743 prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
745 for (PropertyList::iterator itr = pAttributes.begin(),
746 e = pAttributes.end();
749 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
751 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
753 if (!pName || ! pIndex)
754 throw BuilderException("malformed attribute property");
756 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
757 pIndex->getValue<int>()));
760 prgKey.paths = options->getDatabasePathList();
761 Program* program = 0;
762 ProgramMap::iterator pitr = programMap.find(prgKey);
763 if (pitr != programMap.end()) {
764 program = pitr->second.get();
766 program = new Program;
767 // Add vertex shaders, then fragment shaders
768 PropertyList& pvec = pVertShaders;
769 Shader::Type stype = Shader::VERTEX;
770 for (int i = 0; i < 2; ++i) {
771 for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
774 string shaderName = (*nameItr)->getStringValue();
775 string fileName = osgDB::findDataFile(shaderName, options);
776 if (fileName.empty())
777 throw BuilderException(string("couldn't find shader ") +
779 ShaderKey skey(fileName, stype);
780 ShaderMap::iterator sitr = shaderMap.find(skey);
781 if (sitr != shaderMap.end()) {
782 program->addShader(sitr->second.get());
784 ref_ptr<Shader> shader = new Shader(stype);
785 if (shader->loadShaderSourceFromFile(fileName)) {
786 program->addShader(shader.get());
787 shaderMap.insert(ShaderMap::value_type(skey, shader));
792 stype = Shader::FRAGMENT;
794 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
795 program->addBindAttribLocation(key.first, key.second);
797 programMap.insert(ProgramMap::value_type(prgKey, program));
799 pass->setAttributeAndModes(program);
802 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
804 EffectNameValue<Uniform::Type> uniformTypesInit[] =
806 {"float", Uniform::FLOAT},
807 {"float-vec3", Uniform::FLOAT_VEC3},
808 {"float-vec4", Uniform::FLOAT_VEC4},
809 {"sampler-1d", Uniform::SAMPLER_1D},
810 {"sampler-2d", Uniform::SAMPLER_2D},
811 {"sampler-3d", Uniform::SAMPLER_3D}
813 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
815 struct UniformBuilder :public PassAttributeBuilder
817 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
818 const osgDB::ReaderWriter::Options* options)
820 if (!isAttributeActive(effect, prop))
822 const SGPropertyNode* nameProp = prop->getChild("name");
823 const SGPropertyNode* typeProp = prop->getChild("type");
824 const SGPropertyNode* valProp
825 = getEffectPropertyChild(effect, prop, "value");
827 Uniform::Type uniformType = Uniform::FLOAT;
829 name = nameProp->getStringValue();
831 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
835 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
840 props::Type propType = valProp->getType();
844 break; // default float type;
846 uniformType = Uniform::FLOAT_VEC3;
849 uniformType = Uniform::FLOAT_VEC4;
852 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
857 findAttr(uniformTypes, typeProp, uniformType);
859 ref_ptr<Uniform> uniform = new Uniform;
860 uniform->setName(name);
861 uniform->setType(uniformType);
862 switch (uniformType) {
864 uniform->set(valProp->getValue<float>());
866 case Uniform::FLOAT_VEC3:
867 uniform->set(toOsg(valProp->getValue<SGVec3d>()));
869 case Uniform::FLOAT_VEC4:
870 uniform->set(toOsg(valProp->getValue<SGVec4d>()));
872 case Uniform::SAMPLER_1D:
873 case Uniform::SAMPLER_2D:
874 case Uniform::SAMPLER_3D:
875 uniform->set(valProp->getValue<int>());
877 default: // avoid compiler warning
880 pass->addUniform(uniform.get());
884 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
886 // Not sure what to do with "name". At one point I wanted to use it to
887 // order the passes, but I do support render bin and stuff too...
889 struct NameBuilder : public PassAttributeBuilder
891 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
892 const osgDB::ReaderWriter::Options* options)
894 // name can't use <use>
895 string name = prop->getStringValue();
901 InstallAttributeBuilder<NameBuilder> installName("name");
903 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
905 {"fill", PolygonMode::FILL},
906 {"line", PolygonMode::LINE},
907 {"point", PolygonMode::POINT}
909 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
911 struct PolygonModeBuilder : public PassAttributeBuilder
913 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
914 const osgDB::ReaderWriter::Options* options)
916 if (!isAttributeActive(effect, prop))
918 const SGPropertyNode* frontProp
919 = getEffectPropertyChild(effect, prop, "front");
920 const SGPropertyNode* backProp
921 = getEffectPropertyChild(effect, prop, "back");
922 ref_ptr<PolygonMode> pmode = new PolygonMode;
923 PolygonMode::Mode frontMode = PolygonMode::FILL;
924 PolygonMode::Mode backMode = PolygonMode::FILL;
926 findAttr(polygonModeModes, frontProp, frontMode);
927 pmode->setMode(PolygonMode::FRONT, frontMode);
930 findAttr(polygonModeModes, backProp, backMode);
931 pmode->setMode(PolygonMode::BACK, backMode);
933 pass->setAttribute(pmode.get());
937 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
939 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
941 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
942 const osgDB::ReaderWriter::Options* options)
944 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
947 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
948 (realProp->getValue<bool>()
949 ? StateAttribute::ON : StateAttribute::OFF));
953 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
954 installTwoSide("vertex-program-two-side");
956 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
958 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
959 const osgDB::ReaderWriter::Options* options)
961 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
964 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
965 (realProp->getValue<bool>()
966 ? StateAttribute::ON : StateAttribute::OFF));
970 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
971 installPointSize("vertex-program-point-size");
973 EffectNameValue<Depth::Function> depthFunctionInit[] =
975 {"never", Depth::NEVER},
976 {"less", Depth::LESS},
977 {"equal", Depth::EQUAL},
978 {"lequal", Depth::LEQUAL},
979 {"greater", Depth::GREATER},
980 {"notequal", Depth::NOTEQUAL},
981 {"gequal", Depth::GEQUAL},
982 {"always", Depth::ALWAYS}
984 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
986 struct DepthBuilder : public PassAttributeBuilder
988 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
989 const osgDB::ReaderWriter::Options* options)
991 if (!isAttributeActive(effect, prop))
993 ref_ptr<Depth> depth = new Depth;
994 const SGPropertyNode* pfunc
995 = getEffectPropertyChild(effect, prop, "function");
997 Depth::Function func = Depth::LESS;
998 findAttr(depthFunction, pfunc, func);
999 depth->setFunction(func);
1001 const SGPropertyNode* pnear
1002 = getEffectPropertyChild(effect, prop, "near");
1004 depth->setZNear(pnear->getValue<double>());
1005 const SGPropertyNode* pfar
1006 = getEffectPropertyChild(effect, prop, "far");
1008 depth->setZFar(pnear->getValue<double>());
1009 const SGPropertyNode* pmask
1010 = getEffectPropertyChild(effect, prop, "write-mask");
1012 depth->setWriteMask(pmask->getValue<bool>());
1013 pass->setAttribute(depth.get());
1017 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1019 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1020 const osgDB::ReaderWriter::Options* options)
1022 Technique* tniq = new Technique;
1023 effect->techniques.push_back(tniq);
1024 const SGPropertyNode* predProp = prop->getChild("predicate");
1026 tniq->setAlwaysValid(true);
1029 TechniquePredParser parser;
1030 parser.setTechnique(tniq);
1031 expression::BindingLayout& layout = parser.getBindingLayout();
1032 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1033 SGExpressionb* validExp
1034 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1037 tniq->setValidExpression(validExp, layout);
1039 throw expression::ParseError("technique predicate is not a boolean expression");
1041 catch (expression::ParseError& except)
1043 SG_LOG(SG_INPUT, SG_ALERT,
1044 "parsing technique predicate " << except.getMessage());
1045 tniq->setAlwaysValid(false);
1048 PropertyList passProps = prop->getChildren("pass");
1049 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1052 buildPass(effect, tniq, itr->ptr(), options);
1056 // Specifically for .ac files...
1057 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1059 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1060 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1061 Vec4f ambVal, difVal, specVal, emisVal;
1062 float shininess = 0.0f;
1063 const Material* mat = getStateAttribute<Material>(ss);
1065 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1066 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1067 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1068 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1069 shininess = mat->getShininess(Material::FRONT_AND_BACK);
1070 makeChild(matNode, "active")->setValue(true);
1071 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1072 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1073 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1074 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1075 makeChild(matNode, "shininess")->setValue(shininess);
1076 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1078 makeChild(matNode, "active")->setValue(false);
1080 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1081 string shadeModelString("smooth");
1083 ShadeModel::Mode smMode = sm->getMode();
1084 if (smMode == ShadeModel::FLAT)
1085 shadeModelString = "flat";
1087 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1088 string cullFaceString("off");
1089 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1091 switch (cullFace->getMode()) {
1092 case CullFace::FRONT:
1093 cullFaceString = "front";
1095 case CullFace::BACK:
1096 cullFaceString = "back";
1098 case CullFace::FRONT_AND_BACK:
1099 cullFaceString = "front-back";
1105 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1106 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1107 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1109 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1110 string destMode = findName(blendFuncModes, blendFunc->getDestination());
1111 makeChild(blendNode, "active")->setValue(true);
1112 makeChild(blendNode, "source")->setStringValue(sourceMode);
1113 makeChild(blendNode, "destination")->setStringValue(destMode);
1114 makeChild(blendNode, "mode")->setValue(true);
1116 makeChild(blendNode, "active")->setValue(false);
1118 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1119 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1120 makeTextureParameters(paramRoot, ss);
1124 // Walk the techniques property tree, building techniques and
1126 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
1130 PropertyList tniqList = root->getChildren("technique");
1131 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1134 buildTechnique(this, *itr, options);
1139 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1141 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1144 Effect* effect = eg->getEffect();
1147 SGPropertyNode* root = getPropertyRoot();
1148 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1149 end = effect->_extraData.end();
1152 InitializeWhenAdded* adder
1153 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1155 adder->initOnAdd(effect, root);
1159 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1160 const Effect::Key& rhs) const
1162 if (lhs.paths.size() != rhs.paths.size()
1163 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1165 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1166 return props::Compare()(lhs.unmerged, rhs.unmerged);
1168 return lhs.unmerged == rhs.unmerged;
1171 size_t hash_value(const Effect::Key& key)
1174 if (key.unmerged.valid())
1175 boost::hash_combine(seed, *key.unmerged);
1176 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1180 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1182 const Effect& effect = static_cast<const Effect&>(obj);
1184 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1185 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1186 fw.writeObject(*technique);
1193 osgDB::RegisterDotOsgWrapperProxy effectProxy
1197 "Object simgear::Effect",
1199 &Effect_writeLocalData
1203 // Property expressions for technique predicates
1204 class PropertyExpression : public SGExpression<bool>
1207 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1209 void eval(bool& value, const expression::Binding*) const
1211 value = _pnode->getValue<bool>();
1214 SGPropertyNode_ptr _pnode;
1217 class EffectPropertyListener : public SGPropertyChangeListener
1220 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1222 void valueChanged(SGPropertyNode* node)
1224 _tniq->refreshValidity();
1227 osg::ref_ptr<Technique> _tniq;
1230 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1231 expression::Parser* parser)
1233 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1235 PropertyExpression* pexp = new PropertyExpression(pnode);
1236 TechniquePredParser* predParser
1237 = dynamic_cast<TechniquePredParser*>(parser);
1239 pnode->addChangeListener(new EffectPropertyListener(predParser
1244 expression::ExpParserRegistrar propertyRegistrar("property",
1245 propertyExpressionParser);