]> git.mxchange.org Git - simgear.git/blob - simgear/scene/model/SGPickAnimation.cxx
Restructure to avoid ordering issues.
[simgear.git] / simgear / scene / model / SGPickAnimation.cxx
1 /* -*-c++-*-
2  *
3  * Copyright (C) 2013 James Turner
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18  * MA 02110-1301, USA.
19  *
20  */
21      
22      
23 #include <simgear/scene/model/SGPickAnimation.hxx>
24
25 #include <algorithm>
26
27 #include <osg/Geode>
28 #include <osg/PolygonOffset>
29 #include <osg/PolygonMode>
30 #include <osg/Material>
31 #include <osgGA/GUIEventAdapter>
32
33 #include <simgear/sg_inlines.h>
34 #include <simgear/scene/util/SGPickCallback.hxx>
35 #include <simgear/scene/material/EffectGeode.hxx>
36 #include <simgear/scene/util/SGSceneUserData.hxx>
37 #include <simgear/structure/SGBinding.hxx>
38 #include <simgear/scene/util/StateAttributeFactory.hxx>
39 #include <simgear/scene/model/SGRotateTransform.hxx>
40 #include <simgear/scene/model/SGTranslateTransform.hxx>
41
42 using namespace simgear;
43
44 using OpenThreads::Mutex;
45 using OpenThreads::ScopedLock;
46
47 static void readOptionalBindingList(const SGPropertyNode* aNode, SGPropertyNode* modelRoot,
48     const std::string& aName, SGBindingList& aBindings)
49 {
50     const SGPropertyNode* n = aNode->getChild(aName);
51     if (n)
52         aBindings = readBindingList(n->getChildren("binding"), modelRoot);
53     
54 }
55
56
57 osg::Vec2d eventToWindowCoords(const osgGA::GUIEventAdapter* ea)
58 {
59     using namespace osg;
60     const GraphicsContext* gc = ea->getGraphicsContext();
61     const GraphicsContext::Traits* traits = gc->getTraits() ;
62     // Scale x, y to the dimensions of the window
63     double x = (((ea->getX() - ea->getXmin()) / (ea->getXmax() - ea->getXmin()))
64          * (double)traits->width);
65     double y = (((ea->getY() - ea->getYmin()) / (ea->getYmax() - ea->getYmin()))
66          * (double)traits->height);
67     if (ea->getMouseYOrientation() == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS)
68         y = (double)traits->height - y;
69     
70     return osg::Vec2d(x, y);
71 }
72
73  class SGPickAnimation::PickCallback : public SGPickCallback {
74  public:
75    PickCallback(const SGPropertyNode* configNode,
76                 SGPropertyNode* modelRoot) :
77      SGPickCallback(PriorityPanel),
78      _repeatable(configNode->getBoolValue("repeatable", false)),
79      _repeatInterval(configNode->getDoubleValue("interval-sec", 0.1))
80    {
81      std::vector<SGPropertyNode_ptr> bindings;
82
83      bindings = configNode->getChildren("button");
84      for (unsigned int i = 0; i < bindings.size(); ++i) {
85        _buttons.insert( bindings[i]->getIntValue() );
86      }
87
88      _bindingsDown = readBindingList(configNode->getChildren("binding"), modelRoot);
89      readOptionalBindingList(configNode, modelRoot, "mod-up", _bindingsUp);
90      
91      
92      if (configNode->hasChild("cursor")) {
93        _cursorName = configNode->getStringValue("cursor");
94      }
95    }
96      
97      void addHoverBindings(const SGPropertyNode* hoverNode,
98                              SGPropertyNode* modelRoot)
99      {
100          _hover = readBindingList(hoverNode->getChildren("binding"), modelRoot);
101      }
102      
103    virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info&)
104    {
105        if (_buttons.find(button) == _buttons.end()) {
106            return false;
107        }
108        
109      fireBindingList(_bindingsDown);
110      _repeatTime = -_repeatInterval;    // anti-bobble: delay start of repeat
111      return true;
112    }
113    virtual void buttonReleased(int keyModState)
114    {
115        SG_UNUSED(keyModState);
116        fireBindingList(_bindingsUp);
117    }
118      
119    virtual void update(double dt, int keyModState)
120    {
121      SG_UNUSED(keyModState);
122      if (!_repeatable)
123        return;
124
125      _repeatTime += dt;
126      while (_repeatInterval < _repeatTime) {
127        _repeatTime -= _repeatInterval;
128          fireBindingList(_bindingsDown);
129      }
130    }
131    
132    virtual bool hover(const osg::Vec2d& windowPos, const Info& info)
133    {
134        if (_hover.empty()) {
135            return false;
136        }
137        
138        SGPropertyNode_ptr params(new SGPropertyNode);
139        params->setDoubleValue("x", windowPos.x());
140        params->setDoubleValue("y", windowPos.y());
141        fireBindingList(_hover, params.ptr());
142        return true;
143    }
144    
145    std::string getCursor() const
146    { return _cursorName; }
147  private:
148    SGBindingList _bindingsDown;
149    SGBindingList _bindingsUp;
150    SGBindingList _hover;
151    std::set<int> _buttons;
152    bool _repeatable;
153    double _repeatInterval;
154    double _repeatTime;
155    std::string _cursorName;
156  };
157
158  class VncVisitor : public osg::NodeVisitor {
159   public:
160    VncVisitor(double x, double y, int mask) :
161      osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
162      _texX(x), _texY(y), _mask(mask), _done(false)
163    {
164      SG_LOG(SG_INPUT, SG_DEBUG, "VncVisitor constructor "
165        << x << "," << y << " mask " << mask);
166    }
167
168    virtual void apply(osg::Node &node)
169    {
170      // Some nodes have state sets attached
171      touchStateSet(node.getStateSet());
172      if (!_done)
173        traverse(node);
174      if (_done) return;
175      // See whether we are a geode worth exploring
176      osg::Geode *g = dynamic_cast<osg::Geode*>(&node);
177      if (!g) return;
178      // Go find all its drawables
179      int i = g->getNumDrawables();
180      while (--i >= 0) {
181        osg::Drawable *d = g->getDrawable(i);
182        if (d) touchDrawable(*d);
183      }
184      // Out of optimism, do the same for EffectGeode
185      simgear::EffectGeode *eg = dynamic_cast<simgear::EffectGeode*>(&node);
186      if (!eg) return;
187      for (simgear::EffectGeode::DrawablesIterator di = eg->drawablesBegin();
188           di != eg->drawablesEnd(); di++) {
189        touchDrawable(**di);
190      }
191      // Now see whether the EffectGeode has an Effect
192      simgear::Effect *e = eg->getEffect();
193      if (e) {
194        touchStateSet(e->getDefaultStateSet());
195      }
196    }
197
198    inline void touchDrawable(osg::Drawable &d)
199    {
200      osg::StateSet *ss = d.getStateSet();
201      touchStateSet(ss);
202    }
203
204    void touchStateSet(osg::StateSet *ss)
205    {
206      if (!ss) return;
207      osg::StateAttribute *sa = ss->getTextureAttribute(0,
208        osg::StateAttribute::TEXTURE);
209      if (!sa) return;
210      osg::Texture *t = sa->asTexture();
211      if (!t) return;
212      osg::Image *img = t->getImage(0);
213      if (!img) return;
214      if (!_done) {
215        int pixX = _texX * img->s();
216        int pixY = _texY * img->t();
217        _done = img->sendPointerEvent(pixX, pixY, _mask);
218        SG_LOG(SG_INPUT, SG_DEBUG, "VncVisitor image said " << _done
219          << " to coord " << pixX << "," << pixY);
220      }
221    }
222
223    inline bool wasSuccessful()
224    {
225      return _done;
226    }
227
228   private:
229    double _texX, _texY;
230    int _mask;
231    bool _done;
232  };
233
234 ///////////////////////////////////////////////////////////////////////////////
235
236 class SGPickAnimation::VncCallback : public SGPickCallback {
237 public:
238  VncCallback(const SGPropertyNode* configNode,
239               SGPropertyNode* modelRoot,
240               osg::Group *node)
241      : _node(node)
242  {
243    SG_LOG(SG_INPUT, SG_DEBUG, "Configuring VNC callback");
244    const char *cornernames[3] = {"top-left", "top-right", "bottom-left"};
245    SGVec3d *cornercoords[3] = {&_topLeft, &_toRight, &_toDown};
246    for (int c =0; c < 3; c++) {
247      const SGPropertyNode* cornerNode = configNode->getChild(cornernames[c]);
248      *cornercoords[c] = SGVec3d(
249        cornerNode->getDoubleValue("x"),
250        cornerNode->getDoubleValue("y"),
251        cornerNode->getDoubleValue("z"));
252    }
253    _toRight -= _topLeft;
254    _toDown -= _topLeft;
255    _squaredRight = dot(_toRight, _toRight);
256    _squaredDown = dot(_toDown, _toDown);
257  }
258
259  virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info& info)
260  {
261    SGVec3d loc(info.local);
262    SG_LOG(SG_INPUT, SG_DEBUG, "VNC pressed " << button << ": " << loc);
263    loc -= _topLeft;
264    _x = dot(loc, _toRight) / _squaredRight;
265    _y = dot(loc, _toDown) / _squaredDown;
266    if (_x<0) _x = 0; else if (_x > 1) _x = 1;
267    if (_y<0) _y = 0; else if (_y > 1) _y = 1;
268    VncVisitor vv(_x, _y, 1 << button);
269    _node->accept(vv);
270    return vv.wasSuccessful();
271
272  }
273  virtual void buttonReleased(int keyModState)
274  {
275    SG_UNUSED(keyModState);
276    SG_LOG(SG_INPUT, SG_DEBUG, "VNC release");
277    VncVisitor vv(_x, _y, 0);
278    _node->accept(vv);
279  }
280
281 private:
282  double _x, _y;
283  osg::ref_ptr<osg::Group> _node;
284  SGVec3d _topLeft, _toRight, _toDown;
285  double _squaredRight, _squaredDown;
286 };
287
288 ///////////////////////////////////////////////////////////////////////////////
289
290 SGPickAnimation::SGPickAnimation(const SGPropertyNode* configNode,
291                                 SGPropertyNode* modelRoot) :
292   SGAnimation(configNode, modelRoot)
293 {
294   std::vector<SGPropertyNode_ptr> names =
295     configNode->getChildren("proxy-name");
296   for (unsigned i = 0; i < names.size(); ++i) {
297     _proxyNames.push_back(names[i]->getStringValue());
298   }
299 }
300
301 void SGPickAnimation::apply(osg::Node* node)
302 {
303     SGAnimation::apply(node);
304 }
305
306 namespace
307 {
308 OpenThreads::Mutex highlightStateSetMutex;
309 osg::ref_ptr<osg::StateSet> static_highlightStateSet;
310 }
311
312
313
314
315 osg::StateSet* sharedHighlightStateSet()
316 {
317   ScopedLock<Mutex> lock(highlightStateSetMutex);
318   if (!static_highlightStateSet.valid()) {
319     static_highlightStateSet = new osg::StateSet;
320     
321     osg::Texture2D* white = StateAttributeFactory::instance()->getWhiteTexture();
322     static_highlightStateSet->setTextureAttributeAndModes(0, white,
323                                           (osg::StateAttribute::ON
324                                            | osg::StateAttribute::OVERRIDE
325                                            | osg::StateAttribute::PROTECTED));
326     osg::PolygonOffset* polygonOffset = new osg::PolygonOffset;
327     polygonOffset->setFactor(-1);
328     polygonOffset->setUnits(-1);
329     static_highlightStateSet->setAttribute(polygonOffset, osg::StateAttribute::OVERRIDE);
330     static_highlightStateSet->setMode(GL_POLYGON_OFFSET_LINE,
331                       osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
332     osg::PolygonMode* polygonMode = new osg::PolygonMode;
333     polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
334                          osg::PolygonMode::LINE);
335     static_highlightStateSet->setAttribute(polygonMode, osg::StateAttribute::OVERRIDE);
336     osg::Material* material = new osg::Material;
337     material->setColorMode(osg::Material::OFF);
338     material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 1));
339     // XXX Alpha < 1.0 in the diffuse material value is a signal to the
340     // default shader to take the alpha value from the material value
341     // and not the glColor. In many cases the pick animation geometry is
342     // transparent, so the outline would not be visible without this hack.
343     material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, .95));
344     material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 0, 1));
345     material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 0));
346     static_highlightStateSet->setAttribute(
347                            material, osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED);
348     // The default shader has a colorMode uniform that mimics the
349     // behavior of Material color mode.
350  
351     osg::Uniform* colorModeUniform = new osg::Uniform(osg::Uniform::INT, "colorMode");
352     colorModeUniform->set(0); // MODE_OFF
353     colorModeUniform->setDataVariance(osg::Object::STATIC);
354     static_highlightStateSet->addUniform(colorModeUniform,
355                          osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
356   }
357   
358   return static_highlightStateSet.get();
359 }
360
361 void
362 SGPickAnimation::apply(osg::Group& group)
363 {
364   if (_objectNames.empty() && _proxyNames.empty()) {
365     return;
366   }
367   
368   group.traverse(*this);
369   
370   // iterate over all group children
371   int i = group.getNumChildren() - 1;
372   for (; 0 <= i; --i) {
373     osg::Node* child = group.getChild(i);
374     if (child->getName().empty()) {
375         continue;
376     }
377       
378     std::list<std::string>::iterator it = std::find(_objectNames.begin(), _objectNames.end(), child->getName());
379     if (it != _objectNames.end()) {
380       _objectNames.erase(it);
381       install(*child);
382       
383       osg::ref_ptr<osg::Group> renderGroup, pickGroup;      
384       osg::Group* mainGroup = createMainGroup(&group);
385       mainGroup->setName(child->getName());
386       child->setName(""); // don't apply other animations twice
387       
388       if (getConfig()->getBoolValue("visible", true)) {
389           renderGroup = new osg::Group;
390           renderGroup->setName("pick render group");
391           renderGroup->addChild(child);
392           mainGroup->addChild(renderGroup);
393       }
394       
395       pickGroup = new osg::Group;
396       pickGroup->setName("pick highlight group");
397       pickGroup->setNodeMask(simgear::PICK_BIT);
398       pickGroup->setStateSet(sharedHighlightStateSet());
399       mainGroup->addChild(pickGroup);
400       
401       setupCallbacks(SGSceneUserData::getOrCreateSceneUserData(pickGroup), mainGroup);
402
403       pickGroup->addChild(child);
404       group.removeChild(child);
405       continue;
406     }
407     
408     string_list::iterator j = std::find(_proxyNames.begin(), _proxyNames.end(), child->getName());
409     if (j == _proxyNames.end()) {
410       continue;
411     }
412     
413     _proxyNames.erase(j);
414     osg::ref_ptr<osg::Group> proxyGroup = new osg::Group;
415     group.addChild(proxyGroup);
416     proxyGroup->setStateSet(sharedHighlightStateSet());
417     proxyGroup->setNodeMask(simgear::PICK_BIT);
418       
419     setupCallbacks(SGSceneUserData::getOrCreateSceneUserData(proxyGroup), proxyGroup);
420     proxyGroup->addChild(child);
421     group.removeChild(child);
422   } // of group children iteration
423 }
424
425 osg::Group*
426 SGPickAnimation::createMainGroup(osg::Group* pr)
427 {
428   osg::Group* g = new osg::Group;
429   pr->addChild(g);
430   return g;
431 }
432
433 void
434 SGPickAnimation::setupCallbacks(SGSceneUserData* ud, osg::Group* parent)
435 {
436   PickCallback* pickCb = NULL;
437   
438   // add actions that become macro and command invocations
439   std::vector<SGPropertyNode_ptr> actions;
440   actions = getConfig()->getChildren("action");
441   for (unsigned int i = 0; i < actions.size(); ++i) {
442     pickCb = new PickCallback(actions[i], getModelRoot());
443     ud->addPickCallback(pickCb);
444   }
445   
446   if (getConfig()->hasChild("hovered")) {
447     if (!pickCb) {
448       // make a trivial PickCallback to hang the hovered off of
449       SGPropertyNode_ptr dummyNode(new SGPropertyNode);
450       pickCb = new PickCallback(dummyNode.ptr(), getModelRoot());
451       ud->addPickCallback(pickCb);
452     }
453     
454     pickCb->addHoverBindings(getConfig()->getNode("hovered"), getModelRoot());
455   }
456   
457   // Look for the VNC sessions that want raw mouse input
458   actions = getConfig()->getChildren("vncaction");
459   for (unsigned int i = 0; i < actions.size(); ++i) {
460     ud->addPickCallback(new VncCallback(actions[i], getModelRoot(), parent));
461   }
462 }
463
464 ///////////////////////////////////////////////////////////////////////////
465
466 // insert count copies of binding list A, into the output list.
467 // effectively makes the output list fire binding A multiple times
468 // in sequence
469 static void repeatBindings(const SGBindingList& a, SGBindingList& out, int count)
470 {
471     out.clear();
472     for (int i=0; i<count; ++i) {
473         out.insert(out.end(), a.begin(), a.end());
474     }
475 }
476
477 static bool static_knobMouseWheelAlternateDirection = false;
478 static bool static_knobDragAlternateAxis = false;
479 static double static_dragSensitivity = 1.0;
480
481 class KnobSliderPickCallback : public SGPickCallback {
482 public:
483     enum Direction
484     {
485         DIRECTION_NONE,
486         DIRECTION_INCREASE,
487         DIRECTION_DECREASE
488     };
489     
490     enum DragDirection
491     {
492         DRAG_DEFAULT = 0,
493         DRAG_VERTICAL,
494         DRAG_HORIZONTAL
495     };
496
497     
498     KnobSliderPickCallback(const SGPropertyNode* configNode,
499                  SGPropertyNode* modelRoot) :
500         SGPickCallback(PriorityPanel),
501         _direction(DIRECTION_NONE),
502         _repeatInterval(configNode->getDoubleValue("interval-sec", 0.1)),
503         _dragDirection(DRAG_DEFAULT)
504     {
505         readOptionalBindingList(configNode, modelRoot, "action", _action);
506         readOptionalBindingList(configNode, modelRoot, "increase", _bindingsIncrease);
507         readOptionalBindingList(configNode, modelRoot, "decrease", _bindingsDecrease);
508         
509         readOptionalBindingList(configNode, modelRoot, "release", _releaseAction);
510         readOptionalBindingList(configNode, modelRoot, "hovered", _hover);
511         
512         if (configNode->hasChild("shift-action") || configNode->hasChild("shift-increase") ||
513             configNode->hasChild("shift-decrease"))
514         {
515         // explicit shifted behaviour - just do exactly what was provided
516             readOptionalBindingList(configNode, modelRoot, "shift-action", _shiftedAction);
517             readOptionalBindingList(configNode, modelRoot, "shift-increase", _shiftedIncrease);
518             readOptionalBindingList(configNode, modelRoot, "shift-decrease", _shiftedDecrease);
519         } else {
520             // default shifted behaviour - repeat normal bindings N times.
521             int shiftRepeat = configNode->getIntValue("shift-repeat", 10);
522             repeatBindings(_action, _shiftedAction, shiftRepeat);
523             repeatBindings(_bindingsIncrease, _shiftedIncrease, shiftRepeat);
524             repeatBindings(_bindingsDecrease, _shiftedDecrease, shiftRepeat);
525         } // of default shifted behaviour
526         
527         _dragScale = configNode->getDoubleValue("drag-scale-px", 10.0);
528         std::string dragDir = configNode->getStringValue("drag-direction");
529         if (dragDir == "vertical") {
530             _dragDirection = DRAG_VERTICAL;
531         } else if (dragDir == "horizontal") {
532             _dragDirection = DRAG_HORIZONTAL;
533         }
534       
535         if (configNode->hasChild("cursor")) {
536             _cursorName = configNode->getStringValue("cursor");
537         } else {
538           DragDirection dir = effectiveDragDirection();
539           if (dir == DRAG_VERTICAL) {
540             _cursorName = "drag-vertical";
541           } else if (dir == DRAG_HORIZONTAL) {
542             _cursorName = "drag-horizontal";
543           }
544         }
545     }
546     
547     virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info&)
548     {        
549         // the 'be nice to Mac / laptop' users option; alt-clicking spins the
550         // opposite direction. Should make this configurable
551         if ((button == 0) && (ea->getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_ALT)) {
552             button = 1;
553         }
554         
555         int increaseMouseWheel = static_knobMouseWheelAlternateDirection ? 3 : 4;
556         int decreaseMouseWheel = static_knobMouseWheelAlternateDirection ? 4 : 3;
557             
558         _direction = DIRECTION_NONE;
559         if ((button == 0) || (button == increaseMouseWheel)) {
560             _direction = DIRECTION_INCREASE;
561         } else if ((button == 1) || (button == decreaseMouseWheel)) {
562             _direction = DIRECTION_DECREASE;
563         } else {
564             return false;
565         }
566         
567         _lastFirePos = eventToWindowCoords(ea);
568     // delay start of repeat, makes dragging more usable
569         _repeatTime = -_repeatInterval;    
570         _hasDragged = false;
571         return true;
572     }
573     
574     virtual void buttonReleased(int keyModState)
575     {
576         // for *clicks*, we only fire on button release
577         if (!_hasDragged) {
578             fire(keyModState & osgGA::GUIEventAdapter::MODKEY_SHIFT, _direction);
579         }
580         
581         fireBindingList(_releaseAction);
582     }
583   
584     DragDirection effectiveDragDirection() const
585     {
586       if (_dragDirection == DRAG_DEFAULT) {
587         // respect the current default settings - this allows runtime
588         // setting of the default drag direction.
589         return static_knobDragAlternateAxis ? DRAG_VERTICAL : DRAG_HORIZONTAL;
590       }
591       
592       return _dragDirection;
593   }
594   
595     virtual void mouseMoved(const osgGA::GUIEventAdapter* ea)
596     {
597         _mousePos = eventToWindowCoords(ea);
598         osg::Vec2d deltaMouse = _mousePos - _lastFirePos;
599         
600         if (!_hasDragged) {
601             
602             double manhattanDist = deltaMouse.x() * deltaMouse.x()  + deltaMouse.y() * deltaMouse.y();
603             if (manhattanDist < 5) {
604                 // don't do anything, just input noise
605                 return;
606             }
607             
608         // user is dragging, disable repeat behaviour
609             _hasDragged = true;
610         }
611       
612         double delta = (effectiveDragDirection() == DRAG_VERTICAL) ? deltaMouse.y() : deltaMouse.x();
613     // per-animation scale factor lets the aircraft author tune for expectations,
614     // eg heading setting vs 5-state switch.
615     // then we scale by a global sensitivity, which the user can set.
616         delta *= static_dragSensitivity / _dragScale;
617         
618         if (fabs(delta) >= 1.0) {
619             // determine direction from sign of delta
620             Direction dir = (delta > 0.0) ? DIRECTION_INCREASE : DIRECTION_DECREASE;
621             fire(ea->getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT, dir);
622             _lastFirePos = _mousePos;
623         }
624     }
625     
626     virtual void update(double dt, int keyModState)
627     {
628         if (_hasDragged) {
629             return;
630         }
631         
632         _repeatTime += dt;
633         while (_repeatInterval < _repeatTime) {
634             _repeatTime -= _repeatInterval;
635             fire(keyModState & osgGA::GUIEventAdapter::MODKEY_SHIFT, _direction);
636         } // of repeat iteration
637     }
638
639     virtual bool hover(const osg::Vec2d& windowPos, const Info& info)
640     {
641         if (_hover.empty()) {
642             return false;
643         }
644        
645         SGPropertyNode_ptr params(new SGPropertyNode);
646         params->setDoubleValue("x", windowPos.x());
647         params->setDoubleValue("y", windowPos.y());
648         fireBindingList(_hover, params.ptr());
649         return true;
650     }
651   
652     void setCursor(const std::string& aName)
653     {
654       _cursorName = aName;
655     }
656   
657     virtual std::string getCursor() const
658     { return _cursorName; }
659   
660 private:
661     void fire(bool isShifted, Direction dir)
662     {
663         const SGBindingList& act(isShifted ? _shiftedAction : _action);
664         const SGBindingList& incr(isShifted ? _shiftedIncrease : _bindingsIncrease);
665         const SGBindingList& decr(isShifted ? _shiftedDecrease : _bindingsDecrease);
666         
667         switch (dir) {
668             case DIRECTION_INCREASE:
669                 fireBindingListWithOffset(act,  1, 1);
670                 fireBindingList(incr);
671                 break;
672             case DIRECTION_DECREASE:
673                 fireBindingListWithOffset(act, -1, 1);
674                 fireBindingList(decr);
675                 break;
676             default: break;
677         }
678     }
679     
680     SGBindingList _action, _shiftedAction;
681     SGBindingList _releaseAction;
682     SGBindingList _bindingsIncrease, _shiftedIncrease,
683         _bindingsDecrease, _shiftedDecrease;
684     SGBindingList _hover;
685     
686         
687     Direction _direction;
688     double _repeatInterval;
689     double _repeatTime;
690     
691     DragDirection _dragDirection;
692     bool _hasDragged; ///< has the mouse been dragged since the press?
693     osg::Vec2d _mousePos, ///< current window coords location of the mouse
694         _lastFirePos; ///< mouse location where we last fired the bindings
695     double _dragScale;
696   
697     std::string _cursorName;
698 };
699
700 ///////////////////////////////////////////////////////////////////////////////
701
702 class SGKnobAnimation::UpdateCallback : public osg::NodeCallback {
703 public:
704     UpdateCallback(SGExpressiond const* animationValue) :
705         _animationValue(animationValue)
706     {
707         setName("SGKnobAnimation::UpdateCallback");
708     }
709     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
710     {
711         SGRotateTransform* transform = static_cast<SGRotateTransform*>(node);
712         transform->setAngleDeg(_animationValue->getValue());
713         traverse(node, nv);
714     }
715     
716 private:
717     SGSharedPtr<SGExpressiond const> _animationValue;
718 };
719
720
721 SGKnobAnimation::SGKnobAnimation(const SGPropertyNode* configNode,
722                                  SGPropertyNode* modelRoot) :
723     SGPickAnimation(configNode, modelRoot)
724 {
725     SGSharedPtr<SGExpressiond> value = read_value(configNode, modelRoot, "-deg",
726                                                   -SGLimitsd::max(), SGLimitsd::max());
727     _animationValue = value->simplify();
728     
729     
730     readRotationCenterAndAxis(configNode, _center, _axis);
731 }
732
733 osg::Group*
734 SGKnobAnimation::createMainGroup(osg::Group* pr)
735 {  
736   SGRotateTransform* transform = new SGRotateTransform();
737   
738   UpdateCallback* uc = new UpdateCallback(_animationValue);
739   transform->setUpdateCallback(uc);
740   transform->setCenter(_center);
741   transform->setAxis(_axis);
742   
743   pr->addChild(transform);
744   return transform;
745 }
746
747 void
748 SGKnobAnimation::setupCallbacks(SGSceneUserData* ud, osg::Group*)
749 {
750   ud->setPickCallback(new KnobSliderPickCallback(getConfig(), getModelRoot()));
751 }
752
753 void SGKnobAnimation::setAlternateMouseWheelDirection(bool aToggle)
754 {
755     static_knobMouseWheelAlternateDirection = aToggle;
756 }
757
758 void SGKnobAnimation::setAlternateDragAxis(bool aToggle)
759 {
760     static_knobDragAlternateAxis = aToggle;
761 }
762
763 void SGKnobAnimation::setDragSensitivity(double aFactor)
764 {
765     static_dragSensitivity = aFactor;
766 }
767
768 ///////////////////////////////////////////////////////////////////////////////
769
770 class SGSliderAnimation::UpdateCallback : public osg::NodeCallback {
771 public:
772     UpdateCallback(SGExpressiond const* animationValue) :
773     _animationValue(animationValue)
774     {
775         setName("SGSliderAnimation::UpdateCallback");
776     }
777     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
778     {
779         SGTranslateTransform* transform = static_cast<SGTranslateTransform*>(node);
780         transform->setValue(_animationValue->getValue());
781
782         traverse(node, nv);
783     }
784     
785 private:
786     SGSharedPtr<SGExpressiond const> _animationValue;
787 };
788
789
790 SGSliderAnimation::SGSliderAnimation(const SGPropertyNode* configNode,
791                                  SGPropertyNode* modelRoot) :
792     SGPickAnimation(configNode, modelRoot)
793 {
794     SGSharedPtr<SGExpressiond> value = read_value(configNode, modelRoot, "-m",
795                                                   -SGLimitsd::max(), SGLimitsd::max());
796     _animationValue = value->simplify();
797     
798     _axis = readTranslateAxis(configNode);
799 }
800
801 osg::Group*
802 SGSliderAnimation::createMainGroup(osg::Group* pr)
803 {  
804   SGTranslateTransform* transform = new SGTranslateTransform();
805   
806   UpdateCallback* uc = new UpdateCallback(_animationValue);
807   transform->setUpdateCallback(uc);
808   transform->setAxis(_axis);
809   
810   pr->addChild(transform);
811   return transform;
812 }
813
814 void
815 SGSliderAnimation::setupCallbacks(SGSceneUserData* ud, osg::Group*)
816 {
817   ud->setPickCallback(new KnobSliderPickCallback(getConfig(), getModelRoot()));
818 }