]> git.mxchange.org Git - flightgear.git/blob - src/Input/input.cxx
30639bc19dada40f29f3f40d5dab90ab5fcc2dbe
[flightgear.git] / src / Input / input.cxx
1 // input.cxx -- handle user input from various sources.
2 //
3 // Written by David Megginson, started May 2001.
4 //
5 // Copyright (C) 2001 David Megginson, david@megginson.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #ifdef HAVE_WINDOWS_H
28 #  include <windows.h>
29 #endif
30
31 #include <simgear/compiler.h>
32
33 #include <math.h>
34 #include <ctype.h>
35
36 #include STL_FSTREAM
37 #include STL_STRING
38 #include <vector>
39
40 #include <simgear/compiler.h>
41
42 #include <simgear/constants.h>
43 #include <simgear/debug/logstream.hxx>
44 #include <simgear/props/props.hxx>
45
46 #include <Aircraft/aircraft.hxx>
47 #include <Autopilot/xmlauto.hxx>
48 #include <Cockpit/hud.hxx>
49 #include <Cockpit/panel.hxx>
50 #include <Cockpit/panel_io.hxx>
51 #include <GUI/gui.h>
52 #include <Model/panelnode.hxx>
53 #include <Scripting/NasalSys.hxx>
54
55 #include <Main/globals.hxx>
56 #include <Main/fg_props.hxx>
57
58 #include "input.hxx"
59
60 #include <Scenery/scenery.hxx>
61 #include <Main/renderer.hxx>
62 #include <simgear/math/sg_geodesy.hxx>
63
64 SG_USING_STD(ifstream);
65 SG_USING_STD(string);
66 SG_USING_STD(vector);
67
68 void mouseClickHandler(int button, int updown, int x, int y);
69 void mouseMotionHandler(int x, int y);
70 void keyHandler(int key, int keymod, int mousex, int mousey);
71
72 \f
73 ////////////////////////////////////////////////////////////////////////
74 // Local variables.
75 ////////////////////////////////////////////////////////////////////////
76
77 static FGInput * default_input = 0;
78
79 \f
80 ////////////////////////////////////////////////////////////////////////
81 // Local functions.
82 ////////////////////////////////////////////////////////////////////////
83
84 static bool
85 getModShift ()
86 {
87   return bool(fgGetKeyModifiers() & KEYMOD_SHIFT);
88 }
89
90 static bool
91 getModCtrl ()
92 {
93   return bool(fgGetKeyModifiers() & KEYMOD_CTRL);
94 }
95
96 static bool
97 getModAlt ()
98 {
99   return bool(fgGetKeyModifiers() & KEYMOD_ALT);
100 }
101
102 \f
103 ////////////////////////////////////////////////////////////////////////
104 // Implementation of FGBinding.
105 ////////////////////////////////////////////////////////////////////////
106
107 FGBinding::FGBinding ()
108   : _command(0),
109     _arg(new SGPropertyNode),
110     _setting(0)
111 {
112 }
113
114 FGBinding::FGBinding (const SGPropertyNode * node)
115   : _command(0),
116     _arg(0),
117     _setting(0)
118 {
119   read(node);
120 }
121
122 FGBinding::~FGBinding ()
123 {
124   _arg->getParent()->removeChild(_arg->getName(), _arg->getIndex(), false);
125 }
126
127 void
128 FGBinding::read (const SGPropertyNode * node)
129 {
130   const SGPropertyNode * conditionNode = node->getChild("condition");
131   if (conditionNode != 0)
132     setCondition(sgReadCondition(globals->get_props(), conditionNode));
133
134   _command_name = node->getStringValue("command", "");
135   if (_command_name.empty()) {
136     SG_LOG(SG_INPUT, SG_WARN, "No command supplied for binding.");
137     _command = 0;
138     return;
139   }
140
141   _arg = (SGPropertyNode *)node;
142   _setting = 0;
143 }
144
145 void
146 FGBinding::fire () const
147 {
148   if (test()) {
149     if (_command == 0)
150       _command = globals->get_commands()->getCommand(_command_name);
151     if (_command == 0) {
152       SG_LOG(SG_INPUT, SG_WARN, "No command attached to binding");
153     } else if (!(*_command)(_arg)) {
154       SG_LOG(SG_INPUT, SG_ALERT, "Failed to execute command "
155              << _command_name);
156     }
157   }
158 }
159
160 void
161 FGBinding::fire (double offset, double max) const
162 {
163   if (test()) {
164     _arg->setDoubleValue("offset", offset/max);
165     fire();
166   }
167 }
168
169 void
170 FGBinding::fire (double setting) const
171 {
172   if (test()) {
173                                 // A value is automatically added to
174                                 // the args
175     if (_setting == 0)          // save the setting node for efficiency
176       _setting = _arg->getChild("setting", 0, true);
177     _setting->setDoubleValue(setting);
178     fire();
179   }
180 }
181
182
183 \f
184 ////////////////////////////////////////////////////////////////////////
185 // Implementation of FGInput.
186 ////////////////////////////////////////////////////////////////////////
187
188
189 FGInput::FGInput ()
190 {
191     if (default_input == 0)
192         default_input = this;
193 }
194
195 FGInput::~FGInput ()
196 {
197     if (default_input == this)
198         default_input = 0;
199 }
200
201 void
202 FGInput::init ()
203 {
204   _init_keyboard();
205   _init_joystick();
206   _init_mouse();
207
208   fgRegisterKeyHandler(keyHandler);
209   fgRegisterMouseClickHandler(mouseClickHandler);
210   fgRegisterMouseMotionHandler(mouseMotionHandler);
211 }
212
213 void
214 FGInput::reinit ()
215 {
216     init();
217 }
218
219 void
220 FGInput::postinit ()
221 {
222   _postinit_joystick();
223 }
224
225 void
226 FGInput::bind ()
227 {
228   fgTie("/devices/status/keyboard/shift", getModShift);
229   fgTie("/devices/status/keyboard/ctrl", getModCtrl);
230   fgTie("/devices/status/keyboard/alt", getModAlt);
231 }
232
233 void
234 FGInput::unbind ()
235 {
236   fgUntie("/devices/status/keyboard/shift");
237   fgUntie("/devices/status/keyboard/ctrl");
238   fgUntie("/devices/status/keyboard/alt");
239 }
240
241 void 
242 FGInput::update (double dt)
243 {
244   _update_keyboard();
245   _update_joystick(dt);
246   _update_mouse(dt);
247 }
248
249 void
250 FGInput::suspend ()
251 {
252     // NO-OP
253 }
254
255 void
256 FGInput::resume ()
257 {
258     // NO-OP
259 }
260
261 bool
262 FGInput::is_suspended () const
263 {
264     return false;
265 }
266
267 void
268 FGInput::makeDefault (bool status)
269 {
270     if (status)
271         default_input = this;
272     else if (default_input == this)
273         default_input = 0;
274 }
275
276 void
277 FGInput::doKey (int k, int modifiers, int x, int y)
278 {
279                                 // Sanity check.
280   if (k < 0 || k >= MAX_KEYS) {
281     SG_LOG(SG_INPUT, SG_WARN, "Key value " << k << " out of range");
282     return;
283   }
284
285   button &b = _key_bindings[k];
286
287                                 // Key pressed.
288   if (!(modifiers & KEYMOD_RELEASED)) {
289     SG_LOG( SG_INPUT, SG_DEBUG, "User pressed key " << k
290             << " with modifiers " << modifiers );
291     if (!b.last_state || b.is_repeatable) {
292       const binding_list_t &bindings = _find_key_bindings(k, modifiers);
293
294       for (unsigned int i = 0; i < bindings.size(); i++)
295         bindings[i]->fire();
296       b.last_state = 1;
297     }
298   }
299                                 // Key released.
300   else {
301     SG_LOG(SG_INPUT, SG_DEBUG, "User released key " << k
302            << " with modifiers " << modifiers);
303     if (b.last_state) {
304       const binding_list_t &bindings = _find_key_bindings(k, modifiers);
305       for (unsigned int i = 0; i < bindings.size(); i++)
306         bindings[i]->fire();
307       b.last_state = 0;
308     } else {
309       if (k >= 1 && k <= 26) {
310         if (_key_bindings[k + '@'].last_state)
311           doKey(k + '@', KEYMOD_RELEASED, x, y);
312         if (_key_bindings[k + '`'].last_state)
313           doKey(k + '`', KEYMOD_RELEASED, x, y);
314       } else if (k >= 'A' && k <= 'Z') {
315         if (_key_bindings[k - '@'].last_state)
316           doKey(k - '@', KEYMOD_RELEASED, x, y);
317         if (_key_bindings[tolower(k)].last_state)
318           doKey(tolower(k), KEYMOD_RELEASED, x, y);
319       } else if (k >= 'a' && k <= 'z') {
320         if (_key_bindings[k - '`'].last_state)
321           doKey(k - '`', KEYMOD_RELEASED, x, y);
322         if (_key_bindings[toupper(k)].last_state)
323           doKey(toupper(k), KEYMOD_RELEASED, x, y);
324       }
325     }
326   }
327 }
328
329 void
330 FGInput::doMouseClick (int b, int updown, int x, int y)
331 {
332   int modifiers = fgGetKeyModifiers();
333
334   mouse &m = _mouse_bindings[0];
335   mouse_mode &mode = m.modes[m.current_mode];
336
337                                 // Let the property manager know.
338   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
339     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
340
341                                 // Pass on to PUI and the panel if
342                                 // requested, and return if one of
343                                 // them consumes the event.
344   if (mode.pass_through) {
345     if (puMouse(b, updown, x, y))
346       return;
347     else if ((globals->get_current_panel() != 0) &&
348              globals->get_current_panel()->getVisibility() &&
349              globals->get_current_panel()->doMouseAction(b, updown, x, y))
350       return;
351     else if (fgHandle3DPanelMouseEvent(b, updown, x, y))
352       return;
353     else {
354       // pui and the panel didn't want the click event so compute a
355       // terrain intersection point corresponding to the mouse click
356       // and be happy.
357       FGScenery* scenery = globals->get_scenery();
358       SGVec3d start, dir, hit;
359       if (!b && updown == MOUSE_BUTTON_DOWN
360           && FGRenderer::getPickInfo(start, dir, x, y)
361           && scenery->get_cart_ground_intersection(start, dir, hit)) {
362
363         SGGeod geod = SGGeod::fromCart(hit);
364         SGPropertyNode *c = fgGetNode("/sim/input/click", true);
365         c->setDoubleValue("longitude-deg", geod.getLongitudeDeg());
366         c->setDoubleValue("latitude-deg", geod.getLatitudeDeg());
367         c->setDoubleValue("elevation-m", geod.getElevationM());
368         c->setDoubleValue("elevation-ft", geod.getElevationFt());
369
370         fgSetBool("/sim/signals/click", 1);
371       }
372     }
373   }
374
375                                 // OK, PUI and the panel didn't want the click
376   if (b >= MAX_MOUSE_BUTTONS) {
377     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
378            << " where only " << MAX_MOUSE_BUTTONS << " expected");
379     return;
380   }
381
382   _update_button(m.modes[m.current_mode].buttons[b], modifiers, 0 != updown, x, y);
383 }
384
385 void
386 FGInput::doMouseMotion (int x, int y)
387 {
388   // Don't call fgGetKeyModifiers() here, until we are using a
389   // toolkit that supports getting the mods from outside a key
390   // callback.  Glut doesn't.
391   int modifiers = KEYMOD_NONE;
392
393   int xsize = fgGetInt("/sim/startup/xsize", 800);
394   int ysize = fgGetInt("/sim/startup/ysize", 600);
395
396   mouse &m = _mouse_bindings[0];
397
398   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
399       m.x = x;
400       m.y = y;
401       return;
402   }
403   mouse_mode &mode = m.modes[m.current_mode];
404
405                                 // Pass on to PUI if requested, and return
406                                 // if PUI consumed the event.
407   if (mode.pass_through && puMouse(x, y)) {
408       m.x = x;
409       m.y = y;
410       return;
411   }
412
413                                 // OK, PUI didn't want the event,
414                                 // so we can play with it.
415   if (x != m.x) {
416     int delta = x - m.x;
417     for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
418       mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
419   }
420   if (y != m.y) {
421     int delta = y - m.y;
422     for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
423       mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
424   }
425
426                                 // Constrain the mouse if requested
427   if (mode.constrained) {
428     bool need_warp = false;
429     if (x <= (xsize * .25) || x >= (xsize * .75)) {
430       x = int(xsize * .5);
431       need_warp = true;
432     }
433
434     if (y <= (ysize * .25) || y >= (ysize * .75)) {
435       y = int(ysize * .5);
436       need_warp = true;
437     }
438
439     if (need_warp)
440       fgWarpMouse(x, y);
441   }
442   m.x = x;
443   m.y = y;
444 }
445
446 void
447 FGInput::_init_keyboard ()
448 {
449   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing key bindings");
450   _module[0] = 0;
451   SGPropertyNode * key_nodes = fgGetNode("/input/keyboard");
452   if (key_nodes == 0) {
453     SG_LOG(SG_INPUT, SG_WARN, "No key bindings (/input/keyboard)!!");
454     key_nodes = fgGetNode("/input/keyboard", true);
455   }
456   
457   vector<SGPropertyNode_ptr> keys = key_nodes->getChildren("key");
458   for (unsigned int i = 0; i < keys.size(); i++) {
459     int index = keys[i]->getIndex();
460     SG_LOG(SG_INPUT, SG_DEBUG, "Binding key " << index);
461
462     _key_bindings[index].bindings->clear();
463     _key_bindings[index].is_repeatable = keys[i]->getBoolValue("repeatable");
464     _key_bindings[index].last_state = 0;
465     _read_bindings(keys[i], _key_bindings[index].bindings, KEYMOD_NONE);
466   }
467 }
468
469
470 void
471 FGInput::_scan_joystick_dir(SGPath *path, SGPropertyNode* node, int *index)
472 {
473   ulDir *dir = ulOpenDir(path->c_str());
474   if (dir) {
475     ulDirEnt* dent;
476     while ((dent = ulReadDir(dir)) != 0) {
477       if (dent->d_name[0] == '.')
478         continue;
479
480       SGPath p(path->str());
481       p.append(dent->d_name);
482       _scan_joystick_dir(&p, node, index);
483     }
484     ulCloseDir(dir);
485
486   } else if (path->extension() == "xml") {
487     SG_LOG(SG_INPUT, SG_DEBUG, "Reading joystick file " << path->str());
488     SGPropertyNode *n = node->getChild("js-named", (*index)++, true);
489     readProperties(path->str(), n);
490     n->setStringValue("source", path->c_str());
491   }
492 }
493
494
495 void
496 FGInput::_init_joystick ()
497 {
498   jsInit();
499                                 // TODO: zero the old bindings first.
500   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick bindings");
501   SGPropertyNode * js_nodes = fgGetNode("/input/joysticks", true);
502
503   // read all joystick xml files into /input/joysticks/js_named[1000++]
504   SGPath path(globals->get_fg_root());
505   path.append("Input/Joysticks");
506   int js_named_index = 1000;
507   _scan_joystick_dir(&path, js_nodes, &js_named_index);
508
509   // build name->node map with each <name> (reverse order)
510   map<string, SGPropertyNode_ptr> jsmap;
511   vector<SGPropertyNode_ptr> js_named = js_nodes->getChildren("js-named");
512
513   for (int k = (int)js_named.size() - 1; k >= 0; k--) {
514     SGPropertyNode *n = js_named[k];
515     vector<SGPropertyNode_ptr> names = n->getChildren("name");
516     if (names.size() && (n->getChildren("axis").size() || n->getChildren("button").size()))
517       for (unsigned int j = 0; j < names.size(); j++)
518         jsmap[names[j]->getStringValue()] = n;
519   }
520
521   // set up js[] nodes
522   for (int i = 0; i < MAX_JOYSTICKS; i++) {
523     jsJoystick * js = new jsJoystick(i);
524     _joystick_bindings[i].js = js;
525
526     if (js->notWorking()) {
527       SG_LOG(SG_INPUT, SG_DEBUG, "Joystick " << i << " not found");
528       continue;
529     }
530
531     const char * name = js->getName();
532     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
533
534     if (js_node) {
535       SG_LOG(SG_INPUT, SG_INFO, "Using existing bindings for joystick " << i);
536
537     } else {
538       SG_LOG(SG_INPUT, SG_INFO, "Looking for bindings for joystick \"" << name << '"');
539       SGPropertyNode_ptr named;
540
541       if ((named = jsmap[name])) {
542         string source = named->getStringValue("source", "user defined");
543         SG_LOG(SG_INPUT, SG_INFO, "... found joystick: " << source);
544
545       } else if ((named = jsmap["default"])) {
546         string source = named->getStringValue("source", "user defined");
547         SG_LOG(SG_INPUT, SG_INFO, "No config found for joystick \"" << name
548             << "\"\nUsing default: \"" << source << '"');
549
550       } else {
551         throw sg_throwable(string("No joystick configuration file with "
552             "<name>default</name> entry found!"));
553       }
554
555       js_node = js_nodes->getChild("js", i, true);
556       copyProperties(named, js_node);
557       js_node->setStringValue("id", name);
558     }
559   }
560
561   // get rid of unused config nodes
562   js_nodes->removeChildren("js-named", false);
563 }
564
565
566 void
567 FGInput::_postinit_joystick()
568 {
569   FGNasalSys *nasalsys = (FGNasalSys *)globals->get_subsystem("nasal");
570   SGPropertyNode *js_nodes = fgGetNode("/input/joysticks");
571
572   for (int i = 0; i < MAX_JOYSTICKS; i++) {
573     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
574     jsJoystick *js = _joystick_bindings[i].js;
575     if (!js_node || js->notWorking())
576       continue;
577
578 #ifdef WIN32
579     JOYCAPS jsCaps ;
580     joyGetDevCaps( i, &jsCaps, sizeof(jsCaps) );
581     unsigned int nbuttons = jsCaps.wNumButtons;
582     if (nbuttons > MAX_JOYSTICK_BUTTONS) nbuttons = MAX_JOYSTICK_BUTTONS;
583 #else
584     unsigned int nbuttons = MAX_JOYSTICK_BUTTONS;
585 #endif
586
587     int naxes = js->getNumAxes();
588     if (naxes > MAX_JOYSTICK_AXES) naxes = MAX_JOYSTICK_AXES;
589     _joystick_bindings[i].naxes = naxes;
590     _joystick_bindings[i].nbuttons = nbuttons;
591
592     SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick " << i);
593
594                                 // Set up range arrays
595     float minRange[MAX_JOYSTICK_AXES];
596     float maxRange[MAX_JOYSTICK_AXES];
597     float center[MAX_JOYSTICK_AXES];
598
599                                 // Initialize with default values
600     js->getMinRange(minRange);
601     js->getMaxRange(maxRange);
602     js->getCenter(center);
603
604                                 // Allocate axes and buttons
605     _joystick_bindings[i].axes = new axis[naxes];
606     _joystick_bindings[i].buttons = new button[nbuttons];
607
608     //
609     // Initialize nasal groups.
610     //
611     string init;
612     init = "this=\"" + string(js_node->getPath()) + "\"";
613     sprintf(_module, "__js%d", i);
614     nasalsys->createModule(_module, _module, init.c_str(), init.size());
615
616     vector<SGPropertyNode_ptr> nasal = js_node->getChildren("nasal");
617     unsigned int j;
618     for (j = 0; j < nasal.size(); j++) {
619       nasal[j]->setStringValue("module", _module);
620       nasalsys->handleCommand(nasal[j]);
621     }
622
623     //
624     // Initialize the axes.
625     //
626     vector<SGPropertyNode_ptr> axes = js_node->getChildren("axis");
627     size_t nb_axes = axes.size();
628     for (j = 0; j < nb_axes; j++ ) {
629       const SGPropertyNode * axis_node = axes[j];
630       const SGPropertyNode * num_node = axis_node->getChild("number");
631       int n_axis = axis_node->getIndex();
632       if (num_node != 0) {
633           n_axis = num_node->getIntValue(TGT_PLATFORM, -1);
634
635           // Silently ignore platforms that are not specified within the
636           // <number></number> section
637           if (n_axis < 0)
638              continue;
639       }
640
641       if (n_axis >= naxes) {
642           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for axis " << n_axis);
643           continue;
644       }
645       axis &a = _joystick_bindings[i].axes[n_axis];
646
647       js->setDeadBand(n_axis, axis_node->getDoubleValue("dead-band", 0.0));
648
649       a.tolerance = axis_node->getDoubleValue("tolerance", 0.002);
650       minRange[n_axis] = axis_node->getDoubleValue("min-range", minRange[n_axis]);
651       maxRange[n_axis] = axis_node->getDoubleValue("max-range", maxRange[n_axis]);
652       center[n_axis] = axis_node->getDoubleValue("center", center[n_axis]);
653
654       _read_bindings(axis_node, a.bindings, KEYMOD_NONE);
655
656       // Initialize the virtual axis buttons.
657       _init_button(axis_node->getChild("low"), a.low, "low");
658       a.low_threshold = axis_node->getDoubleValue("low-threshold", -0.9);
659
660       _init_button(axis_node->getChild("high"), a.high, "high");
661       a.high_threshold = axis_node->getDoubleValue("high-threshold", 0.9);
662       a.interval_sec = axis_node->getDoubleValue("interval-sec",0.0);
663       a.last_dt = 0.0;
664     }
665
666     //
667     // Initialize the buttons.
668     //
669     vector<SGPropertyNode_ptr> buttons = js_node->getChildren("button");
670     char buf[32];
671     for (j = 0; j < buttons.size() && j < nbuttons; j++) {
672       const SGPropertyNode * button_node = buttons[j];
673       const SGPropertyNode * num_node = button_node->getChild("number");
674       size_t n_but = button_node->getIndex();
675       if (num_node != 0) {
676           n_but = num_node->getIntValue(TGT_PLATFORM,n_but);
677       }
678
679       if (n_but >= nbuttons) {
680           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for button " << n_but);
681           continue;
682       }
683
684       sprintf(buf, "%d", n_but);
685       SG_LOG(SG_INPUT, SG_DEBUG, "Initializing button " << n_but);
686       _init_button(button_node,
687                    _joystick_bindings[i].buttons[n_but],
688                    buf);
689
690       // get interval-sec property
691       button &b = _joystick_bindings[i].buttons[n_but];
692       if (button_node != 0) {
693         b.interval_sec = button_node->getDoubleValue("interval-sec",0.0);
694         b.last_dt = 0.0;
695       }
696     }
697
698     js->setMinRange(minRange);
699     js->setMaxRange(maxRange);
700     js->setCenter(center);
701   }
702 }
703
704
705 // 
706 // Map of all known cursor names
707 // This used to contain all the Glut cursors, but those are
708 // not defined by other toolkits.  It now supports only the cursor
709 // images we actually use, in the interest of portability.  Someday,
710 // it would be cool to write an OpenGL cursor renderer, with the
711 // cursors defined as textures referenced in the property tree.  This
712 // list could then be eliminated. -Andy
713 //
714 static struct {
715   const char * name;
716   int cursor;
717 } mouse_cursor_map[] = {
718   { "none", MOUSE_CURSOR_NONE },
719   { "inherit", MOUSE_CURSOR_POINTER },
720   { "wait", MOUSE_CURSOR_WAIT },
721   { "crosshair", MOUSE_CURSOR_CROSSHAIR },
722   { "left-right", MOUSE_CURSOR_LEFTRIGHT },
723   { 0, 0 }
724 };
725
726 void
727 FGInput::_init_mouse ()
728 {
729   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
730   _module[0] = 0;
731
732   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
733   if (mouse_nodes == 0) {
734     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
735     mouse_nodes = fgGetNode("/input/mice", true);
736   }
737
738   int j;
739   for (int i = 0; i < MAX_MICE; i++) {
740     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
741     mouse &m = _mouse_bindings[i];
742
743                                 // Grab node pointers
744     char buf[64];
745     sprintf(buf, "/devices/status/mice/mouse[%d]/mode", i);
746     m.mode_node = fgGetNode(buf);
747     if (m.mode_node == NULL) {
748       m.mode_node = fgGetNode(buf, true);
749       m.mode_node->setIntValue(0);
750     }
751     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
752       sprintf(buf, "/devices/status/mice/mouse[%d]/button[%d]", i, j);
753       m.mouse_button_nodes[j] = fgGetNode(buf, true);
754       m.mouse_button_nodes[j]->setBoolValue(false);
755     }
756
757                                 // Read all the modes
758     m.nModes = mouse_node->getIntValue("mode-count", 1);
759     m.modes = new mouse_mode[m.nModes];
760
761     for (int j = 0; j < m.nModes; j++) {
762       int k;
763
764                                 // Read the mouse cursor for this mode
765       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
766       const char * cursor_name =
767         mode_node->getStringValue("cursor", "inherit");
768       m.modes[j].cursor = MOUSE_CURSOR_POINTER;
769       for (k = 0; mouse_cursor_map[k].name != 0; k++) {
770         if (!strcmp(mouse_cursor_map[k].name, cursor_name)) {
771           m.modes[j].cursor = mouse_cursor_map[k].cursor;
772           break;
773         }
774       }
775
776                                 // Read other properties for this mode
777       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
778       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
779
780                                 // Read the button bindings for this mode
781       m.modes[j].buttons = new button[MAX_MOUSE_BUTTONS];
782       char buf[32];
783       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
784         sprintf(buf, "mouse button %d", k);
785         SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse button " << k);
786         _init_button(mode_node->getChild("button", k),
787                      m.modes[j].buttons[k],
788                      buf);
789       }
790
791                                 // Read the axis bindings for this mode
792       _read_bindings(mode_node->getChild("x-axis", 0, true),
793                      m.modes[j].x_bindings,
794                      KEYMOD_NONE);
795       _read_bindings(mode_node->getChild("y-axis", 0, true),
796                      m.modes[j].y_bindings,
797                      KEYMOD_NONE);
798     }
799   }
800 }
801
802
803 void
804 FGInput::_init_button (const SGPropertyNode * node,
805                        button &b,
806                        const string name)
807 {       
808   if (node == 0) {
809     SG_LOG(SG_INPUT, SG_DEBUG, "No bindings for button " << name);
810   } else {
811     b.is_repeatable = node->getBoolValue("repeatable", b.is_repeatable);
812     
813                 // Get the bindings for the button
814     _read_bindings(node, b.bindings, KEYMOD_NONE);
815   }
816 }
817
818
819 void
820 FGInput::_update_keyboard ()
821 {
822   // no-op
823 }
824
825
826 void
827 FGInput::_update_joystick (double dt)
828 {
829   int modifiers = KEYMOD_NONE;  // FIXME: any way to get the real ones?
830   int buttons;
831   // float js_val, diff;
832   float axis_values[MAX_JOYSTICK_AXES];
833
834   int i;
835   int j;
836
837   for ( i = 0; i < MAX_JOYSTICKS; i++) {
838
839     jsJoystick * js = _joystick_bindings[i].js;
840     if (js == 0 || js->notWorking())
841       continue;
842
843     js->read(&buttons, axis_values);
844
845                                 // Fire bindings for the axes.
846     for ( j = 0; j < _joystick_bindings[i].naxes; j++) {
847       axis &a = _joystick_bindings[i].axes[j];
848       
849                                 // Do nothing if the axis position
850                                 // is unchanged; only a change in
851                                 // position fires the bindings.
852       if (fabs(axis_values[j] - a.last_value) > a.tolerance) {
853 //      SG_LOG(SG_INPUT, SG_DEBUG, "Axis " << j << " has moved");
854         a.last_value = axis_values[j];
855 //      SG_LOG(SG_INPUT, SG_DEBUG, "There are "
856 //             << a.bindings[modifiers].size() << " bindings");
857         for (unsigned int k = 0; k < a.bindings[modifiers].size(); k++)
858           a.bindings[modifiers][k]->fire(axis_values[j]);
859       }
860      
861                                 // do we have to emulate axis buttons?
862       a.last_dt += dt;
863       if(a.last_dt >= a.interval_sec) {
864         if (a.low.bindings[modifiers].size())
865           _update_button(_joystick_bindings[i].axes[j].low,
866                          modifiers,
867                          axis_values[j] < a.low_threshold,
868                          -1, -1);
869       
870         if (a.high.bindings[modifiers].size())
871           _update_button(_joystick_bindings[i].axes[j].high,
872                          modifiers,
873                          axis_values[j] > a.high_threshold,
874                          -1, -1);
875          a.last_dt -= a.interval_sec;
876       }
877     }
878
879                                 // Fire bindings for the buttons.
880     for (j = 0; j < _joystick_bindings[i].nbuttons; j++) {
881       button &b = _joystick_bindings[i].buttons[j];
882       b.last_dt += dt;
883       if(b.last_dt >= b.interval_sec) {
884         _update_button(_joystick_bindings[i].buttons[j],
885                        modifiers,
886                        (buttons & (1 << j)) > 0,
887                        -1, -1);
888         b.last_dt -= b.interval_sec;
889       }
890     }
891   }
892 }
893
894 void
895 FGInput::_update_mouse ( double dt )
896 {
897   mouse &m = _mouse_bindings[0];
898   int mode =  m.mode_node->getIntValue();
899   if (mode != m.current_mode) {
900     m.current_mode = mode;
901     m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
902     if (mode >= 0 && mode < m.nModes) {
903       fgSetMouseCursor(m.modes[mode].cursor);
904       m.x = fgGetInt("/sim/startup/xsize", 800) / 2;
905       m.y = fgGetInt("/sim/startup/ysize", 600) / 2;
906       fgWarpMouse(m.x, m.y);
907     } else {
908       SG_LOG(SG_INPUT, SG_DEBUG, "Mouse mode " << mode << " out of range");
909       fgSetMouseCursor(MOUSE_CURSOR_POINTER);
910     }
911   }
912
913   if ( fgGetBool( "/sim/mouse/hide-cursor", true ) ) {
914       if ( m.x != m.save_x || m.y != m.save_y ) {
915           m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
916           fgSetMouseCursor(m.modes[mode].cursor);
917       } else {
918           m.timeout -= dt;
919           if ( m.timeout <= 0.0 ) {
920               fgSetMouseCursor(MOUSE_CURSOR_NONE);
921               m.timeout = 0.0;
922           }
923       }
924       m.save_x = m.x;
925       m.save_y = m.y;
926   }
927 }
928
929 void
930 FGInput::_update_button (button &b, int modifiers, bool pressed,
931                          int x, int y)
932 {
933   if (pressed) {
934                                 // The press event may be repeated.
935     if (!b.last_state || b.is_repeatable) {
936       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been pressed" );
937       for (unsigned int k = 0; k < b.bindings[modifiers].size(); k++)
938         b.bindings[modifiers][k]->fire(x, y);
939     }
940   } else {
941                                 // The release event is never repeated.
942     if (b.last_state) {
943       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been released" );
944       for (unsigned int k = 0; k < b.bindings[modifiers|KEYMOD_RELEASED].size(); k++)
945         b.bindings[modifiers|KEYMOD_RELEASED][k]->fire(x, y);
946     }
947   }
948           
949   b.last_state = pressed;
950 }  
951
952
953 void
954 FGInput::_read_bindings (const SGPropertyNode * node, 
955                          binding_list_t * binding_list,
956                          int modifiers)
957 {
958   SG_LOG(SG_INPUT, SG_DEBUG, "Reading all bindings");
959   vector<SGPropertyNode_ptr> bindings = node->getChildren("binding");
960   for (unsigned int i = 0; i < bindings.size(); i++) {
961     const char *cmd = bindings[i]->getStringValue("command");
962     SG_LOG(SG_INPUT, SG_DEBUG, "Reading binding " << cmd);
963
964     if (!strcmp(cmd, "nasal") && _module[0])
965       bindings[i]->setStringValue("module", _module);
966     binding_list[modifiers].push_back(new FGBinding(bindings[i]));
967   }
968
969                                 // Read nested bindings for modifiers
970   if (node->getChild("mod-up") != 0)
971     _read_bindings(node->getChild("mod-up"), binding_list,
972                    modifiers|KEYMOD_RELEASED);
973
974   if (node->getChild("mod-shift") != 0)
975     _read_bindings(node->getChild("mod-shift"), binding_list,
976                    modifiers|KEYMOD_SHIFT);
977
978   if (node->getChild("mod-ctrl") != 0)
979     _read_bindings(node->getChild("mod-ctrl"), binding_list,
980                    modifiers|KEYMOD_CTRL);
981
982   if (node->getChild("mod-alt") != 0)
983     _read_bindings(node->getChild("mod-alt"), binding_list,
984                    modifiers|KEYMOD_ALT);
985 }
986
987
988 const vector<FGBinding *> &
989 FGInput::_find_key_bindings (unsigned int k, int modifiers)
990 {
991   unsigned char kc = (unsigned char)k;
992   button &b = _key_bindings[k];
993
994                                 // Try it straight, first.
995   if (b.bindings[modifiers].size() > 0)
996     return b.bindings[modifiers];
997
998                                 // Alt-Gr is CTRL+ALT
999   else if (modifiers&(KEYMOD_CTRL|KEYMOD_ALT))
1000     return _find_key_bindings(k, modifiers&~(KEYMOD_CTRL|KEYMOD_ALT));
1001
1002                                 // Try removing the control modifier
1003                                 // for control keys.
1004   else if ((modifiers&KEYMOD_CTRL) && iscntrl(kc))
1005     return _find_key_bindings(k, modifiers&~KEYMOD_CTRL);
1006
1007                                 // Try removing shift modifier 
1008                                 // for upper case or any punctuation
1009                                 // (since different keyboards will
1010                                 // shift different punctuation types)
1011   else if ((modifiers&KEYMOD_SHIFT) && (isupper(kc) || ispunct(kc)))
1012     return _find_key_bindings(k, modifiers&~KEYMOD_SHIFT);
1013
1014                                 // Try removing alt modifier for
1015                                 // high-bit characters.
1016   else if ((modifiers&KEYMOD_ALT) && k >= 128 && k < 256)
1017     return _find_key_bindings(k, modifiers&~KEYMOD_ALT);
1018
1019                                 // Give up and return the empty vector.
1020   else
1021     return b.bindings[modifiers];
1022 }
1023
1024
1025 \f
1026 ////////////////////////////////////////////////////////////////////////
1027 // Implementation of FGInput::button.
1028 ////////////////////////////////////////////////////////////////////////
1029
1030 FGInput::button::button ()
1031   : is_repeatable(false),
1032     interval_sec(0),
1033     last_dt(0),
1034     last_state(0)
1035 {
1036 }
1037
1038 FGInput::button::~button ()
1039 {
1040                                 // FIXME: memory leak
1041 //   for (int i = 0; i < KEYMOD_MAX; i++)
1042 //     for (int j = 0; i < bindings[i].size(); j++)
1043 //       delete bindings[i][j];
1044 }
1045
1046
1047 \f
1048 ////////////////////////////////////////////////////////////////////////
1049 // Implementation of FGInput::axis.
1050 ////////////////////////////////////////////////////////////////////////
1051
1052 FGInput::axis::axis ()
1053   : last_value(9999999),
1054     tolerance(0.002),
1055     low_threshold(-0.9),
1056     high_threshold(0.9),
1057     interval_sec(0),
1058     last_dt(0)
1059 {
1060 }
1061
1062 FGInput::axis::~axis ()
1063 {
1064 //   for (int i = 0; i < KEYMOD_MAX; i++)
1065 //     for (int j = 0; i < bindings[i].size(); j++)
1066 //       delete bindings[i][j];
1067 }
1068
1069
1070 \f
1071 ////////////////////////////////////////////////////////////////////////
1072 // Implementation of FGInput::joystick.
1073 ////////////////////////////////////////////////////////////////////////
1074
1075 FGInput::joystick::joystick ()
1076   : jsnum(0),
1077     js(0),
1078     naxes(0),
1079     nbuttons(0),
1080     axes(0),
1081     buttons(0)
1082 {
1083 }
1084
1085 FGInput::joystick::~joystick ()
1086 {
1087 //   delete js;
1088   delete[] axes;
1089   delete[] buttons;
1090 }
1091
1092
1093 \f
1094 ////////////////////////////////////////////////////////////////////////
1095 // Implementation of FGInput::mouse_mode
1096 ////////////////////////////////////////////////////////////////////////
1097
1098 FGInput::mouse_mode::mouse_mode ()
1099   : cursor(MOUSE_CURSOR_POINTER),
1100     constrained(false),
1101     pass_through(false),
1102     buttons(0)
1103 {
1104 }
1105
1106 FGInput::mouse_mode::~mouse_mode ()
1107 {
1108                                 // FIXME: memory leak
1109 //   for (int i = 0; i < KEYMOD_MAX; i++) {
1110 //     int j;
1111 //     for (j = 0; i < x_bindings[i].size(); j++)
1112 //       delete bindings[i][j];
1113 //     for (j = 0; j < y_bindings[i].size(); j++)
1114 //       delete bindings[i][j];
1115 //   }
1116   delete [] buttons;
1117 }
1118
1119
1120 \f
1121 ////////////////////////////////////////////////////////////////////////
1122 // Implementation of FGInput::mouse
1123 ////////////////////////////////////////////////////////////////////////
1124
1125 FGInput::mouse::mouse ()
1126   : x(-1),
1127     y(-1),
1128     nModes(1),
1129     current_mode(0),
1130     modes(0)
1131 {
1132 }
1133
1134 FGInput::mouse::~mouse ()
1135 {
1136   delete [] modes;
1137 }
1138
1139 ////////////////////////////////////////////////////////////////////////
1140 // Implementation of OS callbacks.
1141 ////////////////////////////////////////////////////////////////////////
1142
1143 void keyHandler(int key, int keymod, int mousex, int mousey)
1144 {
1145     if((keymod & KEYMOD_RELEASED) == 0)
1146         if(puKeyboard(key, PU_DOWN))
1147             return;
1148
1149     if(default_input)
1150         default_input->doKey(key, keymod, mousex, mousey);
1151 }
1152
1153 void mouseClickHandler(int button, int updown, int x, int y)
1154 {
1155     if(default_input)
1156         default_input->doMouseClick(button, updown, x, y);
1157 }
1158
1159 void mouseMotionHandler(int x, int y)
1160 {
1161     if (default_input != 0)
1162         default_input->doMouseMotion(x, y);
1163 }