]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/SGMaterialAnimation.cxx
Merge branch 'maint' into next
[simgear.git] / simgear / scene / model / SGMaterialAnimation.cxx
1 // animation.cxx - classes to manage model animation.
2 // Written by David Megginson, started 2002.
3 //
4 // This file is in the Public Domain, and comes with no warranty.
5
6 #ifdef HAVE_CONFIG_H
7 #  include <simgear_config.h>
8 #endif
9
10 #include "SGMaterialAnimation.hxx"
11
12 #include <osg/AlphaFunc>
13 #include <osg/Array>
14 #include <osg/Drawable>
15 #include <osg/Geode>
16 #include <osg/Geometry>
17 #include <osg/Material>
18 #include <osg/StateSet>
19 #include <osgDB/FileNameUtils>
20 #include <osgDB/FileUtils>
21 #include <osgDB/ReadFile>
22
23 #include <simgear/props/condition.hxx>
24 #include <simgear/props/props.hxx>
25 #include <simgear/scene/model/model.hxx>
26
27 namespace {
28 /**
29  * Get a color from properties.
30  */
31 struct ColorSpec {
32   float red, green, blue;
33   float factor;
34   float offset;
35   SGPropertyNode_ptr red_prop;
36   SGPropertyNode_ptr green_prop;
37   SGPropertyNode_ptr blue_prop;
38   SGPropertyNode_ptr factor_prop;
39   SGPropertyNode_ptr offset_prop;
40   SGVec4f v;
41   
42   ColorSpec(const SGPropertyNode* configNode, SGPropertyNode* modelRoot)
43   {
44     red = -1.0;
45     green = -1.0;
46     blue = -1.0;
47     if (!configNode)
48       return;
49     
50     red = configNode->getFloatValue("red", -1.0);
51     green = configNode->getFloatValue("green", -1.0);
52     blue = configNode->getFloatValue("blue", -1.0);
53     factor = configNode->getFloatValue("factor", 1.0);
54     offset = configNode->getFloatValue("offset", 0.0);
55     
56     if (!modelRoot)
57       return;
58     const SGPropertyNode *node;
59     node = configNode->getChild("red-prop");
60     if (node)
61       red_prop = modelRoot->getNode(node->getStringValue(), true);
62     node = configNode->getChild("green-prop");
63     if (node)
64       green_prop = modelRoot->getNode(node->getStringValue(), true);
65     node = configNode->getChild("blue-prop");
66     if (node)
67       blue_prop = modelRoot->getNode(node->getStringValue(), true);
68     node = configNode->getChild("factor-prop");
69     if (node)
70       factor_prop = modelRoot->getNode(node->getStringValue(), true);
71     node = configNode->getChild("offset-prop");
72     if (node)
73       offset_prop = modelRoot->getNode(node->getStringValue(), true);
74   }
75   
76   bool dirty() {
77     return red >= 0 || green >= 0 || blue >= 0;
78   }
79   bool live() {
80     return red_prop || green_prop || blue_prop
81       || factor_prop || offset_prop;
82   }
83   SGVec4f &rgba() {
84     if (red_prop)
85       red = red_prop->getFloatValue();
86     if (green_prop)
87       green = green_prop->getFloatValue();
88     if (blue_prop)
89       blue = blue_prop->getFloatValue();
90     if (factor_prop)
91       factor = factor_prop->getFloatValue();
92     if (offset_prop)
93       offset = offset_prop->getFloatValue();
94     v[0] = SGMiscf::clip(red*factor + offset, 0, 1);
95     v[1] = SGMiscf::clip(green*factor + offset, 0, 1);
96     v[2] = SGMiscf::clip(blue*factor + offset, 0, 1);
97     v[3] = 1;
98     return v;
99   }
100
101   osg::Vec4& rgbaVec4()
102   {
103     return rgba().osg();
104   }
105   
106   SGVec4f &initialRgba() {
107     v[0] = SGMiscf::clip(red*factor + offset, 0, 1);
108     v[1] = SGMiscf::clip(green*factor + offset, 0, 1);
109     v[2] = SGMiscf::clip(blue*factor + offset, 0, 1);
110     v[3] = 1;
111     return v;
112   }
113 };
114
115 /**
116  * Get a property value from a property.
117  */
118 struct PropSpec {
119   float value;
120   float factor;
121   float offset;
122   float min;
123   float max;
124   SGPropertyNode_ptr value_prop;
125   SGPropertyNode_ptr factor_prop;
126   SGPropertyNode_ptr offset_prop;
127   
128   PropSpec(const char* valueName, const char* valuePropName,
129            const SGPropertyNode* configNode, SGPropertyNode* modelRoot)
130   {
131     value = -1;
132     if (!configNode)
133       return;
134     
135     value = configNode->getFloatValue(valueName, -1);
136     factor = configNode->getFloatValue("factor", 1);
137     offset = configNode->getFloatValue("offset", 0);
138     min = configNode->getFloatValue("min", 0);
139     max = configNode->getFloatValue("max", 1);
140     
141     if (!modelRoot)
142       return;
143     const SGPropertyNode *node;
144     node = configNode->getChild(valuePropName);
145     if (node)
146       value_prop = modelRoot->getNode(node->getStringValue(), true);
147     node = configNode->getChild("factor-prop");
148     if (node)
149       factor_prop = modelRoot->getNode(node->getStringValue(), true);
150     node = configNode->getChild("offset-prop");
151     if (node)
152       offset_prop = modelRoot->getNode(node->getStringValue(), true);
153   }
154   bool dirty() { return value >= 0.0; }
155   bool live() { return value_prop || factor_prop || offset_prop; }
156   float getValue()
157   {
158     if (value_prop)
159       value = value_prop->getFloatValue();
160     if (offset_prop)
161       offset = offset_prop->getFloatValue();
162     if (factor_prop)
163       factor = factor_prop->getFloatValue();
164     return SGMiscf::clip(value*factor + offset, min, max);
165   }
166   float getInitialValue()
167   {
168     return SGMiscf::clip(value*factor + offset, min, max);
169   }
170 };
171
172 /**
173  * The possible color properties supplied by a material animation.
174  */
175 enum SuppliedColor {
176   DIFFUSE = 1,
177   AMBIENT = 2,
178   SPECULAR = 4,
179   EMISSION = 8,
180   SHININESS = 16,
181   TRANSPARENCY = 32
182 };
183
184 const unsigned AMBIENT_DIFFUSE = AMBIENT | DIFFUSE;
185
186 const int allMaterialColors = (DIFFUSE | AMBIENT | SPECULAR | EMISSION
187                                | SHININESS);
188
189 // Visitor for finding default material colors in the animation node's
190 // subgraph. This makes some assumptions about the subgraph i.e.,
191 // there will be one material and one color value found. This is
192 // probably true for ac3d models and most uses of material animations,
193 // but will break down if, for example, you animate the transparency
194 // of a vertex colored model.
195 class MaterialDefaultsVisitor : public osg::NodeVisitor {
196 public:
197   MaterialDefaultsVisitor()
198     : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
199       ambientDiffuse(-1.0f, -1.0f, -1.0f, -1.0f)
200   {
201     setVisitorType(osg::NodeVisitor::NODE_VISITOR);
202   }
203
204   virtual void apply(osg::Node& node)
205   {
206     maybeGetMaterialValues(node.getStateSet());
207     traverse(node);
208   }
209
210   virtual void apply(osg::Geode& node)
211   {
212     maybeGetMaterialValues(node.getStateSet());
213     int numDrawables = node.getNumDrawables();
214     for (int i = 0; i < numDrawables; i++) {
215       osg::Geometry* geom = dynamic_cast<osg::Geometry*>(node.getDrawable(i));
216       if (!geom || geom->getColorBinding() != osg::Geometry::BIND_OVERALL)
217         continue;
218       maybeGetMaterialValues(geom->getStateSet());
219       osg::Array* colorArray = geom->getColorArray();
220       osg::Vec4Array* colorVec4 = dynamic_cast<osg::Vec4Array*>(colorArray);
221       if (colorVec4) {
222         ambientDiffuse = (*colorVec4)[0];
223         break;
224       }
225       osg::Vec3Array* colorVec3 = dynamic_cast<osg::Vec3Array*>(colorArray);
226       if (colorVec3) {
227         ambientDiffuse = osg::Vec4((*colorVec3)[0], 1.0f);
228         break;
229       }
230     }
231   }
232   
233   void maybeGetMaterialValues(osg::StateSet* stateSet)
234   {
235     if (!stateSet)
236       return;
237     osg::Material* nodeMat
238       = dynamic_cast<osg::Material*>(stateSet->getAttribute(osg::StateAttribute::MATERIAL));
239     if (!nodeMat)
240       return;
241     material = nodeMat;
242   }
243
244   osg::ref_ptr<osg::Material> material;
245   osg::Vec4 ambientDiffuse;
246 };
247
248 class UpdateCallback : public osg::NodeCallback {
249 public:
250   UpdateCallback(const osgDB::FilePathList& texturePathList,
251                  const SGCondition* condition,
252                  const SGPropertyNode* configNode, SGPropertyNode* modelRoot) :
253     _condition(condition),
254     _ambient(configNode->getChild("ambient"), modelRoot),
255     _diffuse(configNode->getChild("diffuse"), modelRoot),
256     _specular(configNode->getChild("specular"), modelRoot),
257     _emission(configNode->getChild("emission"), modelRoot),
258     _shininess("shininess", "shininess-prop",
259                configNode/*->getChild("shininess")*/, modelRoot),
260     _transparency("alpha", "alpha-prop",
261                   configNode->getChild("transparency"), modelRoot),
262     _texturePathList(texturePathList),
263     _prevState(false)
264   {
265     const SGPropertyNode* node;
266
267     node = configNode->getChild("threshold-prop");
268     if (node)
269       _thresholdProp = modelRoot->getNode(node->getStringValue(), true);
270     node = configNode->getChild("texture-prop");
271     if (node)
272       _textureProp = modelRoot->getNode(node->getStringValue(), true);
273     _shininess.max = 128;
274   }
275
276   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
277   {
278     osg::StateSet* stateSet = node->getStateSet();
279     if ((!_condition || _condition->test()) && stateSet) {
280       if (_textureProp) {
281         std::string textureName = _textureProp->getStringValue();
282         if (_textureName != textureName) {
283           while (stateSet->getTextureAttribute(0,
284                                                osg::StateAttribute::TEXTURE)) {
285             stateSet->removeTextureAttribute(0, osg::StateAttribute::TEXTURE);
286           }
287           std::string textureFile;
288           textureFile = osgDB::findFileInPath(textureName, _texturePathList);
289           if (!textureFile.empty()) {
290             osg::Texture2D* texture2D = SGLoadTexture2D(textureFile);
291             if (texture2D) {
292               stateSet->setTextureAttribute(0, texture2D,
293                                             osg::StateAttribute::OVERRIDE);
294               stateSet->setTextureMode(0, GL_TEXTURE_2D,
295                                        osg::StateAttribute::ON);
296               _textureName = textureName;
297             }
298           }
299         }
300       }
301       if (_thresholdProp) {
302         osg::StateSet* stateSet = node->getOrCreateStateSet();
303         osg::StateAttribute* stateAttribute;
304         stateAttribute = stateSet->getAttribute(osg::StateAttribute::ALPHAFUNC);
305         osg::AlphaFunc* alphaFunc = dynamic_cast<osg::AlphaFunc*>(stateAttribute);
306         assert(alphaFunc);
307         alphaFunc->setReferenceValue(_thresholdProp->getFloatValue());
308       }
309       osg::StateAttribute* stateAttribute
310         = stateSet->getAttribute(osg::StateAttribute::MATERIAL);
311       osg::Material* material = dynamic_cast<osg::Material*>(stateAttribute);
312       if (material) {
313         if (_ambient.live() || (!_prevState && _ambient.dirty()))
314           material->setAmbient(osg::Material::FRONT_AND_BACK,
315                                _ambient.rgbaVec4());    
316         if (_diffuse.live() || (!_prevState && _diffuse.dirty()))
317           material->setDiffuse(osg::Material::FRONT_AND_BACK,
318                                _diffuse.rgbaVec4());
319         if (_specular.live() || (!_prevState && _specular.dirty()))
320           material->setSpecular(osg::Material::FRONT_AND_BACK,
321                                 _specular.rgbaVec4());
322         if (_emission.live() || (!_prevState && _emission.dirty()))
323           material->setEmission(osg::Material::FRONT_AND_BACK,
324                                 _emission.rgbaVec4());
325         if (_shininess.live() || (!_prevState && _shininess.dirty()))
326           material->setShininess(osg::Material::FRONT_AND_BACK,
327                                  _shininess.getValue());
328         if (_transparency.live() || (!_prevState && _transparency.dirty())) {
329           float alpha = _transparency.getValue();
330           material->setAlpha(osg::Material::FRONT_AND_BACK, alpha);
331           if (alpha < 1.0f) {
332             stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
333             stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
334           } else {
335             stateSet->setRenderingHint(osg::StateSet::DEFAULT_BIN);
336           }
337         }
338       }
339       _prevState = true;
340     } else {
341       _prevState = false;
342     }
343     traverse(node, nv);
344   }
345 private:
346   SGSharedPtr<const SGCondition> _condition;
347   SGSharedPtr<const SGPropertyNode> _textureProp;
348   SGSharedPtr<const SGPropertyNode> _thresholdProp;
349   std::string _textureName;
350   ColorSpec _ambient;
351   ColorSpec _diffuse;
352   ColorSpec _specular;
353   ColorSpec _emission;
354   PropSpec _shininess;
355   PropSpec _transparency;
356   osgDB::FilePathList _texturePathList;
357   bool _prevState;
358 };
359 } // namespace
360
361
362 SGMaterialAnimation::SGMaterialAnimation(const SGPropertyNode* configNode,
363                                          SGPropertyNode* modelRoot,
364                                          const osgDB::ReaderWriter::Options*
365                                          options) :
366   SGAnimation(configNode, modelRoot),
367   texturePathList(options->getDatabasePathList())
368 {
369   if (configNode->hasChild("global"))
370     SG_LOG(SG_IO, SG_ALERT, "Use of <global> in material animation is "
371            "no longer supported");
372 }
373
374 osg::Group*
375 SGMaterialAnimation::createAnimationGroup(osg::Group& parent)
376 {
377   osg::Group* group = new osg::Group;
378   group->setName("material animation group");
379
380   SGPropertyNode* inputRoot = getModelRoot();
381   const SGPropertyNode* node = getConfig()->getChild("property-base");
382   if (node)
383     inputRoot = getModelRoot()->getNode(node->getStringValue(), true);
384   if (getConfig()->hasChild("texture-prop")) {
385       osg::StateSet* stateSet = group->getOrCreateStateSet();
386       stateSet->setDataVariance(osg::Object::DYNAMIC);
387   }
388   if (getConfig()->hasChild("texture")) {
389     std::string textureName = getConfig()->getStringValue("texture");
390     std::string textureFile;
391     textureFile = osgDB::findFileInPath(textureName, texturePathList);
392     if (!textureFile.empty()) {
393       osg::StateSet* stateSet = group->getOrCreateStateSet();
394       osg::Texture2D* texture2D = SGLoadTexture2D(textureFile);
395       if (texture2D) {
396         stateSet->setTextureAttribute(0, texture2D,
397                                       osg::StateAttribute::OVERRIDE);
398         stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
399         if (texture2D->getImage()->isImageTranslucent()) {
400           stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
401           stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
402         }
403       }
404     }
405   }
406   if (getConfig()->hasChild("threshold-prop") ||
407       getConfig()->hasChild("threshold")) {
408     osg::StateSet* stateSet = group->getOrCreateStateSet();
409     osg::AlphaFunc* alphaFunc = new osg::AlphaFunc;
410     alphaFunc->setFunction(osg::AlphaFunc::GREATER);
411     float threshold = getConfig()->getFloatValue("threshold", 0);
412     alphaFunc->setReferenceValue(threshold);
413     stateSet->setAttribute(alphaFunc, osg::StateAttribute::OVERRIDE);
414   }
415
416   unsigned suppliedColors = 0;
417   if (getConfig()->hasChild("ambient"))
418     suppliedColors |= AMBIENT;
419   if (getConfig()->hasChild("diffuse"))
420     suppliedColors |= DIFFUSE;
421   if (getConfig()->hasChild("specular"))
422     suppliedColors |= SPECULAR;
423   if (getConfig()->hasChild("emission"))
424     suppliedColors |= EMISSION;
425   if (getConfig()->hasChild("shininess")
426       || getConfig()->hasChild("shininess-prop"))
427     suppliedColors |= SHININESS;
428   if (getConfig()->hasChild("transparency"))
429     suppliedColors |= TRANSPARENCY;
430
431   if (suppliedColors != 0) {
432       osg::StateSet* stateSet = group->getOrCreateStateSet();
433       osg::Material* mat;
434
435       if (defaultMaterial.valid()) {
436         mat = defaultMaterial.get();
437
438       } else {
439         mat = new osg::Material;
440         mat->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
441       }
442       mat->setDataVariance(osg::Object::DYNAMIC);
443       unsigned defaultColorModeMask = 0;
444       mat->setUpdateCallback(0); // Just to make sure.
445       switch (mat->getColorMode()) {
446       case osg::Material::OFF:
447         defaultColorModeMask = 0;
448         break;
449       case osg::Material::AMBIENT:
450         defaultColorModeMask = AMBIENT;
451         break;
452       case osg::Material::DIFFUSE:
453         defaultColorModeMask = DIFFUSE;
454         break;
455       case osg::Material::AMBIENT_AND_DIFFUSE:
456         defaultColorModeMask = AMBIENT | DIFFUSE;
457         break;
458       case osg::Material::SPECULAR:
459         defaultColorModeMask = SPECULAR;
460         break;
461       case osg::Material::EMISSION:
462         defaultColorModeMask = EMISSION;
463         break;
464       }
465       // Copy the color found by traversing geometry into the material
466       // in case we need to specify it (e.g., transparency) and it is
467       // not specified by the animation.
468       if (defaultAmbientDiffuse.x() >= 0) {
469         if (defaultColorModeMask & AMBIENT)
470           mat->setAmbient(osg::Material::FRONT_AND_BACK, defaultAmbientDiffuse);
471         if (defaultColorModeMask & DIFFUSE)
472           mat->setDiffuse(osg::Material::FRONT_AND_BACK, defaultAmbientDiffuse);
473       }
474       // Compute which colors in the animation override colors set via
475       // colorMode / glColor, and set the colorMode for the animation's
476       // material accordingly. 
477       if (suppliedColors & TRANSPARENCY) {
478         // All colors will be affected by the material. Hope all the
479         // defaults are fine, if needed.
480         mat->setColorMode(osg::Material::OFF);
481       } else if ((suppliedColors & defaultColorModeMask) != 0) {
482         // First deal with the complicated AMBIENT/DIFFUSE case.
483         if ((defaultColorModeMask & AMBIENT_DIFFUSE) != 0) {
484           // glColor can supply colors not specified by the animation.
485           unsigned matColorModeMask = ((~suppliedColors & defaultColorModeMask)
486                                        & AMBIENT_DIFFUSE);
487           if ((matColorModeMask & DIFFUSE) != 0)
488             mat->setColorMode(osg::Material::DIFFUSE);
489           else if ((matColorModeMask & AMBIENT) != 0)
490             mat->setColorMode(osg::Material::AMBIENT);
491           else
492             mat->setColorMode(osg::Material::OFF);
493         } else {
494           // The animation overrides the glColor color.
495           mat->setColorMode(osg::Material::OFF);
496         }
497       } else {
498         // No overlap between the animation and color mode, so leave
499         // the color mode alone.
500       }
501       stateSet->setAttribute(mat,(osg::StateAttribute::ON
502                                   | osg::StateAttribute::OVERRIDE));
503   }
504   group->setUpdateCallback(new UpdateCallback(texturePathList,
505                                               getCondition(),
506                                               getConfig(), inputRoot));
507   parent.addChild(group);
508   return group;
509 }
510
511 void
512 SGMaterialAnimation::install(osg::Node& node)
513 {
514   SGAnimation::install(node);
515
516     MaterialDefaultsVisitor defaultsVisitor;
517     node.accept(defaultsVisitor);
518     if (defaultsVisitor.material.valid()) {
519       defaultMaterial
520         = static_cast<osg::Material*>(defaultsVisitor.material->clone(osg::CopyOp::SHALLOW_COPY));
521     }
522     defaultAmbientDiffuse = defaultsVisitor.ambientDiffuse;
523 }