3 * Copyright (C) 2013 James Turner
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.
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.
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,
23 #include <simgear/scene/model/SGPickAnimation.hxx>
26 #include <osg/PolygonOffset>
27 #include <osg/PolygonMode>
28 #include <osg/Material>
29 #include <osgGA/GUIEventAdapter>
31 #include <simgear/scene/util/SGPickCallback.hxx>
32 #include <simgear/scene/material/EffectGeode.hxx>
33 #include <simgear/scene/util/SGSceneUserData.hxx>
34 #include <simgear/structure/SGBinding.hxx>
35 #include <simgear/scene/util/StateAttributeFactory.hxx>
36 #include <simgear/scene/model/SGRotateTransform.hxx>
38 using namespace simgear;
40 using OpenThreads::Mutex;
41 using OpenThreads::ScopedLock;
43 static void readOptionalBindingList(const SGPropertyNode* aNode, SGPropertyNode* modelRoot,
44 const std::string& aName, SGBindingList& aBindings)
46 const SGPropertyNode* n = aNode->getChild(aName);
48 aBindings = readBindingList(n->getChildren("binding"), modelRoot);
52 class SGPickAnimation::PickCallback : public SGPickCallback {
54 PickCallback(const SGPropertyNode* configNode,
55 SGPropertyNode* modelRoot) :
56 _repeatable(configNode->getBoolValue("repeatable", false)),
57 _repeatInterval(configNode->getDoubleValue("interval-sec", 0.1))
59 std::vector<SGPropertyNode_ptr> bindings;
61 bindings = configNode->getChildren("button");
62 for (unsigned int i = 0; i < bindings.size(); ++i) {
63 _buttons.insert( bindings[i]->getIntValue() );
66 _bindingsDown = readBindingList(configNode->getChildren("binding"), modelRoot);
67 readOptionalBindingList(configNode, modelRoot, "mod-up", _bindingsUp);
68 readOptionalBindingList(configNode, modelRoot, "hovered", _hover);
71 virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info&)
73 if (_buttons.find(button) == _buttons.end()) {
77 fireBindingList(_bindingsDown);
78 _repeatTime = -_repeatInterval; // anti-bobble: delay start of repeat
81 virtual void buttonReleased(void)
83 fireBindingList(_bindingsUp);
85 virtual void update(double dt)
91 while (_repeatInterval < _repeatTime) {
92 _repeatTime -= _repeatInterval;
93 fireBindingList(_bindingsDown);
97 virtual bool hover(const osg::Vec2d& windowPos, const Info& info)
103 // FIXME - make x,y available to the binding
104 fireBindingList(_hover);
108 SGBindingList _bindingsDown;
109 SGBindingList _bindingsUp;
110 SGBindingList _hover;
111 std::set<int> _buttons;
113 double _repeatInterval;
117 class VncVisitor : public osg::NodeVisitor {
119 VncVisitor(double x, double y, int mask) :
120 osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
121 _texX(x), _texY(y), _mask(mask), _done(false)
123 SG_LOG(SG_INPUT, SG_DEBUG, "VncVisitor constructor "
124 << x << "," << y << " mask " << mask);
127 virtual void apply(osg::Node &node)
129 // Some nodes have state sets attached
130 touchStateSet(node.getStateSet());
134 // See whether we are a geode worth exploring
135 osg::Geode *g = dynamic_cast<osg::Geode*>(&node);
137 // Go find all its drawables
138 int i = g->getNumDrawables();
140 osg::Drawable *d = g->getDrawable(i);
141 if (d) touchDrawable(*d);
143 // Out of optimism, do the same for EffectGeode
144 simgear::EffectGeode *eg = dynamic_cast<simgear::EffectGeode*>(&node);
146 for (simgear::EffectGeode::DrawablesIterator di = eg->drawablesBegin();
147 di != eg->drawablesEnd(); di++) {
150 // Now see whether the EffectGeode has an Effect
151 simgear::Effect *e = eg->getEffect();
153 touchStateSet(e->getDefaultStateSet());
157 inline void touchDrawable(osg::Drawable &d)
159 osg::StateSet *ss = d.getStateSet();
163 void touchStateSet(osg::StateSet *ss)
166 osg::StateAttribute *sa = ss->getTextureAttribute(0,
167 osg::StateAttribute::TEXTURE);
169 osg::Texture *t = sa->asTexture();
171 osg::Image *img = t->getImage(0);
174 int pixX = _texX * img->s();
175 int pixY = _texY * img->t();
176 _done = img->sendPointerEvent(pixX, pixY, _mask);
177 SG_LOG(SG_INPUT, SG_DEBUG, "VncVisitor image said " << _done
178 << " to coord " << pixX << "," << pixY);
182 inline bool wasSuccessful()
194 class SGPickAnimation::VncCallback : public SGPickCallback {
196 VncCallback(const SGPropertyNode* configNode,
197 SGPropertyNode* modelRoot,
201 SG_LOG(SG_INPUT, SG_DEBUG, "Configuring VNC callback");
202 const char *cornernames[3] = {"top-left", "top-right", "bottom-left"};
203 SGVec3d *cornercoords[3] = {&_topLeft, &_toRight, &_toDown};
204 for (int c =0; c < 3; c++) {
205 const SGPropertyNode* cornerNode = configNode->getChild(cornernames[c]);
206 *cornercoords[c] = SGVec3d(
207 cornerNode->getDoubleValue("x"),
208 cornerNode->getDoubleValue("y"),
209 cornerNode->getDoubleValue("z"));
211 _toRight -= _topLeft;
213 _squaredRight = dot(_toRight, _toRight);
214 _squaredDown = dot(_toDown, _toDown);
217 virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info& info)
219 SGVec3d loc(info.local);
220 SG_LOG(SG_INPUT, SG_DEBUG, "VNC pressed " << button << ": " << loc);
222 _x = dot(loc, _toRight) / _squaredRight;
223 _y = dot(loc, _toDown) / _squaredDown;
224 if (_x<0) _x = 0; else if (_x > 1) _x = 1;
225 if (_y<0) _y = 0; else if (_y > 1) _y = 1;
226 VncVisitor vv(_x, _y, 1 << button);
228 return vv.wasSuccessful();
231 virtual void buttonReleased(void)
233 SG_LOG(SG_INPUT, SG_DEBUG, "VNC release");
234 VncVisitor vv(_x, _y, 0);
237 virtual void update(double dt)
242 osg::ref_ptr<osg::Group> _node;
243 SGVec3d _topLeft, _toRight, _toDown;
244 double _squaredRight, _squaredDown;
247 SGPickAnimation::SGPickAnimation(const SGPropertyNode* configNode,
248 SGPropertyNode* modelRoot) :
249 SGAnimation(configNode, modelRoot)
255 OpenThreads::Mutex colorModeUniformMutex;
256 osg::ref_ptr<osg::Uniform> colorModeUniform;
261 SGPickAnimation::innerSetupPickGroup(osg::Group* commonGroup, osg::Group& parent)
263 // Contains the normal geometry that is interactive
264 osg::ref_ptr<osg::Group> normalGroup = new osg::Group;
265 normalGroup->setName("pick normal group");
266 normalGroup->addChild(commonGroup);
268 // Used to render the geometry with just yellow edges
269 osg::Group* highlightGroup = new osg::Group;
270 highlightGroup->setName("pick highlight group");
271 highlightGroup->setNodeMask(simgear::PICK_BIT);
272 highlightGroup->addChild(commonGroup);
274 // prepare a state set that paints the edges of this object yellow
275 // The material and texture attributes are set with
276 // OVERRIDE|PROTECTED in case there is a material animation on a
277 // higher node in the scene graph, which would have its material
278 // attribute set with OVERRIDE.
279 osg::StateSet* stateSet = highlightGroup->getOrCreateStateSet();
280 osg::Texture2D* white = StateAttributeFactory::instance()->getWhiteTexture();
281 stateSet->setTextureAttributeAndModes(0, white,
282 (osg::StateAttribute::ON
283 | osg::StateAttribute::OVERRIDE
284 | osg::StateAttribute::PROTECTED));
285 osg::PolygonOffset* polygonOffset = new osg::PolygonOffset;
286 polygonOffset->setFactor(-1);
287 polygonOffset->setUnits(-1);
288 stateSet->setAttribute(polygonOffset, osg::StateAttribute::OVERRIDE);
289 stateSet->setMode(GL_POLYGON_OFFSET_LINE,
290 osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
291 osg::PolygonMode* polygonMode = new osg::PolygonMode;
292 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
293 osg::PolygonMode::LINE);
294 stateSet->setAttribute(polygonMode, osg::StateAttribute::OVERRIDE);
295 osg::Material* material = new osg::Material;
296 material->setColorMode(osg::Material::OFF);
297 material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 1));
298 // XXX Alpha < 1.0 in the diffuse material value is a signal to the
299 // default shader to take the alpha value from the material value
300 // and not the glColor. In many cases the pick animation geometry is
301 // transparent, so the outline would not be visible without this hack.
302 material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, .95));
303 material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 0, 1));
304 material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, 0));
305 stateSet->setAttribute(
306 material, osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED);
307 // The default shader has a colorMode uniform that mimics the
308 // behavior of Material color mode.
309 osg::Uniform* cmUniform = 0;
311 ScopedLock<Mutex> lock(colorModeUniformMutex);
312 if (!colorModeUniform.valid()) {
313 colorModeUniform = new osg::Uniform(osg::Uniform::INT, "colorMode");
314 colorModeUniform->set(0); // MODE_OFF
315 colorModeUniform->setDataVariance(osg::Object::STATIC);
317 cmUniform = colorModeUniform.get();
319 stateSet->addUniform(cmUniform,
320 osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
322 // Only add normal geometry if configured
323 if (getConfig()->getBoolValue("visible", true))
324 parent.addChild(normalGroup.get());
325 parent.addChild(highlightGroup);
329 SGPickAnimation::createAnimationGroup(osg::Group& parent)
331 osg::Group* commonGroup = new osg::Group;
332 innerSetupPickGroup(commonGroup, parent);
333 SGSceneUserData* ud = SGSceneUserData::getOrCreateSceneUserData(commonGroup);
335 // add actions that become macro and command invocations
336 std::vector<SGPropertyNode_ptr> actions;
337 actions = getConfig()->getChildren("action");
338 for (unsigned int i = 0; i < actions.size(); ++i)
339 ud->addPickCallback(new PickCallback(actions[i], getModelRoot()));
340 // Look for the VNC sessions that want raw mouse input
341 actions = getConfig()->getChildren("vncaction");
342 for (unsigned int i = 0; i < actions.size(); ++i)
343 ud->addPickCallback(new VncCallback(actions[i], getModelRoot(),
349 ///////////////////////////////////////////////////////////////////////////
351 // insert count copies of binding list A, into the output list.
352 // effectively makes the output list fire binding A multiple times
354 static void repeatBindings(const SGBindingList& a, SGBindingList& out, int count)
357 for (int i=0; i<count; ++i) {
358 out.insert(out.end(), a.begin(), a.end());
362 static bool static_knobMouseWheelAlternateDirection = false;
364 class SGKnobAnimation::KnobPickCallback : public SGPickCallback {
366 KnobPickCallback(const SGPropertyNode* configNode,
367 SGPropertyNode* modelRoot) :
368 _direction(DIRECTION_NONE),
369 _repeatInterval(configNode->getDoubleValue("interval-sec", 0.1)),
370 _stickyShifted(false)
372 readOptionalBindingList(configNode, modelRoot, "action", _action);
373 readOptionalBindingList(configNode, modelRoot, "cw", _bindingsCW);
374 readOptionalBindingList(configNode, modelRoot, "ccw", _bindingsCCW);
376 readOptionalBindingList(configNode, modelRoot, "release", _releaseAction);
377 readOptionalBindingList(configNode, modelRoot, "hovered", _hover);
379 if (configNode->hasChild("shift-action") || configNode->hasChild("shift-cw") ||
380 configNode->hasChild("shift-ccw"))
382 // explicit shifted behaviour - just do exactly what was provided
383 readOptionalBindingList(configNode, modelRoot, "shift-action", _shiftedAction);
384 readOptionalBindingList(configNode, modelRoot, "shift-cw", _shiftedCW);
385 readOptionalBindingList(configNode, modelRoot, "shift-ccw", _shiftedCCW);
387 // default shifted behaviour - repeat normal bindings N times.
388 int shiftRepeat = configNode->getIntValue("shift-repeat", 10);
389 repeatBindings(_action, _shiftedAction, shiftRepeat);
390 repeatBindings(_bindingsCW, _shiftedCW, shiftRepeat);
391 repeatBindings(_bindingsCCW, _shiftedCCW, shiftRepeat);
392 } // of default shifted behaviour
395 virtual bool buttonPressed(int button, const osgGA::GUIEventAdapter* ea, const Info&)
397 _stickyShifted = ea->getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT;
399 // the 'be nice to Mac / laptop' users option; alt-clicking spins the
400 // opposite direction. Should make this configurable
401 if ((button == 0) && (ea->getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_ALT)) {
405 int increaseMouseWheel = static_knobMouseWheelAlternateDirection ? 3 : 4;
406 int decreaseMouseWheel = static_knobMouseWheelAlternateDirection ? 4 : 3;
408 _direction = DIRECTION_NONE;
409 if ((button == 0) || (button == increaseMouseWheel)) {
410 _direction = DIRECTION_CLOCKWISE;
411 } else if ((button == 1) || (button == decreaseMouseWheel)) {
412 _direction = DIRECTION_ANTICLOCKWISE;
417 _repeatTime = -_repeatInterval; // anti-bobble: delay start of repeat
418 fire(_stickyShifted);
422 virtual void buttonReleased(void)
424 fireBindingList(_releaseAction);
427 virtual void update(double dt)
430 while (_repeatInterval < _repeatTime) {
431 _repeatTime -= _repeatInterval;
432 fire(_stickyShifted);
433 } // of repeat iteration
436 virtual bool hover(const osg::Vec2d& windowPos, const Info& info)
438 if (_hover.empty()) {
442 // FIXME - make x,y available to the binding
443 fireBindingList(_hover);
447 void fire(bool isShifted)
449 const SGBindingList& act(isShifted ? _shiftedAction : _action);
450 const SGBindingList& cw(isShifted ? _shiftedCW : _bindingsCW);
451 const SGBindingList& ccw(isShifted ? _shiftedCCW : _bindingsCCW);
453 switch (_direction) {
454 case DIRECTION_CLOCKWISE:
455 fireBindingListWithOffset(act, 1, 1);
458 case DIRECTION_ANTICLOCKWISE:
459 fireBindingListWithOffset(act, -1, 1);
460 fireBindingList(ccw);
466 SGBindingList _action, _shiftedAction;
467 SGBindingList _releaseAction;
468 SGBindingList _bindingsCW, _shiftedCW,
469 _bindingsCCW, _shiftedCCW;
470 SGBindingList _hover;
476 DIRECTION_ANTICLOCKWISE
479 Direction _direction;
480 double _repeatInterval;
483 // FIXME - would be better to pass the current modifier state
484 // into update(), but for now let's make it sticky
488 class SGKnobAnimation::UpdateCallback : public osg::NodeCallback {
490 UpdateCallback(SGExpressiond const* animationValue) :
491 _animationValue(animationValue)
493 setName("SGKnobAnimation::UpdateCallback");
495 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
497 SGRotateTransform* transform = static_cast<SGRotateTransform*>(node);
498 transform->setAngleDeg(_animationValue->getValue());
503 SGSharedPtr<SGExpressiond const> _animationValue;
507 SGKnobAnimation::SGKnobAnimation(const SGPropertyNode* configNode,
508 SGPropertyNode* modelRoot) :
509 SGPickAnimation(configNode, modelRoot)
511 SGSharedPtr<SGExpressiond> value = read_value(configNode, modelRoot, "-deg",
512 -SGLimitsd::max(), SGLimitsd::max());
513 _animationValue = value->simplify();
516 readRotationCenterAndAxis(configNode, _center, _axis);
521 SGKnobAnimation::createAnimationGroup(osg::Group& parent)
523 SGRotateTransform* transform = new SGRotateTransform();
524 innerSetupPickGroup(transform, parent);
526 UpdateCallback* uc = new UpdateCallback(_animationValue);
527 transform->setUpdateCallback(uc);
528 transform->setCenter(_center);
529 transform->setAxis(_axis);
531 SGSceneUserData* ud = SGSceneUserData::getOrCreateSceneUserData(transform);
532 ud->setPickCallback(new KnobPickCallback(getConfig(), getModelRoot()));
537 void SGKnobAnimation::setAlternateMouseWheelDirection(bool aToggle)
539 static_knobMouseWheelAlternateDirection = aToggle;