Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/core/input/InputManager.cc @ 1537

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