Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/input/src/core/input/InputManager.cc @ 1519

Last change on this file since 1519 was 1519, checked in by rgrieder, 16 years ago

moved input related files to src/core/input

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