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"
34 #include <boost/foreach.hpp>
35 #include <boost/tuple/tuple.hpp>
36 #include <boost/tuple/tuple_comparison.hpp>
38 #include <osg/AlphaFunc>
39 #include <osg/BlendFunc>
40 #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;
82 : _cache(0), _isRealized(false)
86 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
87 : root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
88 _isRealized(rhs._isRealized)
90 typedef vector<ref_ptr<Technique> > TechniqueList;
91 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
92 end = rhs.techniques.end();
95 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
98 // Assume that the last technique is always valid.
99 StateSet* Effect::getDefaultStateSet()
101 Technique* tniq = techniques.back().get();
104 Pass* pass = tniq->passes.front().get();
108 // There should always be a valid technique in an effect.
110 Technique* Effect::chooseTechnique(RenderInfo* info)
112 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
114 if (technique->valid(info) == Technique::VALID)
115 return technique.get();
120 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
122 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
124 technique->resizeGLObjectBuffers(maxSize);
128 void Effect::releaseGLObjects(osg::State* state) const
130 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
132 technique->releaseGLObjects(state);
141 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
142 const osgDB::ReaderWriter::Options* options)
144 Pass* pass = new Pass;
145 tniq->passes.push_back(pass);
146 for (int i = 0; i < prop->nChildren(); ++i) {
147 const SGPropertyNode* attrProp = prop->getChild(i);
148 PassAttributeBuilder* builder
149 = PassAttributeBuilder::find(attrProp->getNameString());
151 builder->buildAttribute(effect, pass, attrProp, options);
153 SG_LOG(SG_INPUT, SG_ALERT,
154 "skipping unknown pass attribute " << attrProp->getName());
158 osg::Vec4f getColor(const SGPropertyNode* prop)
160 if (prop->nChildren() == 0) {
161 if (prop->getType() == props::VEC4D) {
162 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
163 } else if (prop->getType() == props::VEC3D) {
164 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
166 SG_LOG(SG_INPUT, SG_ALERT,
167 "invalid color property " << prop->getName() << " "
168 << prop->getStringValue());
169 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
173 static const char* colors[] = {"r", "g", "b"};
174 for (int i = 0; i < 3; ++i) {
175 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
176 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
178 const SGPropertyNode* alphaProp = prop->getChild("a");
179 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
184 struct LightingBuilder : public PassAttributeBuilder
186 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
187 const osgDB::ReaderWriter::Options* options);
190 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
191 const SGPropertyNode* prop,
192 const osgDB::ReaderWriter::Options* options)
194 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
197 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
198 : StateAttribute::OFF));
201 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
203 struct ShadeModelBuilder : public PassAttributeBuilder
205 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
206 const osgDB::ReaderWriter::Options* options)
208 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
211 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
212 string propVal = realProp->getStringValue();
213 if (propVal == "flat")
214 pass->setAttribute(attrFact->getFlatShadeModel());
215 else if (propVal == "smooth")
216 pass->setAttribute(attrFact->getSmoothShadeModel());
218 SG_LOG(SG_INPUT, SG_ALERT,
219 "invalid shade model property " << propVal);
223 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
225 struct CullFaceBuilder : PassAttributeBuilder
227 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
228 const osgDB::ReaderWriter::Options* options)
230 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
232 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
235 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
236 string propVal = realProp->getStringValue();
237 if (propVal == "front")
238 pass->setAttributeAndModes(attrFact->getCullFaceFront());
239 else if (propVal == "back")
240 pass->setAttributeAndModes(attrFact->getCullFaceBack());
241 else if (propVal == "front-back")
242 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
243 else if (propVal == "off")
244 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
246 SG_LOG(SG_INPUT, SG_ALERT,
247 "invalid cull face property " << propVal);
251 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
253 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
255 { "default", StateSet::DEFAULT_BIN },
256 { "opaque", StateSet::OPAQUE_BIN },
257 { "transparent", StateSet::TRANSPARENT_BIN }
260 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
262 struct HintBuilder : public PassAttributeBuilder
264 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
265 const osgDB::ReaderWriter::Options* options)
267 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
270 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
271 findAttr(renderingHints, realProp, renderingHint);
272 pass->setRenderingHint(renderingHint);
276 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
278 struct RenderBinBuilder : public PassAttributeBuilder
280 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
281 const osgDB::ReaderWriter::Options* options)
283 if (!isAttributeActive(effect, prop))
285 const SGPropertyNode* binProp = prop->getChild("bin-number");
286 binProp = getEffectPropertyNode(effect, binProp);
287 const SGPropertyNode* nameProp = prop->getChild("bin-name");
288 nameProp = getEffectPropertyNode(effect, nameProp);
289 if (binProp && nameProp) {
290 pass->setRenderBinDetails(binProp->getIntValue(),
291 nameProp->getStringValue());
294 SG_LOG(SG_INPUT, SG_ALERT,
295 "No render bin number specified in render bin section");
297 SG_LOG(SG_INPUT, SG_ALERT,
298 "No render bin name specified in render bin section");
303 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
305 struct MaterialBuilder : public PassAttributeBuilder
307 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
308 const osgDB::ReaderWriter::Options* options);
311 EffectNameValue<Material::ColorMode> colorModeInit[] =
313 { "ambient", Material::AMBIENT },
314 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
315 { "diffuse", Material::DIFFUSE },
316 { "emissive", Material::EMISSION },
317 { "specular", Material::SPECULAR },
318 { "off", Material::OFF }
320 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
322 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
323 const SGPropertyNode* prop,
324 const osgDB::ReaderWriter::Options* options)
326 if (!isAttributeActive(effect, prop))
328 Material* mat = new Material;
329 const SGPropertyNode* color = 0;
330 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
331 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
332 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
333 mat->setAmbient(Material::FRONT, getColor(color));
334 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
335 mat->setAmbient(Material::BACK, getColor(color));
336 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
337 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
338 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
339 mat->setDiffuse(Material::FRONT, getColor(color));
340 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
341 mat->setDiffuse(Material::BACK, getColor(color));
342 if ((color = getEffectPropertyChild(effect, prop, "specular")))
343 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
344 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
345 mat->setSpecular(Material::FRONT, getColor(color));
346 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
347 mat->setSpecular(Material::BACK, getColor(color));
348 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
349 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
350 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
351 mat->setEmission(Material::FRONT, getColor(color));
352 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
353 mat->setEmission(Material::BACK, getColor(color));
354 const SGPropertyNode* shininess = 0;
355 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
356 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
357 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
358 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
359 mat->setShininess(Material::FRONT, shininess->getFloatValue());
360 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
361 mat->setShininess(Material::BACK, shininess->getFloatValue());
362 Material::ColorMode colorMode = Material::OFF;
363 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
365 mat->setColorMode(colorMode);
366 pass->setAttribute(mat);
369 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
371 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
373 {"dst-alpha", BlendFunc::DST_ALPHA},
374 {"dst-color", BlendFunc::DST_COLOR},
375 {"one", BlendFunc::ONE},
376 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
377 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
378 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
379 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
380 {"src-alpha", BlendFunc::SRC_ALPHA},
381 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
382 {"src-color", BlendFunc::SRC_COLOR},
383 {"constant-color", BlendFunc::CONSTANT_COLOR},
384 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
385 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
386 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
387 {"zero", BlendFunc::ZERO}
389 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
391 struct BlendBuilder : public PassAttributeBuilder
393 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
394 const osgDB::ReaderWriter::Options* options)
396 if (!isAttributeActive(effect, prop))
398 // XXX Compatibility with early <blend> syntax; should go away
400 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
403 if (realProp->nChildren() == 0) {
404 pass->setMode(GL_BLEND, (realProp->getBoolValue()
406 : StateAttribute::OFF));
410 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
412 // XXX When dynamic parameters are supported, this code should
413 // create the blend function even if the mode is off.
414 if (pmode && !pmode->getValue<bool>()) {
415 pass->setMode(GL_BLEND, StateAttribute::OFF);
418 const SGPropertyNode* psource
419 = getEffectPropertyChild(effect, prop, "source");
420 const SGPropertyNode* pdestination
421 = getEffectPropertyChild(effect, prop, "destination");
422 const SGPropertyNode* psourceRGB
423 = getEffectPropertyChild(effect, prop, "source-rgb");
424 const SGPropertyNode* psourceAlpha
425 = getEffectPropertyChild(effect, prop, "source-alpha");
426 const SGPropertyNode* pdestRGB
427 = getEffectPropertyChild(effect, prop, "destination-rgb");
428 const SGPropertyNode* pdestAlpha
429 = getEffectPropertyChild(effect, prop, "destination-alpha");
430 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
431 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
433 findAttr(blendFuncModes, psource, sourceMode);
435 findAttr(blendFuncModes, pdestination, destMode);
436 if (psource && pdestination
437 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
438 && sourceMode == BlendFunc::SRC_ALPHA
439 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
440 pass->setAttributeAndModes(StateAttributeFactory::instance()
441 ->getStandardBlendFunc());
444 BlendFunc* blendFunc = new BlendFunc;
446 blendFunc->setSource(sourceMode);
448 blendFunc->setDestination(destMode);
450 BlendFunc::BlendFuncMode sourceRGBMode;
451 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
452 blendFunc->setSourceRGB(sourceRGBMode);
455 BlendFunc::BlendFuncMode destRGBMode;
456 findAttr(blendFuncModes, pdestRGB, destRGBMode);
457 blendFunc->setDestinationRGB(destRGBMode);
460 BlendFunc::BlendFuncMode sourceAlphaMode;
461 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
462 blendFunc->setSourceAlpha(sourceAlphaMode);
465 BlendFunc::BlendFuncMode destAlphaMode;
466 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
467 blendFunc->setDestinationAlpha(destAlphaMode);
469 pass->setAttributeAndModes(blendFunc);
473 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
475 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
477 {"never", AlphaFunc::NEVER},
478 {"less", AlphaFunc::LESS},
479 {"equal", AlphaFunc::EQUAL},
480 {"lequal", AlphaFunc::LEQUAL},
481 {"greater", AlphaFunc::GREATER},
482 {"notequal", AlphaFunc::NOTEQUAL},
483 {"gequal", AlphaFunc::GEQUAL},
484 {"always", AlphaFunc::ALWAYS}
486 EffectPropertyMap<AlphaFunc::ComparisonFunction>
487 alphaComparison(alphaComparisonInit);
489 struct AlphaTestBuilder : public PassAttributeBuilder
491 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
492 const osgDB::ReaderWriter::Options* options)
494 if (!isAttributeActive(effect, prop))
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 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
542 typedef map<string, ref_ptr<Program> > ProgramMap;
543 ProgramMap programMap;
545 typedef map<string, ref_ptr<Shader> > ShaderMap;
548 void reload_shaders()
550 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
552 Shader *shader = sitr->second.get();
553 string fileName = osgDB::findDataFile(sitr->first);
554 if (!fileName.empty()) {
555 shader->loadShaderSourceFromFile(fileName);
560 struct ShaderProgramBuilder : PassAttributeBuilder
562 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
563 const osgDB::ReaderWriter::Options* options);
566 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
567 const SGPropertyNode* prop,
568 const osgDB::ReaderWriter::Options*
571 if (!isAttributeActive(effect, prop))
573 PropertyList pVertShaders = prop->getChildren("vertex-shader");
574 PropertyList pFragShaders = prop->getChildren("fragment-shader");
576 for (PropertyList::iterator itr = pVertShaders.begin(),
577 e = pVertShaders.end();
581 programKey += (*itr)->getStringValue();
584 for (PropertyList::iterator itr = pFragShaders.begin(),
585 e = pFragShaders.end();
589 programKey += (*itr)->getStringValue();
592 Program* program = 0;
593 ProgramMap::iterator pitr = programMap.find(programKey);
594 if (pitr != programMap.end()) {
595 program = pitr->second.get();
597 program = new Program;
598 program->setName(programKey);
599 // Add vertex shaders, then fragment shaders
600 PropertyList& pvec = pVertShaders;
601 Shader::Type stype = Shader::VERTEX;
602 for (int i = 0; i < 2; ++i) {
603 for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
606 string shaderName = (*nameItr)->getStringValue();
607 ShaderMap::iterator sitr = shaderMap.find(shaderName);
608 if (sitr != shaderMap.end()) {
609 program->addShader(sitr->second.get());
611 string fileName = osgDB::findDataFile(shaderName, options);
612 if (!fileName.empty()) {
613 ref_ptr<Shader> shader = new Shader(stype);
614 if (shader->loadShaderSourceFromFile(fileName)) {
615 program->addShader(shader.get());
616 shaderMap.insert(make_pair(shaderName, shader));
622 stype = Shader::FRAGMENT;
624 programMap.insert(make_pair(programKey, program));
626 pass->setAttributeAndModes(program);
629 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
631 EffectNameValue<Uniform::Type> uniformTypesInit[] =
633 {"float", Uniform::FLOAT},
634 {"float-vec3", Uniform::FLOAT_VEC3},
635 {"float-vec4", Uniform::FLOAT_VEC4},
636 {"sampler-1d", Uniform::SAMPLER_1D},
637 {"sampler-2d", Uniform::SAMPLER_2D},
638 {"sampler-3d", Uniform::SAMPLER_3D}
640 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
642 struct UniformBuilder :public PassAttributeBuilder
644 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
645 const osgDB::ReaderWriter::Options* options)
647 if (!isAttributeActive(effect, prop))
649 const SGPropertyNode* nameProp = prop->getChild("name");
650 const SGPropertyNode* typeProp = prop->getChild("type");
651 const SGPropertyNode* valProp
652 = getEffectPropertyChild(effect, prop, "value");
654 Uniform::Type uniformType = Uniform::FLOAT;
656 name = nameProp->getStringValue();
658 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
662 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
667 props::Type propType = valProp->getType();
671 break; // default float type;
673 uniformType = Uniform::FLOAT_VEC3;
676 uniformType = Uniform::FLOAT_VEC4;
679 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
684 findAttr(uniformTypes, typeProp, uniformType);
686 ref_ptr<Uniform> uniform = new Uniform;
687 uniform->setName(name);
688 uniform->setType(uniformType);
689 switch (uniformType) {
691 uniform->set(valProp->getValue<float>());
693 case Uniform::FLOAT_VEC3:
694 uniform->set(toOsg(valProp->getValue<SGVec3d>()));
696 case Uniform::FLOAT_VEC4:
697 uniform->set(toOsg(valProp->getValue<SGVec4d>()));
699 case Uniform::SAMPLER_1D:
700 case Uniform::SAMPLER_2D:
701 case Uniform::SAMPLER_3D:
702 uniform->set(valProp->getValue<int>());
704 default: // avoid compiler warning
707 pass->addUniform(uniform.get());
711 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
713 // Not sure what to do with "name". At one point I wanted to use it to
714 // order the passes, but I do support render bin and stuff too...
716 struct NameBuilder : public PassAttributeBuilder
718 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
719 const osgDB::ReaderWriter::Options* options)
721 // name can't use <use>
722 string name = prop->getStringValue();
728 InstallAttributeBuilder<NameBuilder> installName("name");
730 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
732 {"fill", PolygonMode::FILL},
733 {"line", PolygonMode::LINE},
734 {"point", PolygonMode::POINT}
736 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
738 struct PolygonModeBuilder : public PassAttributeBuilder
740 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
741 const osgDB::ReaderWriter::Options* options)
743 if (!isAttributeActive(effect, prop))
745 const SGPropertyNode* frontProp
746 = getEffectPropertyChild(effect, prop, "front");
747 const SGPropertyNode* backProp
748 = getEffectPropertyChild(effect, prop, "back");
749 ref_ptr<PolygonMode> pmode = new PolygonMode;
750 PolygonMode::Mode frontMode = PolygonMode::FILL;
751 PolygonMode::Mode backMode = PolygonMode::FILL;
753 findAttr(polygonModeModes, frontProp, frontMode);
754 pmode->setMode(PolygonMode::FRONT, frontMode);
757 findAttr(polygonModeModes, backProp, backMode);
758 pmode->setMode(PolygonMode::BACK, backMode);
760 pass->setAttribute(pmode.get());
764 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
766 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
768 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
769 const osgDB::ReaderWriter::Options* options)
771 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
774 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
775 (realProp->getValue<bool>()
776 ? StateAttribute::ON : StateAttribute::OFF));
780 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
781 installTwoSide("vertex-program-two-side");
783 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
785 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
786 const osgDB::ReaderWriter::Options* options)
788 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
791 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
792 (realProp->getValue<bool>()
793 ? StateAttribute::ON : StateAttribute::OFF));
797 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
798 installPointSize("vertex-program-point-size");
800 EffectNameValue<Depth::Function> depthFunctionInit[] =
802 {"never", Depth::NEVER},
803 {"less", Depth::LESS},
804 {"equal", Depth::EQUAL},
805 {"lequal", Depth::LEQUAL},
806 {"greater", Depth::GREATER},
807 {"notequal", Depth::NOTEQUAL},
808 {"gequal", Depth::GEQUAL},
809 {"always", Depth::ALWAYS}
811 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
813 struct DepthBuilder : public PassAttributeBuilder
815 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
816 const osgDB::ReaderWriter::Options* options)
818 if (!isAttributeActive(effect, prop))
820 ref_ptr<Depth> depth = new Depth;
821 const SGPropertyNode* pfunc
822 = getEffectPropertyChild(effect, prop, "function");
824 Depth::Function func = Depth::LESS;
825 findAttr(depthFunction, pfunc, func);
826 depth->setFunction(func);
828 const SGPropertyNode* pnear
829 = getEffectPropertyChild(effect, prop, "near");
831 depth->setZNear(pnear->getValue<double>());
832 const SGPropertyNode* pfar
833 = getEffectPropertyChild(effect, prop, "far");
835 depth->setZFar(pnear->getValue<double>());
836 const SGPropertyNode* pmask
837 = getEffectPropertyChild(effect, prop, "write-mask");
839 depth->setWriteMask(pmask->getValue<bool>());
840 pass->setAttribute(depth.get());
844 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
846 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
847 const osgDB::ReaderWriter::Options* options)
849 Technique* tniq = new Technique;
850 effect->techniques.push_back(tniq);
851 const SGPropertyNode* predProp = prop->getChild("predicate");
853 tniq->setAlwaysValid(true);
856 TechniquePredParser parser;
857 parser.setTechnique(tniq);
858 expression::BindingLayout& layout = parser.getBindingLayout();
859 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
860 SGExpressionb* validExp
861 = dynamic_cast<SGExpressionb*>(parser.read(predProp
864 tniq->setValidExpression(validExp, layout);
866 throw expression::ParseError("technique predicate is not a boolean expression");
868 catch (expression::ParseError& except)
870 SG_LOG(SG_INPUT, SG_ALERT,
871 "parsing technique predicate " << except.getMessage());
872 tniq->setAlwaysValid(false);
875 PropertyList passProps = prop->getChildren("pass");
876 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
879 buildPass(effect, tniq, itr->ptr(), options);
883 // Specifically for .ac files...
884 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
886 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
887 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
888 Vec4f ambVal, difVal, specVal, emisVal;
889 float shininess = 0.0f;
890 const Material* mat = getStateAttribute<Material>(ss);
892 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
893 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
894 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
895 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
896 shininess = mat->getShininess(Material::FRONT_AND_BACK);
897 makeChild(matNode, "active")->setValue(true);
898 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
899 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
900 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
901 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
902 makeChild(matNode, "shininess")->setValue(shininess);
903 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
905 makeChild(matNode, "active")->setValue(false);
907 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
908 string shadeModelString("smooth");
910 ShadeModel::Mode smMode = sm->getMode();
911 if (smMode == ShadeModel::FLAT)
912 shadeModelString = "flat";
914 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
915 string cullFaceString("off");
916 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
918 switch (cullFace->getMode()) {
919 case CullFace::FRONT:
920 cullFaceString = "front";
923 cullFaceString = "back";
925 case CullFace::FRONT_AND_BACK:
926 cullFaceString = "front-back";
932 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
933 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
934 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
936 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
937 string destMode = findName(blendFuncModes, blendFunc->getDestination());
938 makeChild(blendNode, "active")->setValue(true);
939 makeChild(blendNode, "source")->setStringValue(sourceMode);
940 makeChild(blendNode, "destination")->setStringValue(destMode);
941 makeChild(blendNode, "mode")->setValue(true);
943 makeChild(blendNode, "active")->setValue(false);
945 string renderingHint = findName(renderingHints, ss->getRenderingHint());
946 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
947 makeTextureParameters(paramRoot, ss);
951 // Walk the techniques property tree, building techniques and
953 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
957 PropertyList tniqList = root->getChildren("technique");
958 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
961 buildTechnique(this, *itr, options);
966 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
968 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
971 Effect* effect = eg->getEffect();
974 SGPropertyNode* root = getPropertyRoot();
975 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
976 end = effect->_extraData.end();
979 InitializeWhenAdded* adder
980 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
982 adder->initOnAdd(effect, root);
986 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
987 const Effect::Key& rhs) const
989 if (lhs.paths.size() != rhs.paths.size()
990 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
992 if (lhs.unmerged.valid() && rhs.unmerged.valid())
993 return props::Compare()(lhs.unmerged, rhs.unmerged);
995 return lhs.unmerged == rhs.unmerged;
998 size_t hash_value(const Effect::Key& key)
1001 if (key.unmerged.valid())
1002 boost::hash_combine(seed, *key.unmerged);
1003 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1007 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1009 const Effect& effect = static_cast<const Effect&>(obj);
1011 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1012 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1013 fw.writeObject(*technique);
1020 osgDB::RegisterDotOsgWrapperProxy effectProxy
1024 "Object simgear::Effect",
1026 &Effect_writeLocalData
1030 // Property expressions for technique predicates
1031 class PropertyExpression : public SGExpression<bool>
1034 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1036 void eval(bool& value, const expression::Binding*) const
1038 value = _pnode->getValue<bool>();
1041 SGPropertyNode_ptr _pnode;
1044 class EffectPropertyListener : public SGPropertyChangeListener
1047 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1049 void valueChanged(SGPropertyNode* node)
1051 _tniq->refreshValidity();
1054 osg::ref_ptr<Technique> _tniq;
1057 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1058 expression::Parser* parser)
1060 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1062 PropertyExpression* pexp = new PropertyExpression(pnode);
1063 TechniquePredParser* predParser
1064 = dynamic_cast<TechniquePredParser*>(parser);
1066 pnode->addChangeListener(new EffectPropertyListener(predParser
1071 expression::ExpParserRegistrar propertyRegistrar("property",
1072 propertyExpressionParser);