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/model/SGReaderWriterXMLOptions.hxx>
70 #include <simgear/scene/tgdb/userdata.hxx>
71 #include <simgear/scene/util/SGSceneFeatures.hxx>
72 #include <simgear/scene/util/StateAttributeFactory.hxx>
73 #include <simgear/structure/OSGUtils.hxx>
74 #include <simgear/structure/SGExpression.hxx>
82 using namespace osgUtil;
84 using namespace effect;
87 : _cache(0), _isRealized(false)
91 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
92 : root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
93 _isRealized(rhs._isRealized)
95 typedef vector<ref_ptr<Technique> > TechniqueList;
96 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
97 end = rhs.techniques.end();
100 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
103 // Assume that the last technique is always valid.
104 StateSet* Effect::getDefaultStateSet()
106 Technique* tniq = techniques.back().get();
109 Pass* pass = tniq->passes.front().get();
113 // There should always be a valid technique in an effect.
115 Technique* Effect::chooseTechnique(RenderInfo* info)
117 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
119 if (technique->valid(info) == Technique::VALID)
120 return technique.get();
125 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
127 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
129 technique->resizeGLObjectBuffers(maxSize);
133 void Effect::releaseGLObjects(osg::State* state) const
135 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
137 technique->releaseGLObjects(state);
146 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
147 const SGReaderWriterXMLOptions* options)
149 Pass* pass = new Pass;
150 tniq->passes.push_back(pass);
151 for (int i = 0; i < prop->nChildren(); ++i) {
152 const SGPropertyNode* attrProp = prop->getChild(i);
153 PassAttributeBuilder* builder
154 = PassAttributeBuilder::find(attrProp->getNameString());
156 builder->buildAttribute(effect, pass, attrProp, options);
158 SG_LOG(SG_INPUT, SG_ALERT,
159 "skipping unknown pass attribute " << attrProp->getName());
163 // Default names for vector property components
164 const char* vec3Names[] = {"x", "y", "z"};
165 const char* vec4Names[] = {"x", "y", "z", "w"};
167 osg::Vec4f getColor(const SGPropertyNode* prop)
169 if (prop->nChildren() == 0) {
170 if (prop->getType() == props::VEC4D) {
171 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
172 } else if (prop->getType() == props::VEC3D) {
173 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
175 SG_LOG(SG_INPUT, SG_ALERT,
176 "invalid color property " << prop->getName() << " "
177 << prop->getStringValue());
178 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
182 static const char* colors[] = {"r", "g", "b"};
183 for (int i = 0; i < 3; ++i) {
184 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
185 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
187 const SGPropertyNode* alphaProp = prop->getChild("a");
188 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
193 struct LightingBuilder : public PassAttributeBuilder
195 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
196 const SGReaderWriterXMLOptions* options);
199 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
200 const SGPropertyNode* prop,
201 const SGReaderWriterXMLOptions* options)
203 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
206 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
207 : StateAttribute::OFF));
210 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
212 struct ShadeModelBuilder : public PassAttributeBuilder
214 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
215 const SGReaderWriterXMLOptions* options)
217 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
220 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
221 string propVal = realProp->getStringValue();
222 if (propVal == "flat")
223 pass->setAttribute(attrFact->getFlatShadeModel());
224 else if (propVal == "smooth")
225 pass->setAttribute(attrFact->getSmoothShadeModel());
227 SG_LOG(SG_INPUT, SG_ALERT,
228 "invalid shade model property " << propVal);
232 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
234 struct CullFaceBuilder : PassAttributeBuilder
236 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
237 const SGReaderWriterXMLOptions* options)
239 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
241 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
244 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
245 string propVal = realProp->getStringValue();
246 if (propVal == "front")
247 pass->setAttributeAndModes(attrFact->getCullFaceFront());
248 else if (propVal == "back")
249 pass->setAttributeAndModes(attrFact->getCullFaceBack());
250 else if (propVal == "front-back")
251 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
252 else if (propVal == "off")
253 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
255 SG_LOG(SG_INPUT, SG_ALERT,
256 "invalid cull face property " << propVal);
260 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
262 struct ColorMaskBuilder : PassAttributeBuilder
264 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
265 const SGReaderWriterXMLOptions* options)
267 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
271 ColorMask *mask = new ColorMask;
272 Vec4 m = getColor(realProp);
273 mask->setMask(m.r(), m.g(), m.b(), m.a());
274 pass->setAttributeAndModes(mask);
278 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
280 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
282 { "default", StateSet::DEFAULT_BIN },
283 { "opaque", StateSet::OPAQUE_BIN },
284 { "transparent", StateSet::TRANSPARENT_BIN }
287 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
289 struct HintBuilder : public PassAttributeBuilder
291 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
292 const SGReaderWriterXMLOptions* options)
294 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
297 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
298 findAttr(renderingHints, realProp, renderingHint);
299 pass->setRenderingHint(renderingHint);
303 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
305 struct RenderBinBuilder : public PassAttributeBuilder
307 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
308 const SGReaderWriterXMLOptions* options)
310 if (!isAttributeActive(effect, prop))
312 const SGPropertyNode* binProp = prop->getChild("bin-number");
313 binProp = getEffectPropertyNode(effect, binProp);
314 const SGPropertyNode* nameProp = prop->getChild("bin-name");
315 nameProp = getEffectPropertyNode(effect, nameProp);
316 if (binProp && nameProp) {
317 pass->setRenderBinDetails(binProp->getIntValue(),
318 nameProp->getStringValue());
321 SG_LOG(SG_INPUT, SG_ALERT,
322 "No render bin number specified in render bin section");
324 SG_LOG(SG_INPUT, SG_ALERT,
325 "No render bin name specified in render bin section");
330 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
332 struct MaterialBuilder : public PassAttributeBuilder
334 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
335 const SGReaderWriterXMLOptions* options);
338 EffectNameValue<Material::ColorMode> colorModeInit[] =
340 { "ambient", Material::AMBIENT },
341 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
342 { "diffuse", Material::DIFFUSE },
343 { "emissive", Material::EMISSION },
344 { "specular", Material::SPECULAR },
345 { "off", Material::OFF }
347 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
349 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
350 const SGPropertyNode* prop,
351 const SGReaderWriterXMLOptions* options)
353 if (!isAttributeActive(effect, prop))
355 Material* mat = new Material;
356 const SGPropertyNode* color = 0;
357 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
358 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
359 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
360 mat->setAmbient(Material::FRONT, getColor(color));
361 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
362 mat->setAmbient(Material::BACK, getColor(color));
363 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
364 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
365 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
366 mat->setDiffuse(Material::FRONT, getColor(color));
367 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
368 mat->setDiffuse(Material::BACK, getColor(color));
369 if ((color = getEffectPropertyChild(effect, prop, "specular")))
370 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
371 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
372 mat->setSpecular(Material::FRONT, getColor(color));
373 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
374 mat->setSpecular(Material::BACK, getColor(color));
375 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
376 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
377 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
378 mat->setEmission(Material::FRONT, getColor(color));
379 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
380 mat->setEmission(Material::BACK, getColor(color));
381 const SGPropertyNode* shininess = 0;
382 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
383 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
384 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
385 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
386 mat->setShininess(Material::FRONT, shininess->getFloatValue());
387 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
388 mat->setShininess(Material::BACK, shininess->getFloatValue());
389 Material::ColorMode colorMode = Material::OFF;
390 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
392 mat->setColorMode(colorMode);
393 pass->setAttribute(mat);
396 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
398 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
400 {"dst-alpha", BlendFunc::DST_ALPHA},
401 {"dst-color", BlendFunc::DST_COLOR},
402 {"one", BlendFunc::ONE},
403 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
404 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
405 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
406 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
407 {"src-alpha", BlendFunc::SRC_ALPHA},
408 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
409 {"src-color", BlendFunc::SRC_COLOR},
410 {"constant-color", BlendFunc::CONSTANT_COLOR},
411 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
412 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
413 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
414 {"zero", BlendFunc::ZERO}
416 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
418 struct BlendBuilder : public PassAttributeBuilder
420 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
421 const SGReaderWriterXMLOptions* options)
423 if (!isAttributeActive(effect, prop))
425 // XXX Compatibility with early <blend> syntax; should go away
427 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
430 if (realProp->nChildren() == 0) {
431 pass->setMode(GL_BLEND, (realProp->getBoolValue()
433 : StateAttribute::OFF));
437 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
439 // XXX When dynamic parameters are supported, this code should
440 // create the blend function even if the mode is off.
441 if (pmode && !pmode->getValue<bool>()) {
442 pass->setMode(GL_BLEND, StateAttribute::OFF);
445 const SGPropertyNode* psource
446 = getEffectPropertyChild(effect, prop, "source");
447 const SGPropertyNode* pdestination
448 = getEffectPropertyChild(effect, prop, "destination");
449 const SGPropertyNode* psourceRGB
450 = getEffectPropertyChild(effect, prop, "source-rgb");
451 const SGPropertyNode* psourceAlpha
452 = getEffectPropertyChild(effect, prop, "source-alpha");
453 const SGPropertyNode* pdestRGB
454 = getEffectPropertyChild(effect, prop, "destination-rgb");
455 const SGPropertyNode* pdestAlpha
456 = getEffectPropertyChild(effect, prop, "destination-alpha");
457 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
458 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
460 findAttr(blendFuncModes, psource, sourceMode);
462 findAttr(blendFuncModes, pdestination, destMode);
463 if (psource && pdestination
464 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
465 && sourceMode == BlendFunc::SRC_ALPHA
466 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
467 pass->setAttributeAndModes(StateAttributeFactory::instance()
468 ->getStandardBlendFunc());
471 BlendFunc* blendFunc = new BlendFunc;
473 blendFunc->setSource(sourceMode);
475 blendFunc->setDestination(destMode);
477 BlendFunc::BlendFuncMode sourceRGBMode;
478 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
479 blendFunc->setSourceRGB(sourceRGBMode);
482 BlendFunc::BlendFuncMode destRGBMode;
483 findAttr(blendFuncModes, pdestRGB, destRGBMode);
484 blendFunc->setDestinationRGB(destRGBMode);
487 BlendFunc::BlendFuncMode sourceAlphaMode;
488 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
489 blendFunc->setSourceAlpha(sourceAlphaMode);
492 BlendFunc::BlendFuncMode destAlphaMode;
493 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
494 blendFunc->setDestinationAlpha(destAlphaMode);
496 pass->setAttributeAndModes(blendFunc);
500 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
503 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
505 {"never", Stencil::NEVER },
506 {"less", Stencil::LESS},
507 {"equal", Stencil::EQUAL},
508 {"less-or-equal", Stencil::LEQUAL},
509 {"greater", Stencil::GREATER},
510 {"not-equal", Stencil::NOTEQUAL},
511 {"greater-or-equal", Stencil::GEQUAL},
512 {"always", Stencil::ALWAYS}
515 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
517 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
519 {"keep", Stencil::KEEP},
520 {"zero", Stencil::ZERO},
521 {"replace", Stencil::REPLACE},
522 {"increase", Stencil::INCR},
523 {"decrease", Stencil::DECR},
524 {"invert", Stencil::INVERT},
525 {"increase-wrap", Stencil::INCR_WRAP},
526 {"decrease-wrap", Stencil::DECR_WRAP}
529 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
531 struct StencilBuilder : public PassAttributeBuilder
533 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
534 const SGReaderWriterXMLOptions* options)
536 if (!isAttributeActive(effect, prop))
539 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
541 if (pmode && !pmode->getValue<bool>()) {
542 pass->setMode(GL_STENCIL, StateAttribute::OFF);
545 const SGPropertyNode* pfunction
546 = getEffectPropertyChild(effect, prop, "function");
547 const SGPropertyNode* pvalue
548 = getEffectPropertyChild(effect, prop, "value");
549 const SGPropertyNode* pmask
550 = getEffectPropertyChild(effect, prop, "mask");
551 const SGPropertyNode* psfail
552 = getEffectPropertyChild(effect, prop, "stencil-fail");
553 const SGPropertyNode* pzfail
554 = getEffectPropertyChild(effect, prop, "z-fail");
555 const SGPropertyNode* ppass
556 = getEffectPropertyChild(effect, prop, "pass");
558 Stencil::Function func = Stencil::ALWAYS; // Always pass
560 unsigned int mask = ~0u; // All bits on
561 Stencil::Operation sfailop = Stencil::KEEP; // Keep the old values as default
562 Stencil::Operation zfailop = Stencil::KEEP;
563 Stencil::Operation passop = Stencil::KEEP;
565 ref_ptr<Stencil> stencilFunc = new Stencil;
568 findAttr(stencilFunction, pfunction, func);
570 ref = pvalue->getIntValue();
572 mask = pmask->getIntValue();
575 findAttr(stencilOperation, psfail, sfailop);
577 findAttr(stencilOperation, pzfail, zfailop);
579 findAttr(stencilOperation, ppass, passop);
581 // Set the stencil operation
582 stencilFunc->setFunction(func, ref, mask);
584 // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
585 stencilFunc->setOperation(sfailop, zfailop, passop);
587 // Add the operation to pass
588 pass->setAttributeAndModes(stencilFunc.get());
592 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
595 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
597 {"never", AlphaFunc::NEVER},
598 {"less", AlphaFunc::LESS},
599 {"equal", AlphaFunc::EQUAL},
600 {"lequal", AlphaFunc::LEQUAL},
601 {"greater", AlphaFunc::GREATER},
602 {"notequal", AlphaFunc::NOTEQUAL},
603 {"gequal", AlphaFunc::GEQUAL},
604 {"always", AlphaFunc::ALWAYS}
606 EffectPropertyMap<AlphaFunc::ComparisonFunction>
607 alphaComparison(alphaComparisonInit);
609 struct AlphaTestBuilder : public PassAttributeBuilder
611 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
612 const SGReaderWriterXMLOptions* options)
614 if (!isAttributeActive(effect, prop))
616 // XXX Compatibility with early <alpha-test> syntax; should go away
618 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
621 if (realProp->nChildren() == 0) {
622 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
624 : StateAttribute::OFF));
628 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
630 // XXX When dynamic parameters are supported, this code should
631 // create the blend function even if the mode is off.
632 if (pmode && !pmode->getValue<bool>()) {
633 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
636 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
638 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
640 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
641 float refValue = 1.0f;
643 findAttr(alphaComparison, pComp, func);
645 refValue = pRef->getValue<float>();
646 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
647 pass->setAttributeAndModes(StateAttributeFactory::instance()
648 ->getStandardAlphaFunc());
650 AlphaFunc* alphaFunc = new AlphaFunc;
651 alphaFunc->setFunction(func);
652 alphaFunc->setReferenceValue(refValue);
653 pass->setAttributeAndModes(alphaFunc);
658 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
660 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
662 // Shader key, used both for shaders with relative and absolute names
663 typedef pair<string, Shader::Type> ShaderKey;
667 typedef pair<string, int> AttribKey;
668 osgDB::FilePathList paths;
669 vector<ShaderKey> shaders;
670 vector<AttribKey> attributes;
673 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
675 return (lhs.paths.size() == rhs.paths.size()
676 && equal(lhs.paths.begin(), lhs.paths.end(),
678 && lhs.shaders.size() == rhs.shaders.size()
679 && equal (lhs.shaders.begin(), lhs.shaders.end(),
681 && lhs.attributes.size() == rhs.attributes.size()
682 && equal(lhs.attributes.begin(), lhs.attributes.end(),
683 rhs.attributes.begin()));
688 size_t hash_value(const ProgramKey& key)
691 boost::hash_range(seed, key.paths.begin(), key.paths.end());
692 boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
693 boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
697 // XXX Should these be protected by a mutex? Probably
699 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
700 boost::hash<ProgramKey>, ProgramKey::EqualTo>
702 ProgramMap programMap;
704 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
708 void reload_shaders()
710 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
712 Shader *shader = sitr->second.get();
713 string fileName = osgDB::findDataFile(sitr->first.first);
714 if (!fileName.empty()) {
715 shader->loadShaderSourceFromFile(fileName);
720 struct ShaderProgramBuilder : PassAttributeBuilder
722 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
723 const SGReaderWriterXMLOptions* options);
726 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
727 const SGPropertyNode* prop,
728 const SGReaderWriterXMLOptions*
731 using namespace boost;
732 if (!isAttributeActive(effect, prop))
734 PropertyList pVertShaders = prop->getChildren("vertex-shader");
735 PropertyList pFragShaders = prop->getChildren("fragment-shader");
736 PropertyList pAttributes = prop->getChildren("attribute");
738 for (PropertyList::iterator itr = pVertShaders.begin(),
739 e = pVertShaders.end();
742 prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
744 for (PropertyList::iterator itr = pFragShaders.begin(),
745 e = pFragShaders.end();
748 prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
750 for (PropertyList::iterator itr = pAttributes.begin(),
751 e = pAttributes.end();
754 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
756 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
758 if (!pName || ! pIndex)
759 throw BuilderException("malformed attribute property");
761 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
762 pIndex->getValue<int>()));
765 prgKey.paths = options->getDatabasePathList();
766 Program* program = 0;
767 ProgramMap::iterator pitr = programMap.find(prgKey);
768 if (pitr != programMap.end()) {
769 program = pitr->second.get();
771 program = new Program;
772 // Add vertex shaders, then fragment shaders
773 PropertyList& pvec = pVertShaders;
774 Shader::Type stype = Shader::VERTEX;
775 for (int i = 0; i < 2; ++i) {
776 for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
779 string shaderName = (*nameItr)->getStringValue();
780 string fileName = osgDB::findDataFile(shaderName, options);
781 if (fileName.empty())
782 throw BuilderException(string("couldn't find shader ") +
784 ShaderKey skey(fileName, stype);
785 ShaderMap::iterator sitr = shaderMap.find(skey);
786 if (sitr != shaderMap.end()) {
787 program->addShader(sitr->second.get());
789 ref_ptr<Shader> shader = new Shader(stype);
790 if (shader->loadShaderSourceFromFile(fileName)) {
791 program->addShader(shader.get());
792 shaderMap.insert(ShaderMap::value_type(skey, shader));
797 stype = Shader::FRAGMENT;
799 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
800 program->addBindAttribLocation(key.first, key.second);
802 programMap.insert(ProgramMap::value_type(prgKey, program));
804 pass->setAttributeAndModes(program);
807 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
809 EffectNameValue<Uniform::Type> uniformTypesInit[] =
811 {"float", Uniform::FLOAT},
812 {"float-vec3", Uniform::FLOAT_VEC3},
813 {"float-vec4", Uniform::FLOAT_VEC4},
814 {"sampler-1d", Uniform::SAMPLER_1D},
815 {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
816 {"sampler-2d", Uniform::SAMPLER_2D},
817 {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
818 {"sampler-3d", Uniform::SAMPLER_3D},
819 {"sampler-cube", Uniform::SAMPLER_CUBE}
821 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
823 struct UniformBuilder :public PassAttributeBuilder
825 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
826 const SGReaderWriterXMLOptions* options)
828 if (!isAttributeActive(effect, prop))
830 const SGPropertyNode* nameProp = prop->getChild("name");
831 const SGPropertyNode* typeProp = prop->getChild("type");
832 const SGPropertyNode* valProp = prop->getChild("value");
834 Uniform::Type uniformType = Uniform::FLOAT;
836 name = nameProp->getStringValue();
838 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
842 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
847 props::Type propType = valProp->getType();
851 break; // default float type;
853 uniformType = Uniform::FLOAT_VEC3;
856 uniformType = Uniform::FLOAT_VEC4;
859 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
864 findAttr(uniformTypes, typeProp, uniformType);
866 ref_ptr<Uniform> uniform = new Uniform;
867 uniform->setName(name);
868 uniform->setType(uniformType);
869 switch (uniformType) {
871 initFromParameters(effect, valProp, uniform.get(),
872 static_cast<bool (Uniform::*)(float)>(&Uniform::set),
875 case Uniform::FLOAT_VEC3:
876 initFromParameters(effect, valProp, uniform.get(),
877 static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
880 case Uniform::FLOAT_VEC4:
881 initFromParameters(effect, valProp, uniform.get(),
882 static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
885 case Uniform::SAMPLER_1D:
886 case Uniform::SAMPLER_2D:
887 case Uniform::SAMPLER_3D:
888 case Uniform::SAMPLER_1D_SHADOW:
889 case Uniform::SAMPLER_2D_SHADOW:
890 case Uniform::SAMPLER_CUBE:
891 initFromParameters(effect, valProp, uniform.get(),
892 static_cast<bool (Uniform::*)(int)>(&Uniform::set),
895 default: // avoid compiler warning
898 pass->addUniform(uniform.get());
902 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
904 // Not sure what to do with "name". At one point I wanted to use it to
905 // order the passes, but I do support render bin and stuff too...
907 struct NameBuilder : public PassAttributeBuilder
909 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
910 const SGReaderWriterXMLOptions* options)
912 // name can't use <use>
913 string name = prop->getStringValue();
919 InstallAttributeBuilder<NameBuilder> installName("name");
921 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
923 {"fill", PolygonMode::FILL},
924 {"line", PolygonMode::LINE},
925 {"point", PolygonMode::POINT}
927 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
929 struct PolygonModeBuilder : public PassAttributeBuilder
931 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
932 const SGReaderWriterXMLOptions* options)
934 if (!isAttributeActive(effect, prop))
936 const SGPropertyNode* frontProp
937 = getEffectPropertyChild(effect, prop, "front");
938 const SGPropertyNode* backProp
939 = getEffectPropertyChild(effect, prop, "back");
940 ref_ptr<PolygonMode> pmode = new PolygonMode;
941 PolygonMode::Mode frontMode = PolygonMode::FILL;
942 PolygonMode::Mode backMode = PolygonMode::FILL;
944 findAttr(polygonModeModes, frontProp, frontMode);
945 pmode->setMode(PolygonMode::FRONT, frontMode);
948 findAttr(polygonModeModes, backProp, backMode);
949 pmode->setMode(PolygonMode::BACK, backMode);
951 pass->setAttribute(pmode.get());
955 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
957 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
959 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
960 const SGReaderWriterXMLOptions* options)
962 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
965 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
966 (realProp->getValue<bool>()
967 ? StateAttribute::ON : StateAttribute::OFF));
971 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
972 installTwoSide("vertex-program-two-side");
974 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
976 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
977 const SGReaderWriterXMLOptions* options)
979 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
982 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
983 (realProp->getValue<bool>()
984 ? StateAttribute::ON : StateAttribute::OFF));
988 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
989 installPointSize("vertex-program-point-size");
991 EffectNameValue<Depth::Function> depthFunctionInit[] =
993 {"never", Depth::NEVER},
994 {"less", Depth::LESS},
995 {"equal", Depth::EQUAL},
996 {"lequal", Depth::LEQUAL},
997 {"greater", Depth::GREATER},
998 {"notequal", Depth::NOTEQUAL},
999 {"gequal", Depth::GEQUAL},
1000 {"always", Depth::ALWAYS}
1002 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1004 struct DepthBuilder : public PassAttributeBuilder
1006 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1007 const SGReaderWriterXMLOptions* options)
1009 if (!isAttributeActive(effect, prop))
1011 ref_ptr<Depth> depth = new Depth;
1012 const SGPropertyNode* pfunc
1013 = getEffectPropertyChild(effect, prop, "function");
1015 Depth::Function func = Depth::LESS;
1016 findAttr(depthFunction, pfunc, func);
1017 depth->setFunction(func);
1019 const SGPropertyNode* pnear
1020 = getEffectPropertyChild(effect, prop, "near");
1022 depth->setZNear(pnear->getValue<double>());
1023 const SGPropertyNode* pfar
1024 = getEffectPropertyChild(effect, prop, "far");
1026 depth->setZFar(pnear->getValue<double>());
1027 const SGPropertyNode* pmask
1028 = getEffectPropertyChild(effect, prop, "write-mask");
1030 depth->setWriteMask(pmask->getValue<bool>());
1031 pass->setAttribute(depth.get());
1035 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1037 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1038 const SGReaderWriterXMLOptions* options)
1040 Technique* tniq = new Technique;
1041 effect->techniques.push_back(tniq);
1042 const SGPropertyNode* predProp = prop->getChild("predicate");
1044 tniq->setAlwaysValid(true);
1047 TechniquePredParser parser;
1048 parser.setTechnique(tniq);
1049 expression::BindingLayout& layout = parser.getBindingLayout();
1050 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1051 SGExpressionb* validExp
1052 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1055 tniq->setValidExpression(validExp, layout);
1057 throw expression::ParseError("technique predicate is not a boolean expression");
1059 catch (expression::ParseError& except)
1061 SG_LOG(SG_INPUT, SG_ALERT,
1062 "parsing technique predicate " << except.getMessage());
1063 tniq->setAlwaysValid(false);
1066 PropertyList passProps = prop->getChildren("pass");
1067 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1070 buildPass(effect, tniq, itr->ptr(), options);
1074 // Specifically for .ac files...
1075 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1077 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1078 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1079 Vec4f ambVal, difVal, specVal, emisVal;
1080 float shininess = 0.0f;
1081 const Material* mat = getStateAttribute<Material>(ss);
1083 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1084 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1085 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1086 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1087 shininess = mat->getShininess(Material::FRONT_AND_BACK);
1088 makeChild(matNode, "active")->setValue(true);
1089 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1090 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1091 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1092 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1093 makeChild(matNode, "shininess")->setValue(shininess);
1094 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1096 makeChild(matNode, "active")->setValue(false);
1098 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1099 string shadeModelString("smooth");
1101 ShadeModel::Mode smMode = sm->getMode();
1102 if (smMode == ShadeModel::FLAT)
1103 shadeModelString = "flat";
1105 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1106 string cullFaceString("off");
1107 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1109 switch (cullFace->getMode()) {
1110 case CullFace::FRONT:
1111 cullFaceString = "front";
1113 case CullFace::BACK:
1114 cullFaceString = "back";
1116 case CullFace::FRONT_AND_BACK:
1117 cullFaceString = "front-back";
1123 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1124 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1125 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1127 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1128 string destMode = findName(blendFuncModes, blendFunc->getDestination());
1129 makeChild(blendNode, "active")->setValue(true);
1130 makeChild(blendNode, "source")->setStringValue(sourceMode);
1131 makeChild(blendNode, "destination")->setStringValue(destMode);
1132 makeChild(blendNode, "mode")->setValue(true);
1134 makeChild(blendNode, "active")->setValue(false);
1136 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1137 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1138 makeTextureParameters(paramRoot, ss);
1142 // Walk the techniques property tree, building techniques and
1144 bool Effect::realizeTechniques(const SGReaderWriterXMLOptions* options)
1148 PropertyList tniqList = root->getChildren("technique");
1149 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1152 buildTechnique(this, *itr, options);
1157 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1159 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1162 Effect* effect = eg->getEffect();
1165 SGPropertyNode* root = getPropertyRoot();
1166 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1167 end = effect->_extraData.end();
1170 InitializeWhenAdded* adder
1171 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1173 adder->initOnAdd(effect, root);
1177 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1178 const Effect::Key& rhs) const
1180 if (lhs.paths.size() != rhs.paths.size()
1181 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1183 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1184 return props::Compare()(lhs.unmerged, rhs.unmerged);
1186 return lhs.unmerged == rhs.unmerged;
1189 size_t hash_value(const Effect::Key& key)
1192 if (key.unmerged.valid())
1193 boost::hash_combine(seed, *key.unmerged);
1194 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1198 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1200 const Effect& effect = static_cast<const Effect&>(obj);
1202 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1203 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1204 fw.writeObject(*technique);
1211 osgDB::RegisterDotOsgWrapperProxy effectProxy
1215 "Object simgear::Effect",
1217 &Effect_writeLocalData
1221 // Property expressions for technique predicates
1222 class PropertyExpression : public SGExpression<bool>
1225 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1227 void eval(bool& value, const expression::Binding*) const
1229 value = _pnode->getValue<bool>();
1232 SGPropertyNode_ptr _pnode;
1235 class EffectPropertyListener : public SGPropertyChangeListener
1238 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1240 void valueChanged(SGPropertyNode* node)
1242 _tniq->refreshValidity();
1245 osg::ref_ptr<Technique> _tniq;
1248 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1249 expression::Parser* parser)
1251 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1253 PropertyExpression* pexp = new PropertyExpression(pnode);
1254 TechniquePredParser* predParser
1255 = dynamic_cast<TechniquePredParser*>(parser);
1257 pnode->addChangeListener(new EffectPropertyListener(predParser
1262 expression::ExpParserRegistrar propertyRegistrar("property",
1263 propertyExpressionParser);