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 "Technique.hxx"
25 #include "TextureBuilder.hxx"
33 #include <boost/bind.hpp>
34 #include <boost/foreach.hpp>
35 #include <boost/lexical_cast.hpp>
36 #include <boost/tuple/tuple.hpp>
37 #include <boost/tuple/tuple_comparison.hpp>
39 #include <osg/AlphaFunc>
40 #include <osg/BlendFunc>
41 #include <osg/CullFace>
42 #include <osg/Drawable>
43 #include <osg/Material>
45 #include <osg/PolygonMode>
46 #include <osg/Program>
47 #include <osg/Referenced>
48 #include <osg/RenderInfo>
49 #include <osg/ShadeModel>
50 #include <osg/StateSet>
52 #include <osg/Texture1D>
53 #include <osg/Texture2D>
54 #include <osg/Texture3D>
55 #include <osg/TextureRectangle>
56 #include <osg/Uniform>
58 #include <osgUtil/CullVisitor>
59 #include <osgDB/FileUtils>
60 #include <osgDB/Input>
61 #include <osgDB/ParameterOutput>
62 #include <osgDB/ReadFile>
63 #include <osgDB/Registry>
65 #include <simgear/scene/tgdb/userdata.hxx>
66 #include <simgear/scene/util/SGSceneFeatures.hxx>
67 #include <simgear/scene/util/StateAttributeFactory.hxx>
68 #include <simgear/structure/OSGUtils.hxx>
69 #include <simgear/structure/SGExpression.hxx>
77 using namespace osgUtil;
79 using namespace effect;
85 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
86 : root(rhs.root), parametersProp(rhs.parametersProp)
88 using namespace boost;
89 transform(rhs.techniques.begin(), rhs.techniques.end(),
90 back_inserter(techniques),
91 bind(simgear::clone_ref<Technique>, _1, copyop));
94 // Assume that the last technique is always valid.
95 StateSet* Effect::getDefaultStateSet()
97 Technique* tniq = techniques.back().get();
100 Pass* pass = tniq->passes.front().get();
104 // There should always be a valid technique in an effect.
106 Technique* Effect::chooseTechnique(RenderInfo* info)
108 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
110 if (technique->valid(info) == Technique::VALID)
111 return technique.get();
116 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
118 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
120 technique->resizeGLObjectBuffers(maxSize);
124 void Effect::releaseGLObjects(osg::State* state) const
126 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
128 technique->releaseGLObjects(state);
136 class PassAttributeBuilder : public Referenced
139 virtual void buildAttribute(Effect* effect, Pass* pass,
140 const SGPropertyNode* prop,
141 const osgDB::ReaderWriter::Options* options)
145 typedef map<const string, ref_ptr<PassAttributeBuilder> > PassAttrMap;
146 PassAttrMap passAttrMap;
149 struct InstallAttributeBuilder
151 InstallAttributeBuilder(const string& name)
153 passAttrMap.insert(make_pair(name, new T));
157 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
158 const osgDB::ReaderWriter::Options* options)
160 Pass* pass = new Pass;
161 tniq->passes.push_back(pass);
162 for (int i = 0; i < prop->nChildren(); ++i) {
163 const SGPropertyNode* attrProp = prop->getChild(i);
164 PassAttrMap::iterator itr = passAttrMap.find(attrProp->getName());
165 if (itr != passAttrMap.end())
166 itr->second->buildAttribute(effect, pass, attrProp, options);
168 SG_LOG(SG_INPUT, SG_ALERT,
169 "skipping unknown pass attribute " << attrProp->getName());
173 osg::Vec4f getColor(const SGPropertyNode* prop)
175 if (prop->nChildren() == 0) {
176 if (prop->getType() == props::VEC4D) {
177 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
178 } else if (prop->getType() == props::VEC3D) {
179 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
181 SG_LOG(SG_INPUT, SG_ALERT,
182 "invalid color property " << prop->getName() << " "
183 << prop->getStringValue());
184 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
188 static const char* colors[] = {"r", "g", "b"};
189 for (int i = 0; i < 3; ++i) {
190 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
191 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
193 const SGPropertyNode* alphaProp = prop->getChild("a");
194 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
199 struct LightingBuilder : public PassAttributeBuilder
201 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
202 const osgDB::ReaderWriter::Options* options);
205 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
206 const SGPropertyNode* prop,
207 const osgDB::ReaderWriter::Options* options)
209 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
212 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
213 : StateAttribute::OFF));
216 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
218 struct ShadeModelBuilder : public PassAttributeBuilder
220 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
221 const osgDB::ReaderWriter::Options* options)
223 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
226 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
227 string propVal = realProp->getStringValue();
228 if (propVal == "flat")
229 pass->setAttribute(attrFact->getFlatShadeModel());
230 else if (propVal == "smooth")
231 pass->setAttribute(attrFact->getSmoothShadeModel());
233 SG_LOG(SG_INPUT, SG_ALERT,
234 "invalid shade model property " << propVal);
238 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
240 struct CullFaceBuilder : PassAttributeBuilder
242 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
243 const osgDB::ReaderWriter::Options* options)
245 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
247 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
250 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
251 string propVal = realProp->getStringValue();
252 if (propVal == "front")
253 pass->setAttributeAndModes(attrFact->getCullFaceFront());
254 else if (propVal == "back")
255 pass->setAttributeAndModes(attrFact->getCullFaceBack());
256 else if (propVal == "front-back")
257 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
258 else if (propVal == "off")
259 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
261 SG_LOG(SG_INPUT, SG_ALERT,
262 "invalid cull face property " << propVal);
266 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
268 struct HintBuilder : public PassAttributeBuilder
270 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
271 const osgDB::ReaderWriter::Options* options)
273 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
276 string propVal = realProp->getStringValue();
277 if (propVal == "opaque")
278 pass->setRenderingHint(StateSet::OPAQUE_BIN);
279 else if (propVal == "transparent")
280 pass->setRenderingHint(StateSet::TRANSPARENT_BIN);
284 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
286 struct RenderBinBuilder : public PassAttributeBuilder
288 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
289 const osgDB::ReaderWriter::Options* options)
291 const SGPropertyNode* binProp = prop->getChild("bin-number");
292 binProp = getEffectPropertyNode(effect, binProp);
293 const SGPropertyNode* nameProp = prop->getChild("bin-name");
294 nameProp = getEffectPropertyNode(effect, nameProp);
295 if (binProp && nameProp) {
296 pass->setRenderBinDetails(binProp->getIntValue(),
297 nameProp->getStringValue());
300 SG_LOG(SG_INPUT, SG_ALERT,
301 "No render bin number specified in render bin section");
303 SG_LOG(SG_INPUT, SG_ALERT,
304 "No render bin name specified in render bin section");
309 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
311 struct MaterialBuilder : public PassAttributeBuilder
313 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
314 const osgDB::ReaderWriter::Options* options);
317 EffectNameValue<Material::ColorMode> colorModeInit[] =
319 { "ambient", Material::AMBIENT },
320 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
321 { "diffuse", Material::DIFFUSE },
322 { "emissive", Material::EMISSION },
323 { "specular", Material::SPECULAR },
324 { "off", Material::OFF }
326 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
328 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
329 const SGPropertyNode* prop,
330 const osgDB::ReaderWriter::Options* options)
332 Material* mat = new Material;
333 const SGPropertyNode* color = 0;
334 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
335 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
336 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
337 mat->setAmbient(Material::FRONT, getColor(color));
338 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
339 mat->setAmbient(Material::BACK, getColor(color));
340 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
341 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
342 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
343 mat->setDiffuse(Material::FRONT, getColor(color));
344 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
345 mat->setDiffuse(Material::BACK, getColor(color));
346 if ((color = getEffectPropertyChild(effect, prop, "specular")))
347 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
348 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
349 mat->setSpecular(Material::FRONT, getColor(color));
350 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
351 mat->setSpecular(Material::BACK, getColor(color));
352 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
353 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
354 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
355 mat->setEmission(Material::FRONT, getColor(color));
356 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
357 mat->setEmission(Material::BACK, getColor(color));
358 const SGPropertyNode* shininess = 0;
359 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
360 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
361 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
362 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
363 mat->setShininess(Material::FRONT, shininess->getFloatValue());
364 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
365 mat->setShininess(Material::BACK, shininess->getFloatValue());
366 Material::ColorMode colorMode = Material::OFF;
367 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
369 mat->setColorMode(colorMode);
370 pass->setAttribute(mat);
373 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
375 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
377 {"dst-alpha", BlendFunc::DST_ALPHA},
378 {"dst-color", BlendFunc::DST_COLOR},
379 {"one", BlendFunc::ONE},
380 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
381 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
382 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
383 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
384 {"src-alpha", BlendFunc::SRC_ALPHA},
385 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
386 {"src-color", BlendFunc::SRC_COLOR},
387 {"constant-color", BlendFunc::CONSTANT_COLOR},
388 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
389 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
390 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
391 {"zero", BlendFunc::ZERO}
393 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
395 struct BlendBuilder : public PassAttributeBuilder
397 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
398 const osgDB::ReaderWriter::Options* options)
400 // XXX Compatibility with early <blend> syntax; should go away
402 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
405 if (realProp->nChildren() == 0) {
406 pass->setMode(GL_BLEND, (realProp->getBoolValue()
408 : StateAttribute::OFF));
412 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
414 // XXX When dynamic parameters are supported, this code should
415 // create the blend function even if the mode is off.
416 if (pmode && !pmode->getValue<bool>()) {
417 pass->setMode(GL_BLEND, StateAttribute::OFF);
420 const SGPropertyNode* psource = getEffectPropertyChild(effect, prop,
422 const SGPropertyNode* pdestination
423 = getEffectPropertyChild(effect, prop, "destination");
424 const SGPropertyNode* psourceRGB
425 = getEffectPropertyChild(effect, prop, "source-rgb");
426 const SGPropertyNode* psourceAlpha
427 = getEffectPropertyChild(effect, prop, "source-alpha");
428 const SGPropertyNode* pdestRGB
429 = getEffectPropertyChild(effect, prop, "destination-rgb");
430 const SGPropertyNode* pdestAlpha
431 = getEffectPropertyChild(effect, prop, "destination-alpha");
432 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
433 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
435 findAttr(blendFuncModes, psource, sourceMode);
437 findAttr(blendFuncModes, pdestination, destMode);
438 if (psource && pdestination
439 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
440 && sourceMode == BlendFunc::SRC_ALPHA
441 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
442 pass->setAttributeAndModes(StateAttributeFactory::instance()
443 ->getStandardBlendFunc());
446 BlendFunc* blendFunc = new BlendFunc;
448 blendFunc->setSource(sourceMode);
450 blendFunc->setDestination(destMode);
452 BlendFunc::BlendFuncMode sourceRGBMode;
453 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
454 blendFunc->setSourceRGB(sourceRGBMode);
457 BlendFunc::BlendFuncMode destRGBMode;
458 findAttr(blendFuncModes, pdestRGB, destRGBMode);
459 blendFunc->setDestinationRGB(destRGBMode);
462 BlendFunc::BlendFuncMode sourceAlphaMode;
463 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
464 blendFunc->setSourceAlpha(sourceAlphaMode);
467 BlendFunc::BlendFuncMode destAlphaMode;
468 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
469 blendFunc->setDestinationAlpha(destAlphaMode);
471 pass->setAttributeAndModes(blendFunc);
475 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
477 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
479 {"never", AlphaFunc::NEVER},
480 {"less", AlphaFunc::LESS},
481 {"equal", AlphaFunc::EQUAL},
482 {"lequal", AlphaFunc::LEQUAL},
483 {"greater", AlphaFunc::GREATER},
484 {"notequal", AlphaFunc::NOTEQUAL},
485 {"gequal", AlphaFunc::GEQUAL},
486 {"always", AlphaFunc::ALWAYS}
488 EffectPropertyMap<AlphaFunc::ComparisonFunction>
489 alphaComparison(alphaComparisonInit);
491 struct AlphaTestBuilder : public PassAttributeBuilder
493 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
494 const osgDB::ReaderWriter::Options* options)
496 // XXX Compatibility with early <alpha-test> syntax; should go away
498 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
501 if (realProp->nChildren() == 0) {
502 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
504 : StateAttribute::OFF));
508 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
510 // XXX When dynamic parameters are supported, this code should
511 // create the blend function even if the mode is off.
512 if (pmode && !pmode->getValue<bool>()) {
513 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
516 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
518 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
520 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
521 float refValue = 1.0f;
523 findAttr(alphaComparison, pComp, func);
525 refValue = pRef->getValue<float>();
526 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
527 pass->setAttributeAndModes(StateAttributeFactory::instance()
528 ->getStandardAlphaFunc());
530 AlphaFunc* alphaFunc = new AlphaFunc;
531 alphaFunc->setFunction(func);
532 alphaFunc->setReferenceValue(refValue);
533 pass->setAttributeAndModes(alphaFunc);
538 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
540 EffectNameValue<TexEnv::Mode> texEnvModesInit[] =
542 {"add", TexEnv::ADD},
543 {"blend", TexEnv::BLEND},
544 {"decal", TexEnv::DECAL},
545 {"modulate", TexEnv::MODULATE},
546 {"replace", TexEnv::REPLACE}
548 EffectPropertyMap<TexEnv::Mode> texEnvModes(texEnvModesInit);
550 TexEnv* buildTexEnv(Effect* effect, const SGPropertyNode* prop)
552 const SGPropertyNode* modeProp = getEffectPropertyChild(effect, prop,
554 const SGPropertyNode* colorProp = getEffectPropertyChild(effect, prop,
558 TexEnv::Mode mode = TexEnv::MODULATE;
559 findAttr(texEnvModes, modeProp, mode);
560 if (mode == TexEnv::MODULATE) {
561 return StateAttributeFactory::instance()->getStandardTexEnv();
563 TexEnv* env = new TexEnv(mode);
565 env->setColor(toOsg(colorProp->getValue<SGVec4d>()));
570 struct TextureUnitBuilder : PassAttributeBuilder
572 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
573 const osgDB::ReaderWriter::Options* options);
576 void TextureUnitBuilder::buildAttribute(Effect* effect, Pass* pass,
577 const SGPropertyNode* prop,
578 const osgDB::ReaderWriter::Options* options)
581 // Decode the texture unit
583 const SGPropertyNode* pUnit = prop->getChild("unit");
585 unit = pUnit->getValue<int>();
587 const SGPropertyNode* pName = prop->getChild("name");
590 unit = boost::lexical_cast<int>(pName->getStringValue());
591 } catch (boost::bad_lexical_cast& lex) {
592 SG_LOG(SG_INPUT, SG_ALERT, "can't decode name as texture unit "
596 const SGPropertyNode* pType = prop->getChild("type");
601 type = pType->getStringValue();
602 Texture* texture = 0;
604 texture = TextureBuilder::buildFromType(effect, type, prop,
607 catch (BuilderException& e) {
608 SG_LOG(SG_INPUT, SG_ALERT, "No image file for texture, using white ");
609 texture = StateAttributeFactory::instance()->getWhiteTexture();
611 pass->setTextureAttributeAndModes(unit, texture);
612 const SGPropertyNode* envProp = prop->getChild("environment");
614 TexEnv* env = buildTexEnv(effect, envProp);
616 pass->setTextureAttributeAndModes(unit, env);
622 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
624 typedef map<string, ref_ptr<Program> > ProgramMap;
625 ProgramMap programMap;
627 typedef map<string, ref_ptr<Shader> > ShaderMap;
630 void reload_shaders()
632 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
634 Shader *shader = sitr->second.get();
635 string fileName = osgDB::findDataFile(sitr->first);
636 if (!fileName.empty()) {
637 shader->loadShaderSourceFromFile(fileName);
642 struct ShaderProgramBuilder : PassAttributeBuilder
644 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
645 const osgDB::ReaderWriter::Options* options);
648 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
649 const SGPropertyNode* prop,
650 const osgDB::ReaderWriter::Options*
653 PropertyList pVertShaders = prop->getChildren("vertex-shader");
654 PropertyList pFragShaders = prop->getChildren("fragment-shader");
656 for (PropertyList::iterator itr = pVertShaders.begin(),
657 e = pVertShaders.end();
661 programKey += (*itr)->getStringValue();
664 for (PropertyList::iterator itr = pFragShaders.begin(),
665 e = pFragShaders.end();
669 programKey += (*itr)->getStringValue();
672 Program* program = 0;
673 ProgramMap::iterator pitr = programMap.find(programKey);
674 if (pitr != programMap.end()) {
675 program = pitr->second.get();
677 program = new Program;
678 program->setName(programKey);
679 // Add vertex shaders, then fragment shaders
680 PropertyList& pvec = pVertShaders;
681 Shader::Type stype = Shader::VERTEX;
682 for (int i = 0; i < 2; ++i) {
683 for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
686 string shaderName = (*nameItr)->getStringValue();
687 ShaderMap::iterator sitr = shaderMap.find(shaderName);
688 if (sitr != shaderMap.end()) {
689 program->addShader(sitr->second.get());
691 string fileName = osgDB::findDataFile(shaderName, options);
692 if (!fileName.empty()) {
693 ref_ptr<Shader> shader = new Shader(stype);
694 if (shader->loadShaderSourceFromFile(fileName)) {
695 program->addShader(shader.get());
696 shaderMap.insert(make_pair(shaderName, shader));
702 stype = Shader::FRAGMENT;
704 programMap.insert(make_pair(programKey, program));
706 pass->setAttributeAndModes(program);
709 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
711 EffectNameValue<Uniform::Type> uniformTypesInit[] =
713 {"float", Uniform::FLOAT},
714 {"float-vec3", Uniform::FLOAT_VEC3},
715 {"float-vec4", Uniform::FLOAT_VEC4},
716 {"sampler-1d", Uniform::SAMPLER_1D},
717 {"sampler-2d", Uniform::SAMPLER_2D},
718 {"sampler-3d", Uniform::SAMPLER_3D}
720 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
722 struct UniformBuilder :public PassAttributeBuilder
724 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
725 const osgDB::ReaderWriter::Options* options)
727 const SGPropertyNode* nameProp = prop->getChild("name");
728 const SGPropertyNode* typeProp = prop->getChild("type");
729 const SGPropertyNode* valProp
730 = getEffectPropertyChild(effect, prop, "value");
732 Uniform::Type uniformType = Uniform::FLOAT;
734 name = nameProp->getStringValue();
736 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
740 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
745 props::Type propType = valProp->getType();
749 break; // default float type;
751 uniformType = Uniform::FLOAT_VEC3;
754 uniformType = Uniform::FLOAT_VEC4;
757 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
762 findAttr(uniformTypes, typeProp, uniformType);
764 ref_ptr<Uniform> uniform = new Uniform;
765 uniform->setName(name);
766 uniform->setType(uniformType);
767 switch (uniformType) {
769 uniform->set(valProp->getValue<float>());
771 case Uniform::FLOAT_VEC3:
772 uniform->set(toOsg(valProp->getValue<SGVec3d>()));
774 case Uniform::FLOAT_VEC4:
775 uniform->set(toOsg(valProp->getValue<SGVec4d>()));
777 case Uniform::SAMPLER_1D:
778 case Uniform::SAMPLER_2D:
779 case Uniform::SAMPLER_3D:
780 uniform->set(valProp->getValue<int>());
782 default: // avoid compiler warning
785 pass->addUniform(uniform.get());
789 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
791 // Not sure what to do with "name". At one point I wanted to use it to
792 // order the passes, but I do support render bin and stuff too...
794 struct NameBuilder : public PassAttributeBuilder
796 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
797 const osgDB::ReaderWriter::Options* options)
799 // name can't use <use>
800 string name = prop->getStringValue();
806 InstallAttributeBuilder<NameBuilder> installName("name");
808 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
810 {"fill", PolygonMode::FILL},
811 {"line", PolygonMode::LINE},
812 {"point", PolygonMode::POINT}
814 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
816 struct PolygonModeBuilder : public PassAttributeBuilder
818 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
819 const osgDB::ReaderWriter::Options* options)
821 const SGPropertyNode* frontProp
822 = getEffectPropertyChild(effect, prop, "front");
823 const SGPropertyNode* backProp
824 = getEffectPropertyChild(effect, prop, "back");
825 ref_ptr<PolygonMode> pmode = new PolygonMode;
826 PolygonMode::Mode frontMode = PolygonMode::FILL;
827 PolygonMode::Mode backMode = PolygonMode::FILL;
829 findAttr(polygonModeModes, frontProp, frontMode);
830 pmode->setMode(PolygonMode::FRONT, frontMode);
833 findAttr(polygonModeModes, backProp, backMode);
834 pmode->setMode(PolygonMode::BACK, backMode);
836 pass->setAttribute(pmode.get());
840 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
841 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
842 const osgDB::ReaderWriter::Options* options)
844 Technique* tniq = new Technique;
845 effect->techniques.push_back(tniq);
846 const SGPropertyNode* predProp = prop->getChild("predicate");
848 tniq->setAlwaysValid(true);
851 TechniquePredParser parser;
852 parser.setTechnique(tniq);
853 expression::BindingLayout& layout = parser.getBindingLayout();
854 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
855 SGExpressionb* validExp
856 = dynamic_cast<SGExpressionb*>(parser.read(predProp
859 tniq->setValidExpression(validExp, layout);
861 throw expression::ParseError("technique predicate is not a boolean expression");
863 catch (expression::ParseError& except)
865 SG_LOG(SG_INPUT, SG_ALERT,
866 "parsing technique predicate " << except.getMessage());
867 tniq->setAlwaysValid(false);
870 PropertyList passProps = prop->getChildren("pass");
871 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
874 buildPass(effect, tniq, itr->ptr(), options);
878 // Specifically for .ac files...
879 bool makeParametersFromStateSet(SGPropertyNode* paramRoot, const StateSet* ss)
881 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
882 Vec4f ambVal, difVal, specVal, emisVal;
883 float shininess = 0.0f;
884 const Material* mat = getStateAttribute<Material>(ss);
886 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
887 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
888 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
889 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
890 shininess = mat->getShininess(Material::FRONT_AND_BACK);
892 matNode->getChild("ambient", 0, true)->setValue(toVec4d(toSG(ambVal)));
893 matNode->getChild("diffuse", 0, true)->setValue(toVec4d(toSG(difVal)));
894 matNode->getChild("specular", 0, true)->setValue(toVec4d(toSG(specVal)));
895 matNode->getChild("emissive", 0, true)->setValue(toVec4d(toSG(emisVal)));
896 matNode->getChild("shininess", 0, true)->setValue(shininess);
897 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
898 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
899 string shadeModelString("smooth");
901 ShadeModel::Mode smMode = sm->getMode();
902 if (smMode == ShadeModel::FLAT)
903 shadeModelString = "flat";
905 paramRoot->getChild("shade-model", 0, true)
906 ->setStringValue(shadeModelString);
907 string cullFaceString("off");
908 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
910 switch (cullFace->getMode()) {
911 case CullFace::FRONT:
912 cullFaceString = "front";
915 cullFaceString = "back";
917 case CullFace::FRONT_AND_BACK:
918 cullFaceString = "front-back";
924 paramRoot->getChild("cull-face", 0, true)->setStringValue(cullFaceString);
925 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
927 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
928 string destMode = findName(blendFuncModes, blendFunc->getDestination());
929 SGPropertyNode* blendNode = paramRoot->getChild("blend", 0, true);
930 blendNode->getChild("source", 0, true)->setStringValue(sourceMode);
931 blendNode->getChild("destination", 0, true)->setStringValue(destMode);
932 blendNode->getChild("mode", 0, true)->setValue(true);
934 makeTextureParameters(paramRoot, ss);
938 // Walk the techniques property tree, building techniques and
940 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
942 PropertyList tniqList = root->getChildren("technique");
943 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
946 buildTechnique(this, *itr, options);
950 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
952 const Effect& effect = static_cast<const Effect&>(obj);
954 fw.indent() << "techniques " << effect.techniques.size() << "\n";
955 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
956 fw.writeObject(*technique);
963 osgDB::RegisterDotOsgWrapperProxy effectProxy
967 "Object simgear::Effect",
969 &Effect_writeLocalData
973 // Property expressions for technique predicates
974 class PropertyExpression : public SGExpression<bool>
977 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
979 void eval(bool& value, const expression::Binding*) const
981 value = _pnode->getValue<bool>();
984 SGPropertyNode_ptr _pnode;
987 class EffectPropertyListener : public SGPropertyChangeListener
990 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
992 void valueChanged(SGPropertyNode* node)
994 _tniq->refreshValidity();
997 osg::ref_ptr<Technique> _tniq;
1000 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1001 expression::Parser* parser)
1003 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1005 PropertyExpression* pexp = new PropertyExpression(pnode);
1006 TechniquePredParser* predParser
1007 = dynamic_cast<TechniquePredParser*>(parser);
1009 pnode->addChangeListener(new EffectPropertyListener(predParser
1014 expression::ExpParserRegistrar propertyRegistrar("property",
1015 propertyExpressionParser);