Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/core/InputManager.cc @ 1494

Last change on this file since 1494 was 1494, checked in by rgrieder, 16 years ago
  • set the svn:eol-style property to all files so, that where ever you check out, you'll get the right line endings (had to change every file with mixed endings to windows in order to set the property)
  • Property svn:eol-style set to native
File size: 48.9 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30  @file
31  @brief Implementation of the InputManager that captures all the input from OIS
32         and redirects it to handlers.
33 */
34
35#include "InputManager.h"
36#include "util/Convert.h"
37#include "CoreIncludes.h"
38#include "ConfigValueIncludes.h"
39#include "Debug.h"
40#include "InputBuffer.h"
41#include "KeyBinder.h"
42#include "CommandExecutor.h"
43#include "ConsoleCommand.h"#include "Shell.h"
44namespace orxonox
45{
46  SetConsoleCommandShortcut(InputManager, keyBind);
47  SetConsoleCommandShortcut(InputManager, storeKeyStroke);
48  SetConsoleCommandShortcut(InputManager, calibrate);
49
50  // ###############################
51  // ###    Internal Methods     ###
52  // ###############################
53  // ###############################
54
55  /**
56    @brief Constructor only sets member fields to initial zero values
57           and registers the class in the class hierarchy.
58  */
59  InputManager::InputManager() :
60      inputSystem_(0), keyboard_(0), mouse_(0),
61      joySticksSize_(0),
62      keyBinder_(0), keyDetector_(0), buffer_(0), calibratorCallback_(0),
63      state_(IS_UNINIT), stateRequest_(IS_UNINIT), savedState_(IS_UNINIT),
64      keyboardModifiers_(0)
65  {
66    RegisterObject(InputManager);
67  }
68
69  /**
70    @brief The one instance of the InputManager is stored in this function.
71    @return A reference to the only instance of the InputManager
72  */
73  InputManager& InputManager::_getSingleton()
74  {
75    static InputManager theOnlyInstance;
76    return theOnlyInstance;
77  }
78
79  /**
80    @brief Destructor only called at the end of the program, after main.
81  */
82  InputManager::~InputManager()
83  {
84    _destroy();
85  }
86
87  /**
88    @brief Creates the OIS::InputMananger, the keyboard, the mouse and
89           the joysticks and assigns the key bindings.
90    @param windowHnd The window handle of the render window
91    @param windowWidth The width of the render window
92    @param windowHeight The height of the render window
93  */
94  bool InputManager::_initialise(const size_t windowHnd, int windowWidth, int windowHeight,
95        bool createKeyboard, bool createMouse, bool createJoySticks)
96  {
97    if (state_ == IS_UNINIT)
98    {
99      CCOUT(3) << "Initialising Input System..." << std::endl;
100      CCOUT(ORX_DEBUG) << "Initialising OIS components..." << std::endl;
101
102      OIS::ParamList paramList;
103      std::ostringstream windowHndStr;
104
105      // Fill parameter list
106      windowHndStr << (unsigned int)windowHnd;
107      paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
108      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
109      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
110//#if defined OIS_LINUX_PLATFORM
111//      paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
112//#endif
113
114      try
115      {
116        inputSystem_ = OIS::InputManager::createInputSystem(paramList);
117        CCOUT(ORX_DEBUG) << "Created OIS input system" << std::endl;
118      }
119      catch (OIS::Exception ex)
120      {
121        CCOUT(ORX_ERROR) << "Error: Failed creating an OIS input system."
122            << "OIS message: \"" << ex.eText << "\"" << std::endl;
123        inputSystem_ = 0;
124        return false;
125      }
126
127      if (createKeyboard)
128        _initialiseKeyboard();
129
130      if (createMouse)
131        _initialiseMouse();
132
133      if (createJoySticks)
134        _initialiseJoySticks();
135
136      // Set mouse/joystick region
137      if (mouse_)
138      {
139        //// hack the mouse position
140        //((OIS::MouseState&)mouse_->getMouseState()).X.abs = windowWidth/2;
141        //((OIS::MouseState&)mouse_->getMouseState()).Y.abs = windowHeight/2;
142        setWindowExtents(windowWidth, windowHeight);
143      }
144
145      state_ = IS_NONE;
146      CCOUT(ORX_DEBUG) << "Initialising OIS components done." << std::endl;
147
148      // InputManager holds the input buffer --> create one and add it.
149      buffer_ = new InputBuffer();
150      addKeyHandler(buffer_, "buffer");
151      Shell::getInstance().setInputBuffer(buffer_);
152      keyBinder_ = new KeyBinder();
153      keyBinder_->loadBindings();
154      addKeyHandler(keyBinder_, "keybinder");
155      addMouseHandler(keyBinder_, "keybinder");
156      addJoyStickHandler(keyBinder_, "keybinder");
157
158      keyDetector_ = new KeyDetector();
159      keyDetector_->loadBindings();
160      addKeyHandler(keyDetector_, "keydetector");
161      addMouseHandler(keyDetector_, "keydetector");
162      addJoyStickHandler(keyDetector_, "keydetector");
163
164      calibratorCallback_ = new CalibratorCallback();
165      addKeyHandler(calibratorCallback_, "calibratorcallback");
166
167      setConfigValues();
168
169      CCOUT(ORX_DEBUG) << "Initialising complete." << std::endl;
170    }
171    else
172    {
173      CCOUT(ORX_WARNING) << "Warning: OIS compoments already initialised, skipping" << std::endl;
174    }
175    return true;
176  }
177
178  /**
179    @brief Creates a keyboard and sets the event handler.
180    @return False if keyboard stays uninitialised, true otherwise.
181  */
182  bool InputManager::_initialiseKeyboard()
183  {
184    if (keyboard_ != 0)
185    {
186      CCOUT(2) << "Warning: Keyboard already initialised, skipping." << std::endl;
187      return true;
188    }
189    try
190    {
191      if (inputSystem_->getNumberOfDevices(OIS::OISKeyboard) > 0)
192      {
193        keyboard_ = (OIS::Keyboard*)inputSystem_->createInputObject(OIS::OISKeyboard, true);
194        // register our listener in OIS.
195        keyboard_->setEventCallback(this);
196        // note: OIS will not detect keys that have already been down when the keyboard was created.        CCOUT(ORX_DEBUG) << "Created OIS keyboard" << std::endl;
197        return true;
198      }
199      else
200      {
201        CCOUT(ORX_WARNING) << "Warning: No keyboard found!" << std::endl;
202        return false;
203      }
204    }
205    catch (OIS::Exception ex)
206    {
207      // TODO: Test this output regarding formatting
208      CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS keyboard\n"
209          << "OIS error message: \"" << ex.eText << "\"" << std::endl;
210      keyboard_ = 0;
211      return false;
212    }
213  }
214
215  /**
216    @brief Creates a mouse and sets the event handler.
217    @return False if mouse stays uninitialised, true otherwise.
218  */
219  bool InputManager::_initialiseMouse()
220  {
221    if (mouse_ != 0)
222    {
223      CCOUT(2) << "Warning: Mouse already initialised, skipping." << std::endl;
224      return true;
225    }
226    try
227    {
228      if (inputSystem_->getNumberOfDevices(OIS::OISMouse) > 0)
229      {
230        mouse_ = static_cast<OIS::Mouse*>(inputSystem_->createInputObject(OIS::OISMouse, true));
231        // register our listener in OIS.
232        mouse_->setEventCallback(this);
233        CCOUT(ORX_DEBUG) << "Created OIS mouse" << std::endl;
234        return true;
235      }
236      else
237      {
238        CCOUT(ORX_WARNING) << "Warning: No mouse found!" << std::endl;
239        return false;
240      }
241    }
242    catch (OIS::Exception ex)
243    {
244      CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS mouse\n"
245          << "OIS error message: \"" << ex.eText << "\"" << std::endl;
246      mouse_ = 0;
247      return false;
248    }
249  }
250
251  /**
252    @brief Creates all joy sticks and sets the event handler.
253    @return False joy stick stay uninitialised, true otherwise.
254  */
255  bool InputManager::_initialiseJoySticks()
256  {
257    if (joySticksSize_ > 0)
258    {
259      CCOUT(2) << "Warning: Joy sticks already initialised, skipping." << std::endl;
260      return true;
261    }
262    bool success = false;
263    if (inputSystem_->getNumberOfDevices(OIS::OISJoyStick) > 0)
264    {
265      for (int i = 0; i < inputSystem_->getNumberOfDevices(OIS::OISJoyStick); i++)
266      {
267        try
268        {
269          OIS::JoyStick* stig = static_cast<OIS::JoyStick*>(inputSystem_->createInputObject(OIS::OISJoyStick, true));
270          joySticks_.push_back(stig);
271          // register our listener in OIS.
272          stig->setEventCallback(this);
273          CCOUT(ORX_DEBUG) << "Created OIS joy stick with ID " << stig->getID() << std::endl;
274          success = true;
275        }
276        catch (OIS::Exception ex)
277        {
278          CCOUT(ORX_WARNING) << "Warning: Failed to create OIS joy number" << i << "\n"
279              << "OIS error message: \"" << ex.eText << "\"" << std::endl;
280        }
281      }
282    }
283    else
284    {
285      CCOUT(ORX_WARNING) << "Warning: Joy stick support requested, but no joy stick was found" << std::endl;
286      return false;
287    }
288    joySticksSize_ = joySticks_.size();
289    activeJoyStickHandlers_.resize(joySticksSize_);
290    joyStickButtonsDown_.resize(joySticksSize_);
291    povStates_.resize(joySticksSize_);
292    sliderStates_.resize(joySticksSize_);
293    joySticksCalibration_.resize(joySticksSize_);
294    for (unsigned int iJoyStick = 0; iJoyStick < joySticksSize_; iJoyStick++)
295    {
296      // reset the calibration with default values
297      for (unsigned int i = 0; i < 24; i++)
298      {
299        joySticksCalibration_[iJoyStick].negativeCoeff[i] = 1.0f/32767.0f;
300        joySticksCalibration_[iJoyStick].positiveCoeff[i] = 1.0f/32768.0f;
301        joySticksCalibration_[iJoyStick].zeroStates[i] = 0;
302      }
303    }
304    return success;
305  }
306
307  /**
308    @brief Sets the configurable values. Use keybindings.ini as file..
309  */
310  void InputManager::setConfigValues()
311  {
312    if (joySticksSize_)    {      std::vector<MultiTypeMath> coeffPos;
313      std::vector<MultiTypeMath> coeffNeg;
314      std::vector<MultiTypeMath> zero;
315      coeffPos.resize(24);
316      coeffNeg.resize(24);
317      zero.resize(24);
318      for (unsigned int i = 0; i < 24; i++)
319      {
320        coeffPos[i] =  1.0f/32767.0f;
321        coeffNeg[i] =  1.0f/32768.0f;
322        zero[i]     =  0;
323      }
324
325      ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");      if (!cont)      {          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffPos", coeffPos);          getIdentifier()->addConfigValueContainer("CoeffPos", cont);      }      cont->getValue(&coeffPos);      cont = getIdentifier()->getConfigValueContainer("CoeffNeg");      if (!cont)      {          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffNeg", coeffNeg);          getIdentifier()->addConfigValueContainer("CoeffNeg", cont);      }      cont->getValue(&coeffNeg);      cont = getIdentifier()->getConfigValueContainer("Zero");      if (!cont)      {          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "Zero", zero);          getIdentifier()->addConfigValueContainer("Zero", cont);      }      cont->getValue(&zero);      // copy values to our own variables      for (unsigned int i = 0; i < 24; i++)      {        joySticksCalibration_[0].positiveCoeff[i] = coeffPos[i];        joySticksCalibration_[0].negativeCoeff[i] = coeffNeg[i];        joySticksCalibration_[0].zeroStates[i]    = zero[i];      }    }  }
326
327  /**
328    @brief Destroys all the created input devices and sets the InputManager to construction state.
329  */
330  void InputManager::_destroy()
331  {
332    if (state_ != IS_UNINIT)
333    {
334      CCOUT(ORX_DEBUG) << "Destroying ..." << std::endl;
335
336      if (buffer_)
337        delete buffer_;
338
339      if (keyBinder_)
340        delete keyBinder_;
341
342      if (keyDetector_)
343        delete keyDetector_;
344
345      if (calibratorCallback_)
346        delete calibratorCallback_;
347
348      keyHandlers_.clear();
349      mouseHandlers_.clear();
350      joyStickHandlers_.clear();
351
352      _destroyKeyboard();
353      _destroyMouse();
354      _destroyJoySticks();
355
356      activeHandlers_.clear();
357
358      // inputSystem_ can never be 0, or else the code is mistaken
359      OIS::InputManager::destroyInputSystem(inputSystem_);
360      inputSystem_ = 0;
361
362      state_ = IS_UNINIT;
363      CCOUT(ORX_DEBUG) << "Destroying done." << std::endl;
364    }
365  }
366
367  /**
368    @brief Destroys the keyboard and sets it to 0.
369  */
370  void InputManager::_destroyKeyboard()
371  {
372    if (keyboard_)
373      // inputSystem_ can never be 0, or else the code is mistaken
374      inputSystem_->destroyInputObject(keyboard_);
375    keyboard_ = 0;
376    activeKeyHandlers_.clear();
377    keysDown_.clear();
378    CCOUT(ORX_DEBUG) << "Keyboard destroyed." << std::endl;
379  }
380
381  /**
382    @brief Destroys the mouse and sets it to 0.
383  */
384  void InputManager::_destroyMouse()
385  {
386    if (mouse_)
387      // inputSystem_ can never be 0, or else the code is mistaken
388      inputSystem_->destroyInputObject(mouse_);
389    mouse_ = 0;
390    activeMouseHandlers_.clear();
391    mouseButtonsDown_.clear();
392    CCOUT(ORX_DEBUG) << "Mouse destroyed." << std::endl;
393  }
394
395  /**
396    @brief Destroys all the joy sticks and resizes the lists to 0.
397  */
398  void InputManager::_destroyJoySticks()
399  {
400    if (joySticksSize_ > 0)
401    {
402      // note: inputSystem_ can never be 0, or else the code is mistaken
403      for (unsigned int i = 0; i < joySticksSize_; i++)
404        if (joySticks_[i] != 0)
405          inputSystem_->destroyInputObject(joySticks_[i]);
406
407      joySticks_.clear();
408      joySticksSize_ = 0;
409      activeJoyStickHandlers_.clear();
410      joyStickButtonsDown_.clear();
411      povStates_.clear();
412      sliderStates_.clear();
413      joySticksCalibration_.clear();
414    }
415    CCOUT(ORX_DEBUG) << "Joy sticks destroyed." << std::endl;
416  }
417
418  void InputManager::_saveState()
419  {
420    savedHandlers_.activeHandlers_ = activeHandlers_;
421    savedHandlers_.activeJoyStickHandlers_ = activeJoyStickHandlers_;
422    savedHandlers_.activeKeyHandlers_ = activeKeyHandlers_;
423    savedHandlers_.activeMouseHandlers_ = activeMouseHandlers_;
424  }
425
426  void InputManager::_restoreState()
427  {
428    activeHandlers_ = savedHandlers_.activeHandlers_;
429    activeJoyStickHandlers_ = savedHandlers_.activeJoyStickHandlers_;
430    activeKeyHandlers_ = savedHandlers_.activeKeyHandlers_;
431    activeMouseHandlers_ = savedHandlers_.activeMouseHandlers_;
432  }
433
434  void InputManager::_updateTickables()
435  {
436    // we can use a map to have a list of unique pointers (an object can implement all 3 handlers)
437    std::map<InputTickable*, HandlerState> tempSet;
438    for (unsigned int iHandler = 0; iHandler < activeKeyHandlers_.size(); iHandler++)
439      tempSet[activeKeyHandlers_[iHandler]].joyStick = true;
440    for (unsigned int iHandler = 0; iHandler < activeMouseHandlers_.size(); iHandler++)
441      tempSet[activeMouseHandlers_[iHandler]].mouse = true;
442    for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
443      for (unsigned int iHandler = 0; iHandler  < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
444        tempSet[activeJoyStickHandlers_[iJoyStick][iHandler]].joyStick = true;
445
446    // copy the content of the map back to the actual vector
447    activeHandlers_.clear();
448    for (std::map<InputTickable*, HandlerState>::const_iterator itHandler = tempSet.begin();
449        itHandler != tempSet.end(); itHandler++)
450      activeHandlers_.push_back(std::pair<InputTickable*, HandlerState>((*itHandler).first, (*itHandler).second));
451  }
452
453
454  // #################################
455  // ### Private Interface Methods ###
456  // #################################
457  // #################################
458
459  /**
460    @brief Updates the InputManager. Tick is called by Orxonox.
461    @param dt Delta time
462  */
463  void InputManager::tick(float dt)
464  {
465    if (state_ == IS_UNINIT)
466      return;
467
468    if (state_ != stateRequest_)
469    {
470      InputState sr = stateRequest_;
471      switch (sr)
472      {
473      case IS_NORMAL:
474        activeKeyHandlers_.clear();
475        activeMouseHandlers_.clear();
476        for (unsigned int i = 0; i < joySticksSize_; i++)
477          activeJoyStickHandlers_[i].clear();
478
479        // normal play mode
480        // note: we assume that the handlers exist since otherwise, something's wrong anyway.
481        enableKeyHandler("keybinder");
482        enableMouseHandler("keybinder");
483        enableJoyStickHandler("keybinder", 0);
484        stateRequest_ = IS_NORMAL;
485        state_ = IS_NORMAL;
486        break;
487
488      case IS_GUI:
489        state_ = IS_GUI;
490        break;
491
492      case IS_CONSOLE:
493        activeKeyHandlers_.clear();
494        activeMouseHandlers_.clear();
495        for (unsigned int i = 0; i < joySticksSize_; i++)
496          activeJoyStickHandlers_[i].clear();
497
498        enableMouseHandler("keybinder");
499        enableJoyStickHandler("keybinder", 0);
500        enableKeyHandler("buffer");
501        stateRequest_ = IS_CONSOLE;
502        state_ = IS_CONSOLE;
503        break;
504
505      case IS_DETECT:
506        savedState_ = state_;
507        _saveState();
508
509        activeKeyHandlers_.clear();
510        activeMouseHandlers_.clear();
511        for (unsigned int i = 0; i < joySticksSize_; i++)
512          activeJoyStickHandlers_[i].clear();
513
514        enableKeyHandler("keydetector");
515        enableMouseHandler("keydetector");
516        enableJoyStickHandler("keydetector", 0);
517
518        stateRequest_ = IS_DETECT;
519        state_ = IS_DETECT;
520        break;
521
522      case IS_NODETECT:
523        _restoreState();
524        keysDown_.clear();
525        mouseButtonsDown_.clear();
526        joyStickButtonsDown_[0].clear();
527        state_ = IS_NODETECT;
528        stateRequest_ = savedState_;
529        break;
530
531      case IS_CALIBRATE:
532        if (joySticksSize_)
533        {
534          savedState_ = _getSingleton().state_;
535          for (unsigned int i = 0; i < 24; i++)
536          {
537            marginalsMax_[i] = INT_MIN;
538            marginalsMin_[i] = INT_MAX;
539          }
540          COUT(0) << "Move all joy stick axes in all directions a few times. "
541            << "Then put all axes in zero state and hit enter." << std::endl;
542
543          savedState_ = state_;
544          _saveState();
545
546          activeKeyHandlers_.clear();
547          activeMouseHandlers_.clear();
548          for (unsigned int i = 0; i < joySticksSize_; i++)
549            activeJoyStickHandlers_[i].clear();
550
551          enableKeyHandler("calibratorcallback");
552          stateRequest_ = IS_CALIBRATE;
553          state_ = IS_CALIBRATE;
554        }
555        else
556        {
557          COUT(3) << "Connot calibrate, no joy stick found!" << std::endl;
558          stateRequest_ = state_;
559        }
560        break;
561
562      case IS_NOCALIBRATE:
563        _completeCalibration();
564        _restoreState();
565        keyBinder_->resetJoyStickAxes();
566        state_ = IS_NOCALIBRATE;
567        stateRequest_ = savedState_;
568        break;
569
570      case IS_NONE:
571        activeKeyHandlers_.clear();
572        activeMouseHandlers_.clear();
573        for (unsigned int i = 0; i < joySticksSize_; i++)
574          activeJoyStickHandlers_[i].clear();
575        state_ = IS_NONE;
576
577      default:
578        break;
579      }
580    }
581
582    // Capture all the input. This calls the event handlers in InputManager.
583    if (mouse_)
584      mouse_->capture();
585    if (keyboard_)
586      keyboard_->capture();
587    for (unsigned  int i = 0; i < joySticksSize_; i++)
588      joySticks_[i]->capture();
589
590    if (state_ != IS_CALIBRATE)
591    {
592      // call all the handlers for the held key events
593      for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
594        for (unsigned int iHandler = 0; iHandler < activeKeyHandlers_.size(); iHandler++)
595          activeKeyHandlers_[iHandler]->keyHeld(KeyEvent(keysDown_[iKey], keyboardModifiers_));
596
597      // call all the handlers for the held mouse button events
598      for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
599        for (unsigned int iHandler = 0; iHandler < activeMouseHandlers_.size(); iHandler++)
600          activeMouseHandlers_[iHandler]->mouseButtonHeld(mouseButtonsDown_[iButton]);
601
602      // call all the handlers for the held joy stick button events
603      for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
604        for (unsigned int iButton   = 0; iButton   < joyStickButtonsDown_[iJoyStick].size(); iButton++)
605          for (unsigned int iHandler = 0; iHandler  < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
606            activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonHeld(iJoyStick, joyStickButtonsDown_[iJoyStick][iButton]);
607    }
608
609    // call the ticks for the handlers (need to be treated specially)
610    for (unsigned int iHandler = 0; iHandler < activeHandlers_.size(); iHandler++)
611      activeHandlers_[iHandler].first->tickInput(dt, activeHandlers_[iHandler].second);
612  }
613
614  void InputManager::_completeCalibration()
615  {
616    for (unsigned int i = 0; i < 24; i++)
617    {
618      // positive coefficient
619      if (marginalsMax_[i] == INT_MIN)
620        marginalsMax_[i] =  32767;
621      // coefficients
622      if (marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i])
623        joySticksCalibration_[0].positiveCoeff[i] =  1.0f/(marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i]);
624      else
625        joySticksCalibration_[0].positiveCoeff[i] =  1.0f;
626      // config value
627      ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");      assert(cont);      cont->set(i, joySticksCalibration_[0].positiveCoeff[i]);      // negative coefficient
628      if (marginalsMin_[i] == INT_MAX)
629        marginalsMin_[i] = -32768;
630      // coefficients
631      if (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i])
632        joySticksCalibration_[0].negativeCoeff[i] = -1.0f/(marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i]);      else        joySticksCalibration_[0].negativeCoeff[i] =  1.0f;      // config value
633      cont = getIdentifier()->getConfigValueContainer("CoeffNeg");      assert(cont);      cont->set(i, joySticksCalibration_[0].negativeCoeff[i]);      // zero states
634      if (i < 8)
635      {
636        if (!(i & 1))
637          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abX;
638        else
639          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abY;
640      }
641      else
642      {
643        if (i - 8 < joySticks_[0]->getJoyStickState().mAxes.size())
644          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mAxes[i - 8].abs;
645        else
646          joySticksCalibration_[0].zeroStates[i] = 0;
647      }
648      // config value
649      cont = getIdentifier()->getConfigValueContainer("Zero");      assert(cont);      cont->set(i, joySticksCalibration_[0].zeroStates[i]);    }
650  }
651
652  // ###### Key Events ######
653
654  /**
655    @brief Event handler for the keyPressed Event.
656    @param e Event information
657  */
658  bool InputManager::keyPressed(const OIS::KeyEvent &e)
659  {
660    // check whether the key already is in the list (can happen when focus was lost)
661    unsigned int iKey = 0;
662    while (iKey < keysDown_.size() && keysDown_[iKey].key != (KeyCode::Enum)e.key)
663      iKey++;
664    if (iKey == keysDown_.size())
665      keysDown_.push_back(Key(e));
666
667    // update modifiers
668    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
669      keyboardModifiers_ |= KeyboardModifier::Alt;   // alt key
670    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
671      keyboardModifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
672    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
673      keyboardModifiers_ |= KeyboardModifier::Shift; // shift key
674
675    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
676      activeKeyHandlers_[i]->keyPressed(KeyEvent(e, keyboardModifiers_));
677
678    return true;
679  }
680
681  /**
682    @brief Event handler for the keyReleased Event.
683    @param e Event information
684  */
685  bool InputManager::keyReleased(const OIS::KeyEvent &e)
686  {
687    // remove the key from the keysDown_ list
688    for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
689    {
690      if (keysDown_[iKey].key == (KeyCode::Enum)e.key)
691      {
692        keysDown_.erase(keysDown_.begin() + iKey);
693        break;
694      }
695    }
696
697    // update modifiers
698    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
699      keyboardModifiers_ &= ~KeyboardModifier::Alt;   // alt key
700    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
701      keyboardModifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
702    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
703      keyboardModifiers_ &= ~KeyboardModifier::Shift; // shift key
704
705    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
706      activeKeyHandlers_[i]->keyReleased(KeyEvent(e, keyboardModifiers_));
707
708    return true;
709  }
710
711
712  // ###### Mouse Events ######
713
714  /**
715    @brief Event handler for the mouseMoved Event.
716    @param e Event information
717  */
718  bool InputManager::mouseMoved(const OIS::MouseEvent &e)
719  {
720    // check for actual moved event
721    if (e.state.X.rel != 0 || e.state.Y.rel != 0)
722    {
723      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
724        activeMouseHandlers_[i]->mouseMoved(IntVector2(e.state.X.abs, e.state.Y.abs),
725            IntVector2(e.state.X.rel, e.state.Y.rel), IntVector2(e.state.width, e.state.height));
726    }
727
728    // check for mouse scrolled event
729    if (e.state.Z.rel != 0)
730    {
731      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
732        activeMouseHandlers_[i]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
733    }
734
735    return true;
736  }
737
738  /**
739    @brief Event handler for the mousePressed Event.
740    @param e Event information
741    @param id The ID of the mouse button
742  */
743  bool InputManager::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
744  {
745    // check whether the button already is in the list (can happen when focus was lost)
746    unsigned int iButton = 0;
747    while (iButton < mouseButtonsDown_.size() && mouseButtonsDown_[iButton] != (MouseButton::Enum)id)
748      iButton++;
749    if (iButton == mouseButtonsDown_.size())
750      mouseButtonsDown_.push_back((MouseButton::Enum)id);
751
752    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
753      activeMouseHandlers_[i]->mouseButtonPressed((MouseButton::Enum)id);
754
755    return true;
756  }
757
758  /**
759    @brief Event handler for the mouseReleased Event.
760    @param e Event information
761    @param id The ID of the mouse button
762  */
763  bool InputManager::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
764  {
765    // remove the button from the keysDown_ list
766    for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
767    {
768      if (mouseButtonsDown_[iButton] == (MouseButton::Enum)id)
769      {
770        mouseButtonsDown_.erase(mouseButtonsDown_.begin() + iButton);
771        break;
772      }
773    }
774
775    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
776      activeMouseHandlers_[i]->mouseButtonReleased((MouseButton::Enum)id);
777
778    return true;
779  }
780
781
782  // ###### Joy Stick Events ######
783
784  inline unsigned int InputManager::_getJoystick(const OIS::JoyStickEvent& arg)
785  {
786    // use the device to identify which one called the method
787    OIS::JoyStick* joyStick = (OIS::JoyStick*)arg.device;
788    unsigned int iJoyStick = 0;
789    while (joySticks_[iJoyStick] != joyStick)
790    {
791      iJoyStick++;
792      if (iJoyStick == joySticksSize_)
793      {
794        CCOUT(3) << "Unknown joystick fired an event. This means there is a bug somewhere! Aborting." << std::endl;
795        abort();
796      }
797    }
798    return iJoyStick;
799  }
800
801  bool InputManager::buttonPressed(const OIS::JoyStickEvent &arg, int button)
802  {
803    unsigned int iJoyStick = _getJoystick(arg);
804
805    // check whether the button already is in the list (can happen when focus was lost)
806    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
807    unsigned int iButton = 0;
808    while (iButton < buttonsDown.size() && buttonsDown[iButton] != button)
809      iButton++;
810    if (iButton == buttonsDown.size())
811      buttonsDown.push_back(button);
812
813    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
814      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonPressed(iJoyStick, button);
815
816    return true;
817  }
818
819  bool InputManager::buttonReleased(const OIS::JoyStickEvent &arg, int button)
820  {
821    unsigned int iJoyStick = _getJoystick(arg);
822
823    // remove the button from the joyStickButtonsDown_ list
824    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
825    for (unsigned int iButton = 0; iButton < buttonsDown.size(); iButton++)
826    {
827      if (buttonsDown[iButton] == button)
828      {
829        buttonsDown.erase(buttonsDown.begin() + iButton);
830        break;
831      }
832    }
833
834    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
835      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonReleased(iJoyStick, button);
836
837    return true;
838  }
839
840  void InputManager::_fireAxis(unsigned int iJoyStick, int axis, int value)
841  {
842    if (state_ == IS_CALIBRATE)
843    {
844      if (value > marginalsMax_[axis])
845        marginalsMax_[axis] = value;
846      if (value < marginalsMin_[axis])
847        marginalsMin_[axis] = value;
848    }
849    else
850    {
851      float fValue = value - joySticksCalibration_[iJoyStick].zeroStates[axis];
852      if (fValue > 0.0f)
853        fValue *= joySticksCalibration_[iJoyStick].positiveCoeff[axis];
854      else
855        fValue *= joySticksCalibration_[iJoyStick].negativeCoeff[axis];
856
857      for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
858        activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickAxisMoved(iJoyStick, axis, fValue);
859    }
860  }
861
862  bool InputManager::axisMoved(const OIS::JoyStickEvent &arg, int axis)
863  {
864    //if (arg.state.mAxes[axis].abs > 10000 || arg.state.mAxes[axis].abs < -10000)
865    //{ CCOUT(3) << "axis " << axis << " moved" << arg.state.mAxes[axis].abs << std::endl;}
866
867    unsigned int iJoyStick = _getJoystick(arg);
868
869    // keep in mind that the first 8 axes are reserved for the sliders
870    _fireAxis(iJoyStick, axis + 8, arg.state.mAxes[axis].abs);
871
872    return true;
873  }
874
875  bool InputManager::sliderMoved(const OIS::JoyStickEvent &arg, int id)
876  {
877    //if (arg.state.mSliders[id].abX > 10000 || arg.state.mSliders[id].abX < -10000)
878    //{CCOUT(3) << "slider " << id << " moved" << arg.state.mSliders[id].abX << std::endl;}
879    //CCOUT(3) << arg.state.mSliders[id].abX << "\t |" << arg.state.mSliders[id].abY << std::endl;
880
881    unsigned int iJoyStick = _getJoystick(arg);
882
883    if (sliderStates_[iJoyStick].sliderStates[id].x != arg.state.mSliders[id].abX)
884      _fireAxis(iJoyStick, id * 2, arg.state.mSliders[id].abX);
885    else if (sliderStates_[iJoyStick].sliderStates[id].y != arg.state.mSliders[id].abY)
886      _fireAxis(iJoyStick, id * 2 + 1, arg.state.mSliders[id].abY);
887
888    return true;
889  }
890
891  bool InputManager::povMoved(const OIS::JoyStickEvent &arg, int id)
892  {
893    unsigned int iJoyStick = _getJoystick(arg);
894
895    // translate the POV into 8 simple buttons
896    int lastState = povStates_[iJoyStick][id];
897    if (lastState & OIS::Pov::North)
898      buttonReleased(arg, 32 + id * 4 + 0);
899    if (lastState & OIS::Pov::South)
900      buttonReleased(arg, 32 + id * 4 + 1);
901    if (lastState & OIS::Pov::East)
902      buttonReleased(arg, 32 + id * 4 + 2);
903    if (lastState & OIS::Pov::West)
904      buttonReleased(arg, 32 + id * 4 + 3);
905
906    povStates_[iJoyStick].povStates[id] = arg.state.mPOV[id].direction;
907
908    int currentState = povStates_[iJoyStick][id];
909    if (currentState & OIS::Pov::North)
910      buttonPressed(arg, 32 + id * 4 + 0);
911    if (currentState & OIS::Pov::South)
912      buttonPressed(arg, 32 + id * 4 + 1);
913    if (currentState & OIS::Pov::East)
914      buttonPressed(arg, 32 + id * 4 + 2);
915    if (currentState & OIS::Pov::West)
916      buttonPressed(arg, 32 + id * 4 + 3);
917
918    return true;
919  }
920
921  /*bool InputManager::vector3Moved(const OIS::JoyStickEvent &arg, int id)
922  {
923    unsigned int iJoyStick = _getJoystick(arg);
924
925    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
926      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickVector3Moved(JoyStickState(arg.state, iJoyStick), id);
927
928    return true;
929  }*/
930
931
932  // ################################
933  // ### Static Interface Methods ###
934  // ################################
935  // ################################
936
937  std::string InputManager::bindingCommmandString_s = "";
938
939  bool InputManager::initialise(const size_t windowHnd, int windowWidth, int windowHeight,
940    bool createKeyboard, bool createMouse, bool createJoySticks)
941  {
942    return _getSingleton()._initialise(windowHnd, windowWidth, windowHeight,
943          createKeyboard, createMouse, createJoySticks);
944  }
945
946  bool InputManager::initialiseKeyboard()
947  {
948    return _getSingleton()._initialiseKeyboard();
949  }
950
951  bool InputManager::initialiseMouse()
952  {
953    return _getSingleton()._initialiseMouse();
954  }
955
956  bool InputManager::initialiseJoySticks()
957  {
958    return _getSingleton()._initialiseJoySticks();
959  }
960
961  int InputManager::numberOfKeyboards()
962  {
963    if (_getSingleton().keyboard_ != 0)
964      return 1;
965    else
966      return 0;
967  }
968
969  int InputManager::numberOfMice()
970  {
971    if (_getSingleton().mouse_ != 0)
972      return 1;
973    else
974      return 0;
975  }
976
977  int InputManager::numberOfJoySticks()
978  {
979    return _getSingleton().joySticksSize_;
980  }
981
982  /*bool InputManager::isKeyDown(KeyCode::Enum key)
983  {
984    if (_getSingleton().keyboard_)
985      return _getSingleton().keyboard_->isKeyDown((OIS::KeyCode)key);
986    else
987      return false;
988  }*/
989
990  /*bool InputManager::isModifierDown(KeyboardModifier::Enum modifier)
991  {
992    if (_getSingleton().keyboard_)
993      return isModifierDown(modifier);
994    else
995      return false;
996  }*/
997
998  /*const MouseState InputManager::getMouseState()
999  {
1000    if (_getSingleton().mouse_)
1001      return _getSingleton().mouse_->getMouseState();
1002    else
1003      return MouseState();
1004  }*/
1005
1006  /*const JoyStickState InputManager::getJoyStickState(unsigned int ID)
1007  {
1008    if (ID < _getSingleton().joySticksSize_)
1009      return JoyStickState(_getSingleton().joySticks_[ID]->getJoyStickState(), ID);
1010    else
1011      return JoyStickState();
1012  }*/
1013
1014  void InputManager::destroy()
1015  {
1016    _getSingleton()._destroy();
1017  }
1018
1019  void InputManager::destroyKeyboard()
1020  {
1021    return _getSingleton()._destroyKeyboard();
1022  }
1023
1024  void InputManager::destroyMouse()
1025  {
1026    return _getSingleton()._destroyMouse();
1027  }
1028
1029  void InputManager::destroyJoySticks()
1030  {
1031    return _getSingleton()._destroyJoySticks();
1032  }
1033
1034
1035  /**
1036    @brief Adjusts the mouse window metrics.
1037    This method has to be called every time the size of the window changes.
1038    @param width The new width of the render window
1039    @param height the new height of the render window
1040  */
1041  void InputManager::setWindowExtents(const int width, const int height)
1042  {
1043    if (_getSingleton().mouse_)
1044    {
1045      // Set mouse region (if window resizes, we should alter this to reflect as well)
1046      const OIS::MouseState &mouseState = _getSingleton().mouse_->getMouseState();
1047      mouseState.width  = width;
1048      mouseState.height = height;
1049    }
1050  }
1051
1052  /**
1053    @brief Sets the input mode to either GUI, inGame or Buffer
1054    @param mode The new input mode
1055    @remark Only has an affect if the mode actually changes
1056  */
1057  void InputManager::setInputState(const InputState state)
1058  {
1059    _getSingleton().stateRequest_ = state;
1060  }
1061
1062  /**
1063    @brief Returns the current input handling method
1064    @return The current input mode.
1065  */
1066  InputManager::InputState InputManager::getInputState()
1067  {
1068    return _getSingleton().state_;
1069  }
1070
1071  void InputManager::storeKeyStroke(const std::string& name)
1072  {
1073    setInputState(IS_NODETECT);
1074    COUT(0) << "Binding string \"" << bindingCommmandString_s << "\" on key '" << name << "'" << std::endl;
1075    CommandExecutor::execute("config KeyBinder " + name + " " + bindingCommmandString_s, false);
1076  }
1077
1078  void InputManager::keyBind(const std::string& command)
1079  {
1080    bindingCommmandString_s = command;
1081    setInputState(IS_DETECT);
1082    COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl;
1083  }
1084
1085  void InputManager::calibrate()
1086  {
1087    _getSingleton().setInputState(IS_CALIBRATE);
1088  }
1089
1090  // ###### KeyHandler ######
1091
1092  /**
1093    @brief Adds a new key handler.
1094    @param handler Pointer to the handler object.
1095    @param name Unique name of the handler.
1096    @return True if added, false if name already existed.
1097  */
1098  bool InputManager::addKeyHandler(KeyHandler* handler, const std::string& name)
1099  {
1100    if (!handler)
1101      return false;
1102    if (_getSingleton().keyHandlers_.find(name) == _getSingleton().keyHandlers_.end())
1103    {
1104      _getSingleton().keyHandlers_[name] = handler;
1105      return true;
1106    }
1107    else
1108      return false;
1109  }
1110
1111  /**
1112    @brief Removes a Key handler from the list.
1113    @param name Unique name of the handler.
1114    @return True if removal was successful, false if name was not found.
1115  */
1116  bool InputManager::removeKeyHandler(const std::string &name)
1117  {
1118    disableKeyHandler(name);
1119    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
1120    if (it != _getSingleton().keyHandlers_.end())
1121    {
1122      _getSingleton().keyHandlers_.erase(it);
1123      return true;
1124    }
1125    else
1126      return false;
1127  }
1128
1129  /**
1130    @brief Returns the pointer to a handler.
1131    @param name Unique name of the handler.
1132    @return Pointer to the instance, 0 if name was not found.
1133  */
1134  KeyHandler* InputManager::getKeyHandler(const std::string& name)
1135  {
1136    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
1137    if (it != _getSingleton().keyHandlers_.end())
1138    {
1139      return (*it).second;
1140    }
1141    else
1142      return 0;
1143  }
1144
1145  /**
1146    @brief Enables a specific key handler that has already been added.
1147    @param name Unique name of the handler.
1148    @return False if name was not found, true otherwise.
1149  */
1150  bool InputManager::enableKeyHandler(const std::string& name)
1151  {
1152    // get pointer from the map with all stored handlers
1153    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1154    if (mapIt == _getSingleton().keyHandlers_.end())
1155      return false;
1156    // see whether the handler already is in the list
1157    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1158          it != _getSingleton().activeKeyHandlers_.end(); it++)
1159    {
1160      if ((*it) == (*mapIt).second)
1161      {
1162        return true;
1163      }
1164    }
1165    _getSingleton().activeKeyHandlers_.push_back((*mapIt).second);
1166    _getSingleton().stateRequest_ = IS_CUSTOM;
1167    _getSingleton()._updateTickables();
1168    return true;
1169  }
1170
1171  /**
1172    @brief Disables a specific key handler.
1173    @param name Unique name of the handler.
1174    @return False if name was not found, true otherwise.
1175  */
1176  bool InputManager::disableKeyHandler(const std::string &name)
1177  {
1178    // get pointer from the map with all stored handlers
1179    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1180    if (mapIt == _getSingleton().keyHandlers_.end())
1181      return false;
1182    // look for the handler in the list
1183    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1184          it != _getSingleton().activeKeyHandlers_.end(); it++)
1185    {
1186      if ((*it) == (*mapIt).second)
1187      {
1188        _getSingleton().activeKeyHandlers_.erase(it);
1189        _getSingleton().stateRequest_ = IS_CUSTOM;
1190        _getSingleton()._updateTickables();
1191        return true;
1192      }
1193    }
1194    return true;
1195  }
1196
1197  /**
1198    @brief Checks whether a key handler is active
1199    @param name Unique name of the handler.
1200    @return False if key handler is not active or doesn't exist, true otherwise.
1201  */
1202  bool InputManager::isKeyHandlerActive(const std::string& name)
1203  {
1204    // get pointer from the map with all stored handlers
1205    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1206    if (mapIt == _getSingleton().keyHandlers_.end())
1207      return false;
1208    // see whether the handler already is in the list
1209    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1210          it != _getSingleton().activeKeyHandlers_.end(); it++)
1211    {
1212      if ((*it) == (*mapIt).second)
1213        return true;
1214    }
1215    return false;
1216  }
1217
1218
1219  // ###### MouseHandler ######
1220  /**
1221    @brief Adds a new mouse handler.
1222    @param handler Pointer to the handler object.
1223    @param name Unique name of the handler.
1224    @return True if added, false if name already existed.
1225  */
1226  bool InputManager::addMouseHandler(MouseHandler* handler, const std::string& name)
1227  {
1228    if (!handler)
1229      return false;
1230    if (_getSingleton().mouseHandlers_.find(name) == _getSingleton().mouseHandlers_.end())
1231    {
1232      _getSingleton().mouseHandlers_[name] = handler;
1233      return true;
1234    }
1235    else
1236      return false;
1237  }
1238
1239  /**
1240    @brief Removes a Mouse handler from the list.
1241    @param name Unique name of the handler.
1242    @return True if removal was successful, false if name was not found.
1243  */
1244  bool InputManager::removeMouseHandler(const std::string &name)
1245  {
1246    disableMouseHandler(name);
1247    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
1248    if (it != _getSingleton().mouseHandlers_.end())
1249    {
1250      _getSingleton().mouseHandlers_.erase(it);
1251      return true;
1252    }
1253    else
1254      return false;
1255  }
1256
1257  /**
1258    @brief Returns the pointer to a handler.
1259    @param name Unique name of the handler.
1260    @return Pointer to the instance, 0 if name was not found.
1261  */
1262  MouseHandler* InputManager::getMouseHandler(const std::string& name)
1263  {
1264    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
1265    if (it != _getSingleton().mouseHandlers_.end())
1266    {
1267      return (*it).second;
1268    }
1269    else
1270      return 0;
1271  }
1272
1273  /**
1274    @brief Enables a specific mouse handler that has already been added.
1275    @param name Unique name of the handler.
1276    @return False if name was not found, true otherwise.
1277  */
1278  bool InputManager::enableMouseHandler(const std::string& name)
1279  {
1280    // get pointer from the map with all stored handlers
1281    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1282    if (mapIt == _getSingleton().mouseHandlers_.end())
1283      return false;
1284    // see whether the handler already is in the list
1285    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1286          it != _getSingleton().activeMouseHandlers_.end(); it++)
1287    {
1288      if ((*it) == (*mapIt).second)
1289      {
1290        return true;
1291      }
1292    }
1293    _getSingleton().activeMouseHandlers_.push_back((*mapIt).second);
1294    _getSingleton().stateRequest_ = IS_CUSTOM;
1295    _getSingleton()._updateTickables();
1296    return true;
1297  }
1298
1299  /**
1300    @brief Disables a specific mouse handler.
1301    @param name Unique name of the handler.
1302    @return False if name was not found, true otherwise.
1303  */
1304  bool InputManager::disableMouseHandler(const std::string &name)
1305  {
1306    // get pointer from the map with all stored handlers
1307    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1308    if (mapIt == _getSingleton().mouseHandlers_.end())
1309      return false;
1310    // look for the handler in the list
1311    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1312          it != _getSingleton().activeMouseHandlers_.end(); it++)
1313    {
1314      if ((*it) == (*mapIt).second)
1315      {
1316        _getSingleton().activeMouseHandlers_.erase(it);
1317        _getSingleton().stateRequest_ = IS_CUSTOM;
1318        _getSingleton()._updateTickables();
1319        return true;
1320      }
1321    }
1322    return true;
1323  }
1324
1325  /**
1326    @brief Checks whether a mouse handler is active
1327    @param name Unique name of the handler.
1328    @return False if key handler is not active or doesn't exist, true otherwise.
1329  */
1330  bool InputManager::isMouseHandlerActive(const std::string& name)
1331  {
1332    // get pointer from the map with all stored handlers
1333    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1334    if (mapIt == _getSingleton().mouseHandlers_.end())
1335      return false;
1336    // see whether the handler already is in the list
1337    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1338          it != _getSingleton().activeMouseHandlers_.end(); it++)
1339    {
1340      if ((*it) == (*mapIt).second)
1341        return true;
1342    }
1343    return false;
1344  }
1345
1346
1347  // ###### JoyStickHandler ######
1348
1349  /**
1350    @brief Adds a new joy stick handler.
1351    @param handler Pointer to the handler object.
1352    @param name Unique name of the handler.
1353    @return True if added, false if name already existed.
1354  */
1355  bool InputManager::addJoyStickHandler(JoyStickHandler* handler, const std::string& name)
1356  {
1357    if (!handler)
1358      return false;
1359    if (_getSingleton().joyStickHandlers_.find(name) == _getSingleton().joyStickHandlers_.end())
1360    {
1361      _getSingleton().joyStickHandlers_[name] = handler;
1362      return true;
1363    }
1364    else
1365      return false;
1366  }
1367
1368  /**
1369    @brief Removes a JoyStick handler from the list.
1370    @param name Unique name of the handler.
1371    @return True if removal was successful, false if name was not found.
1372  */
1373  bool InputManager::removeJoyStickHandler(const std::string &name)
1374  {
1375    for (std::vector<OIS::JoyStick*>::iterator itstick = _getSingleton().joySticks_.begin();
1376          itstick != _getSingleton().joySticks_.end(); itstick++)
1377      disableJoyStickHandler(name, itstick - _getSingleton().joySticks_.begin());
1378
1379    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
1380    if (it != _getSingleton().joyStickHandlers_.end())
1381    {
1382      _getSingleton().joyStickHandlers_.erase(it);
1383      return true;
1384    }
1385    else
1386      return false;
1387  }
1388
1389  /**
1390    @brief Returns the pointer to a handler.
1391    @param name Unique name of the handler.
1392    @return Pointer to the instance, 0 if name was not found.
1393  */
1394  JoyStickHandler* InputManager::getJoyStickHandler(const std::string& name)
1395  {
1396    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
1397    if (it != _getSingleton().joyStickHandlers_.end())
1398    {
1399      return (*it).second;
1400    }
1401    else
1402      return 0;
1403  }
1404
1405  /**
1406    @brief Enables a specific joy stick handler that has already been added.
1407    @param name Unique name of the handler.
1408    @return False if name or id was not found, true otherwise.
1409  */
1410  bool InputManager::enableJoyStickHandler(const std::string& name, unsigned int ID)
1411  {
1412    // get handler pointer from the map with all stored handlers
1413    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1414    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1415      return false;
1416
1417    // check for existence of the ID
1418    if (ID >= _getSingleton().joySticksSize_)
1419      return false;
1420
1421    // see whether the handler already is in the list
1422    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1423          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1424    {
1425      if ((*it) == (*handlerIt).second)
1426      {
1427        return true;
1428      }
1429    }
1430    _getSingleton().activeJoyStickHandlers_[ID].push_back((*handlerIt).second);
1431    _getSingleton().stateRequest_ = IS_CUSTOM;
1432    _getSingleton()._updateTickables();
1433    return true;
1434  }
1435
1436  /**
1437    @brief Disables a specific joy stick handler.
1438    @param name Unique name of the handler.
1439    @return False if name or id was not found, true otherwise.
1440  */
1441  bool InputManager::disableJoyStickHandler(const std::string &name, unsigned int ID)
1442  {
1443    // get handler pointer from the map with all stored handlers
1444    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1445    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1446      return false;
1447
1448    // check for existence of the ID
1449    if (ID >= _getSingleton().joySticksSize_)
1450      return false;
1451
1452    // look for the handler in the list
1453    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1454          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1455    {
1456      if ((*it) == (*handlerIt).second)
1457      {
1458        _getSingleton().activeJoyStickHandlers_[ID].erase(it);
1459        _getSingleton().stateRequest_ = IS_CUSTOM;
1460        _getSingleton()._updateTickables();
1461        return true;
1462      }
1463    }
1464    return true;
1465  }
1466
1467  /**
1468    @brief Checks whether a joy stick handler is active
1469    @param name Unique name of the handler.
1470    @return False if key handler is not active or doesn't exist, true otherwise.
1471  */
1472  bool InputManager::isJoyStickHandlerActive(const std::string& name, unsigned int ID)
1473  {
1474    // get handler pointer from the map with all stored handlers
1475    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1476    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1477      return false;
1478
1479    // check for existence of the ID
1480    if (ID >= _getSingleton().joySticksSize_)
1481      return false;
1482
1483    // see whether the handler already is in the list
1484    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1485          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1486    {
1487      if ((*it) == (*handlerIt).second)
1488        return true;
1489    }
1490    return false;
1491  }
1492
1493}
Note: See TracBrowser for help on using the repository browser.