1 // animation.cxx - classes to manage model animation.
2 // Written by David Megginson, started 2002.
4 // This file is in the Public Domain, and comes with no warranty.
7 # include <simgear_config.h>
10 #include "SGMaterialAnimation.hxx"
12 #include <osg/AlphaFunc>
14 #include <osg/Drawable>
16 #include <osg/Geometry>
17 #include <osg/Material>
18 #include <osg/StateSet>
19 #include <osgDB/FileNameUtils>
20 #include <osgDB/FileUtils>
21 #include <osgDB/ReadFile>
23 #include <simgear/props/condition.hxx>
24 #include <simgear/props/props.hxx>
25 #include <simgear/scene/material/Effect.hxx>
26 #include <simgear/scene/material/EffectGeode.hxx>
27 #include <simgear/scene/material/Pass.hxx>
28 #include <simgear/scene/material/Technique.hxx>
29 #include <simgear/scene/model/model.hxx>
30 #include <simgear/scene/model/ConditionNode.hxx>
33 using namespace simgear;
37 * Get a color from properties.
40 float red, green, blue;
43 SGPropertyNode_ptr red_prop;
44 SGPropertyNode_ptr green_prop;
45 SGPropertyNode_ptr blue_prop;
46 SGPropertyNode_ptr factor_prop;
47 SGPropertyNode_ptr offset_prop;
50 ColorSpec(const SGPropertyNode* configNode, SGPropertyNode* modelRoot)
58 red = configNode->getFloatValue("red", -1.0);
59 green = configNode->getFloatValue("green", -1.0);
60 blue = configNode->getFloatValue("blue", -1.0);
61 factor = configNode->getFloatValue("factor", 1.0);
62 offset = configNode->getFloatValue("offset", 0.0);
66 const SGPropertyNode *node;
67 node = configNode->getChild("red-prop");
69 red_prop = modelRoot->getNode(node->getStringValue(), true);
70 node = configNode->getChild("green-prop");
72 green_prop = modelRoot->getNode(node->getStringValue(), true);
73 node = configNode->getChild("blue-prop");
75 blue_prop = modelRoot->getNode(node->getStringValue(), true);
76 node = configNode->getChild("factor-prop");
78 factor_prop = modelRoot->getNode(node->getStringValue(), true);
79 node = configNode->getChild("offset-prop");
81 offset_prop = modelRoot->getNode(node->getStringValue(), true);
85 return red >= 0 || green >= 0 || blue >= 0;
88 return red_prop || green_prop || blue_prop
89 || factor_prop || offset_prop;
93 red = red_prop->getFloatValue();
95 green = green_prop->getFloatValue();
97 blue = blue_prop->getFloatValue();
99 factor = factor_prop->getFloatValue();
101 offset = offset_prop->getFloatValue();
102 v[0] = SGMiscf::clip(red*factor + offset, 0, 1);
103 v[1] = SGMiscf::clip(green*factor + offset, 0, 1);
104 v[2] = SGMiscf::clip(blue*factor + offset, 0, 1);
111 return toOsg(rgba());
114 SGVec4f &initialRgba() {
115 v[0] = SGMiscf::clip(red*factor + offset, 0, 1);
116 v[1] = SGMiscf::clip(green*factor + offset, 0, 1);
117 v[2] = SGMiscf::clip(blue*factor + offset, 0, 1);
124 * Get a property value from a property.
132 SGPropertyNode_ptr value_prop;
133 SGPropertyNode_ptr factor_prop;
134 SGPropertyNode_ptr offset_prop;
136 PropSpec(const char* valueName, const char* valuePropName,
137 const SGPropertyNode* configNode, SGPropertyNode* modelRoot)
143 value = configNode->getFloatValue(valueName, -1);
144 factor = configNode->getFloatValue("factor", 1);
145 offset = configNode->getFloatValue("offset", 0);
146 min = configNode->getFloatValue("min", 0);
147 max = configNode->getFloatValue("max", 1);
151 const SGPropertyNode *node;
152 node = configNode->getChild(valuePropName);
154 value_prop = modelRoot->getNode(node->getStringValue(), true);
155 node = configNode->getChild("factor-prop");
157 factor_prop = modelRoot->getNode(node->getStringValue(), true);
158 node = configNode->getChild("offset-prop");
160 offset_prop = modelRoot->getNode(node->getStringValue(), true);
162 bool dirty() { return value >= 0.0; }
163 bool live() { return value_prop || factor_prop || offset_prop; }
167 value = value_prop->getFloatValue();
169 offset = offset_prop->getFloatValue();
171 factor = factor_prop->getFloatValue();
172 return SGMiscf::clip(value*factor + offset, min, max);
174 float getInitialValue()
176 return SGMiscf::clip(value*factor + offset, min, max);
181 * The possible color properties supplied by a material animation.
192 const unsigned AMBIENT_DIFFUSE = AMBIENT | DIFFUSE;
194 const int allMaterialColors = (DIFFUSE | AMBIENT | SPECULAR | EMISSION
197 // Visitor for finding default material colors in the animation node's
198 // subgraph. This makes some assumptions about the subgraph i.e.,
199 // there will be one material and one color value found. This is
200 // probably true for ac3d models and most uses of material animations,
201 // but will break down if, for example, you animate the transparency
202 // of a vertex colored model.
203 class MaterialDefaultsVisitor : public osg::NodeVisitor {
205 MaterialDefaultsVisitor()
206 : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
207 ambientDiffuse(-1.0f, -1.0f, -1.0f, -1.0f)
209 setVisitorType(osg::NodeVisitor::NODE_VISITOR);
212 virtual void apply(osg::Node& node)
214 maybeGetMaterialValues(node.getStateSet());
218 virtual void apply(osg::Geode& node)
220 using namespace simgear;
221 EffectGeode* eg = dynamic_cast<EffectGeode*>(&node);
223 const Effect* effect = eg->getEffect();
225 for (vector<osg::ref_ptr<Technique> >::const_iterator itr
226 = effect->techniques.begin(), end = effect->techniques.end();
229 const Technique* tniq = itr->get();
230 for (vector<osg::ref_ptr<Pass> >::const_iterator pitr
231 = tniq->passes.begin(), pend = tniq->passes.end();
234 maybeGetMaterialValues(pitr->get());
237 maybeGetMaterialValues(node.getStateSet());
239 int numDrawables = node.getNumDrawables();
240 for (int i = 0; i < numDrawables; i++) {
241 osg::Geometry* geom = dynamic_cast<osg::Geometry*>(node.getDrawable(i));
242 if (!geom || geom->getColorBinding() != osg::Geometry::BIND_OVERALL)
244 maybeGetMaterialValues(geom->getStateSet());
245 osg::Array* colorArray = geom->getColorArray();
246 osg::Vec4Array* colorVec4 = dynamic_cast<osg::Vec4Array*>(colorArray);
248 ambientDiffuse = (*colorVec4)[0];
251 osg::Vec3Array* colorVec3 = dynamic_cast<osg::Vec3Array*>(colorArray);
253 ambientDiffuse = osg::Vec4((*colorVec3)[0], 1.0f);
259 void maybeGetMaterialValues(const osg::StateSet* stateSet)
263 const osg::Material* nodeMat
264 = dynamic_cast<const osg::Material*>(stateSet
265 ->getAttribute(osg::StateAttribute
272 osg::ref_ptr<const osg::Material> material;
273 osg::Vec4 ambientDiffuse;
276 class MaterialPropertyAdapter
279 MaterialPropertyAdapter(const SGPropertyNode* configNode,
280 SGPropertyNode* modelRoot) :
281 _ambient(configNode->getChild("ambient"), modelRoot),
282 _diffuse(configNode->getChild("diffuse"), modelRoot),
283 _specular(configNode->getChild("specular"), modelRoot),
284 _emission(configNode->getChild("emission"), modelRoot),
285 _shininess("shininess", "shininess-prop",
286 configNode/*->getChild("shininess")*/, modelRoot),
287 _transparency("alpha", "alpha-prop",
288 configNode->getChild("transparency"), modelRoot)
290 _shininess.max = 128;
291 _isAnimated = (_ambient.live() || _diffuse.live() || _specular.live()
292 || _emission.live() || _shininess.live()
293 || _transparency.live());
295 bool isAnimated() { return _isAnimated; }
296 // This takes a StateSet argument because the rendering bin will
297 // be changed if there is transparency.
298 void setMaterialValues(osg::StateSet* stateSet)
300 osg::StateAttribute* stateAttribute
301 = stateSet->getAttribute(osg::StateAttribute::MATERIAL);
302 osg::Material* material = dynamic_cast<osg::Material*>(stateAttribute);
304 if (_ambient.live() || _ambient.dirty())
305 material->setAmbient(osg::Material::FRONT_AND_BACK,
306 _ambient.rgbaVec4());
307 if (_diffuse.live() || _diffuse.dirty())
308 material->setDiffuse(osg::Material::FRONT_AND_BACK,
309 _diffuse.rgbaVec4());
310 if (_specular.live() || _specular.dirty())
311 material->setSpecular(osg::Material::FRONT_AND_BACK,
312 _specular.rgbaVec4());
313 if (_emission.live() || _emission.dirty())
314 material->setEmission(osg::Material::FRONT_AND_BACK,
315 _emission.rgbaVec4());
316 if (_shininess.live() || _shininess.dirty())
317 material->setShininess(osg::Material::FRONT_AND_BACK,
318 _shininess.getValue());
319 if (_transparency.live() || _transparency.dirty()) {
320 float alpha = _transparency.getValue();
321 material->setAlpha(osg::Material::FRONT_AND_BACK, alpha);
323 stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
324 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
326 stateSet->setRenderingHint(osg::StateSet::DEFAULT_BIN);
336 PropSpec _transparency;
341 class UpdateCallback : public osg::NodeCallback {
343 UpdateCallback(const osgDB::FilePathList& texturePathList,
344 const SGPropertyNode* configNode, SGPropertyNode* modelRoot) :
345 _materialProps(configNode, modelRoot),
346 _texturePathList(texturePathList),
349 const SGPropertyNode* node;
351 node = configNode->getChild("threshold-prop");
353 _thresholdProp = modelRoot->getNode(node->getStringValue(), true);
354 node = configNode->getChild("texture-prop");
356 _textureProp = modelRoot->getNode(node->getStringValue(), true);
359 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
361 osg::StateSet* stateSet = node->getStateSet();
364 std::string textureName = _textureProp->getStringValue();
365 if (_textureName != textureName) {
366 while (stateSet->getTextureAttribute(0,
367 osg::StateAttribute::TEXTURE)) {
368 stateSet->removeTextureAttribute(0, osg::StateAttribute::TEXTURE);
370 std::string textureFile;
371 textureFile = osgDB::findFileInPath(textureName, _texturePathList);
372 if (!textureFile.empty()) {
373 osg::Texture2D* texture2D = SGLoadTexture2D(textureFile);
375 stateSet->setTextureAttribute(0, texture2D,
376 osg::StateAttribute::OVERRIDE);
377 stateSet->setTextureMode(0, GL_TEXTURE_2D,
378 osg::StateAttribute::ON);
379 _textureName = textureName;
384 if (_thresholdProp) {
385 osg::StateSet* stateSet = node->getOrCreateStateSet();
386 osg::StateAttribute* stateAttribute;
387 stateAttribute = stateSet->getAttribute(osg::StateAttribute::ALPHAFUNC);
388 osg::AlphaFunc* alphaFunc
389 = dynamic_cast<osg::AlphaFunc*>(stateAttribute);
391 alphaFunc->setReferenceValue(_thresholdProp->getFloatValue());
393 if (_materialProps.isAnimated() || !_prevState)
394 _materialProps.setMaterialValues(stateSet);
402 SGSharedPtr<const SGPropertyNode> _textureProp;
403 SGSharedPtr<const SGPropertyNode> _thresholdProp;
404 std::string _textureName;
405 MaterialPropertyAdapter _materialProps;
406 osgDB::FilePathList _texturePathList;
412 SGMaterialAnimation::SGMaterialAnimation(const SGPropertyNode* configNode,
413 SGPropertyNode* modelRoot,
414 const osgDB::ReaderWriter::Options*
416 SGAnimation(configNode, modelRoot),
417 texturePathList(options->getDatabasePathList())
419 if (configNode->hasChild("global"))
420 SG_LOG(SG_IO, SG_ALERT, "Use of <global> in material animation is "
421 "no longer supported");
425 SGMaterialAnimation::createAnimationGroup(osg::Group& parent)
427 osg::Group* group = new osg::Group;
428 group->setName("material animation group");
430 SGPropertyNode* inputRoot = getModelRoot();
431 const SGPropertyNode* node = getConfig()->getChild("property-base");
433 inputRoot = getModelRoot()->getNode(node->getStringValue(), true);
434 osg::StateSet* stateSet = group->getOrCreateStateSet();
435 if (getConfig()->hasChild("texture")) {
436 std::string textureName = getConfig()->getStringValue("texture");
437 std::string textureFile;
438 textureFile = osgDB::findFileInPath(textureName, texturePathList);
439 if (!textureFile.empty()) {
440 osg::Texture2D* texture2D = SGLoadTexture2D(textureFile);
442 stateSet->setTextureAttribute(0, texture2D,
443 osg::StateAttribute::OVERRIDE);
444 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
445 if (texture2D->getImage()->isImageTranslucent()) {
446 stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
447 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
452 if (getConfig()->hasChild("threshold-prop") ||
453 getConfig()->hasChild("threshold")) {
454 osg::AlphaFunc* alphaFunc = new osg::AlphaFunc;
455 alphaFunc->setFunction(osg::AlphaFunc::GREATER);
456 float threshold = getConfig()->getFloatValue("threshold", 0);
457 alphaFunc->setReferenceValue(threshold);
458 stateSet->setAttribute(alphaFunc, osg::StateAttribute::OVERRIDE);
461 unsigned suppliedColors = 0;
462 if (getConfig()->hasChild("ambient"))
463 suppliedColors |= AMBIENT;
464 if (getConfig()->hasChild("diffuse"))
465 suppliedColors |= DIFFUSE;
466 if (getConfig()->hasChild("specular"))
467 suppliedColors |= SPECULAR;
468 if (getConfig()->hasChild("emission"))
469 suppliedColors |= EMISSION;
470 if (getConfig()->hasChild("shininess")
471 || getConfig()->hasChild("shininess-prop"))
472 suppliedColors |= SHININESS;
473 if (getConfig()->hasChild("transparency"))
474 suppliedColors |= TRANSPARENCY;
475 osg::Material* mat = 0;
476 if (suppliedColors != 0) {
477 if (defaultMaterial.valid()) {
478 mat = defaultMaterial.get();
481 mat = new osg::Material;
482 mat->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
484 mat->setDataVariance(osg::Object::DYNAMIC);
485 unsigned defaultColorModeMask = 0;
486 mat->setUpdateCallback(0); // Just to make sure.
487 // XXX This should probably go away, as ac3d models always have a
488 // DIFFUSE color mode.
489 switch (mat->getColorMode()) {
490 case osg::Material::OFF:
491 defaultColorModeMask = 0;
493 case osg::Material::AMBIENT:
494 defaultColorModeMask = AMBIENT;
496 case osg::Material::DIFFUSE:
497 defaultColorModeMask = DIFFUSE;
499 case osg::Material::AMBIENT_AND_DIFFUSE:
500 defaultColorModeMask = AMBIENT | DIFFUSE;
502 case osg::Material::SPECULAR:
503 defaultColorModeMask = SPECULAR;
505 case osg::Material::EMISSION:
506 defaultColorModeMask = EMISSION;
509 // Copy the color found by traversing geometry into the material
510 // in case we need to specify it (e.g., transparency) and it is
511 // not specified by the animation.
512 if (defaultAmbientDiffuse.x() >= 0) {
513 if (defaultColorModeMask & AMBIENT)
514 mat->setAmbient(osg::Material::FRONT_AND_BACK, defaultAmbientDiffuse);
515 if (defaultColorModeMask & DIFFUSE)
516 mat->setDiffuse(osg::Material::FRONT_AND_BACK, defaultAmbientDiffuse);
518 // Compute which colors in the animation override colors set via
519 // colorMode / glColor, and set the colorMode for the animation's
520 // material accordingly.
521 if (suppliedColors & TRANSPARENCY) {
522 // All colors will be affected by the material. Hope all the
523 // defaults are fine, if needed.
524 mat->setColorMode(osg::Material::OFF);
525 } else if ((suppliedColors & defaultColorModeMask) != 0) {
526 // First deal with the complicated AMBIENT/DIFFUSE case.
527 if ((defaultColorModeMask & AMBIENT_DIFFUSE) != 0) {
528 // glColor can supply colors not specified by the animation.
529 unsigned matColorModeMask = ((~suppliedColors & defaultColorModeMask)
531 if ((matColorModeMask & DIFFUSE) != 0)
532 mat->setColorMode(osg::Material::DIFFUSE);
533 else if ((matColorModeMask & AMBIENT) != 0)
534 mat->setColorMode(osg::Material::AMBIENT);
536 mat->setColorMode(osg::Material::OFF);
538 // The animation overrides the glColor color.
539 mat->setColorMode(osg::Material::OFF);
542 // No overlap between the animation and color mode, so leave
543 // the color mode alone.
545 stateSet->setAttribute(mat,(osg::StateAttribute::ON
546 | osg::StateAttribute::OVERRIDE));
548 bool matAnimated = false;
550 MaterialPropertyAdapter adapter(getConfig(), inputRoot);
551 adapter.setMaterialValues(stateSet);
552 matAnimated = adapter.isAnimated();
554 if (matAnimated || getConfig()->hasChild("texture-prop")
555 || getConfig()->hasChild("threshold-prop") || getCondition()) {
556 stateSet->setDataVariance(osg::Object::DYNAMIC);
557 group->setUpdateCallback(new UpdateCallback(texturePathList,
558 getConfig(), inputRoot));
560 stateSet->setDataVariance(osg::Object::STATIC);
562 if (getCondition()) {
563 ConditionNode* cn = new ConditionNode;
564 cn->setCondition(getCondition());
565 osg::Group* modelGroup = new osg::Group;
566 group->addChild(modelGroup);
568 cn->addChild(modelGroup);
572 parent.addChild(group);
578 SGMaterialAnimation::install(osg::Node& node)
580 SGAnimation::install(node);
582 MaterialDefaultsVisitor defaultsVisitor;
583 node.accept(defaultsVisitor);
584 if (defaultsVisitor.material.valid()) {
586 = static_cast<osg::Material*>(defaultsVisitor.material->clone(osg::CopyOp::SHALLOW_COPY));
588 defaultAmbientDiffuse = defaultsVisitor.ambientDiffuse;
591 const char* colorNames[] =
599 // Build an effect which mimics the material color mode in a
600 // shader. The OpenGL material values will be overridden by the
601 // material animation's material.
603 // This is a hack to get the effect to respect the values set in the
604 // material, set up by the animation, which overrides the values in
605 // the effect's material attributes. Things will be different when
606 // material animations are implemented purely by manipulating effects.
609 SGMaterialAnimation::makeEffectProperties(const SGPropertyNode* animProp)
611 SGPropertyNode_ptr eRoot = new SGPropertyNode;
612 SGPropertyNode* inherit = makeNode(eRoot, "inherits-from");
613 if (animProp->hasChild("diffuse") || animProp->hasChild("transparency"))
614 inherit->setStringValue("Effects/material-off");
616 inherit->setStringValue("Effects/material-diffuse");