Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Added 'calibrate' command for the joystick
Simply type 'calibrate', move your axes around, center them press enter again.
Values are stored in keybindings.ini

File size: 49.1 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30  @file
31  @brief Implementation of the InputManager that captures all the input from OIS
32         and redirects it to handlers.
33 */
34
35#include "InputManager.h"
36#include "util/Convert.h"
37#include "CoreIncludes.h"
38#include "ConfigValueIncludes.h"
39#include "Debug.h"
40#include "InputBuffer.h"
41#include "KeyBinder.h"
42#include "CommandExecutor.h"
43#include "ConsoleCommand.h"
44
45namespace orxonox
46{
47  ConsoleCommandShortcut(InputManager, keyBind, AccessLevel::User);
48  ConsoleCommandShortcut(InputManager, storeKeyStroke, AccessLevel::Offline);
49  ConsoleCommandShortcut(InputManager, calibrate, AccessLevel::User);
50
51  // ###############################
52  // ###    Internal Methods     ###
53  // ###############################
54  // ###############################
55
56  /**
57    @brief Constructor only sets member fields to initial zero values
58           and registers the class in the class hierarchy.
59  */
60  InputManager::InputManager() :
61      inputSystem_(0), keyboard_(0), mouse_(0),
62      joySticksSize_(0),
63      keyBinder_(0), keyDetector_(0), buffer_(0), calibratorCallback_(0),
64      state_(IS_UNINIT), stateRequest_(IS_UNINIT), savedState_(IS_UNINIT),
65      keyboardModifiers_(0)
66  {
67    RegisterObject(InputManager);
68  }
69
70  /**
71    @brief The one instance of the InputManager is stored in this function.
72    @return A reference to the only instance of the InputManager
73  */
74  InputManager& InputManager::_getSingleton()
75  {
76    static InputManager theOnlyInstance;
77    return theOnlyInstance;
78  }
79
80  /**
81    @brief Destructor only called at the end of the program, after main.
82  */
83  InputManager::~InputManager()
84  {
85    _destroy();
86  }
87
88  /**
89    @brief Creates the OIS::InputMananger, the keyboard, the mouse and
90           the joysticks and assigns the key bindings.
91    @param windowHnd The window handle of the render window
92    @param windowWidth The width of the render window
93    @param windowHeight The height of the render window
94  */
95  bool InputManager::_initialise(const size_t windowHnd, int windowWidth, int windowHeight,
96        bool createKeyboard, bool createMouse, bool createJoySticks)
97  {
98    if (state_ == IS_UNINIT)
99    {
100      CCOUT(3) << "Initialising Input System..." << std::endl;
101      CCOUT(ORX_DEBUG) << "Initialising OIS components..." << std::endl;
102
103      OIS::ParamList paramList;
104      std::ostringstream windowHndStr;
105
106      // Fill parameter list
107      windowHndStr << (unsigned int)windowHnd;
108      paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
109      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
110      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
111//#if defined OIS_LINUX_PLATFORM
112//      paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
113//#endif
114
115      try
116      {
117        inputSystem_ = OIS::InputManager::createInputSystem(paramList);
118        CCOUT(ORX_DEBUG) << "Created OIS input system" << std::endl;
119      }
120      catch (OIS::Exception ex)
121      {
122        CCOUT(ORX_ERROR) << "Error: Failed creating an OIS input system."
123            << "OIS message: \"" << ex.eText << "\"" << std::endl;
124        inputSystem_ = 0;
125        return false;
126      }
127
128      if (createKeyboard)
129        _initialiseKeyboard();
130
131      if (createMouse)
132        _initialiseMouse();
133
134      if (createJoySticks)
135        _initialiseJoySticks();
136
137      // Set mouse/joystick region
138      if (mouse_)
139      {
140        //// hack the mouse position
141        //((OIS::MouseState&)mouse_->getMouseState()).X.abs = windowWidth/2;
142        //((OIS::MouseState&)mouse_->getMouseState()).Y.abs = windowHeight/2;
143        setWindowExtents(windowWidth, windowHeight);
144      }
145
146      state_ = IS_NONE;
147      CCOUT(ORX_DEBUG) << "Initialising OIS components done." << std::endl;
148
149      // InputManager holds the input buffer --> create one and add it.
150      buffer_ = new InputBuffer();
151      addKeyHandler(buffer_, "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 keyboard" << 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        state_ = IS_NODETECT;
561        stateRequest_ = savedState_;
562        break;
563
564      case IS_CALIBRATE:
565        if (joySticksSize_)
566        {
567          savedState_ = _getSingleton().state_;
568          for (unsigned int i = 0; i < 24; i++)
569          {
570            marginalsMax_[i] = INT_MIN;
571            marginalsMin_[i] = INT_MAX;
572          }
573          COUT(3) << "Move all joy stick axes in all directions a few times. "
574            << "Then put all axes in zero state and hit enter." << std::endl;
575
576          savedState_ = state_;
577          _saveState();
578
579          activeKeyHandlers_.clear();
580          activeMouseHandlers_.clear();
581          for (unsigned int i = 0; i < joySticksSize_; i++)
582            activeJoyStickHandlers_[i].clear();
583
584          enableKeyHandler("calibratorcallback");
585          stateRequest_ = IS_CALIBRATE;
586          state_ = IS_CALIBRATE;
587        }
588        else
589        {
590          COUT(3) << "Connot calibrate, no joy stick found!" << std::endl;
591          stateRequest_ = state_;
592        }
593        break;
594
595      case IS_NOCALIBRATE:
596        _completeCalibration();
597        _restoreState();
598        state_ = IS_NOCALIBRATE;
599        stateRequest_ = savedState_;
600        break;
601
602      case IS_NONE:
603        activeKeyHandlers_.clear();
604        activeMouseHandlers_.clear();
605        for (unsigned int i = 0; i < joySticksSize_; i++)
606          activeJoyStickHandlers_[i].clear();
607        state_ = IS_NONE;
608
609      default:
610        break;
611      }
612    }
613
614    // Capture all the input. This calls the event handlers in InputManager.
615    if (mouse_)
616      mouse_->capture();
617    if (keyboard_)
618      keyboard_->capture();
619    for (unsigned  int i = 0; i < joySticksSize_; i++)
620      joySticks_[i]->capture();
621
622    if (state_ != IS_CALIBRATE)
623    {
624      // call all the handlers for the held key events
625      for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
626        for (unsigned int iHandler = 0; iHandler < activeKeyHandlers_.size(); iHandler++)
627          activeKeyHandlers_[iHandler]->keyHeld(KeyEvent(keysDown_[iKey], keyboardModifiers_));
628
629      // call all the handlers for the held mouse button events
630      for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
631        for (unsigned int iHandler = 0; iHandler < activeMouseHandlers_.size(); iHandler++)
632          activeMouseHandlers_[iHandler]->mouseButtonHeld(mouseButtonsDown_[iButton]);
633
634      // call all the handlers for the held joy stick button events
635      for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
636        for (unsigned int iButton   = 0; iButton   < joyStickButtonsDown_[iJoyStick].size(); iButton++)
637          for (unsigned int iHandler = 0; iHandler  < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
638            activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonHeld(iJoyStick, joyStickButtonsDown_[iJoyStick][iButton]);
639    }
640
641    // call the ticks for the handlers (need to be treated specially)
642    for (unsigned int iHandler = 0; iHandler < activeHandlers_.size(); iHandler++)
643      activeHandlers_[iHandler].first->tickInput(dt, activeHandlers_[iHandler].second);
644  }
645
646  void InputManager::_completeCalibration()
647  {
648    for (unsigned int i = 0; i < 24; i++)
649    {
650      // positive coefficient
651      if (marginalsMax_[i] == INT_MIN)
652        marginalsMax_[i] =  32767;
653      // coefficients
654      if (marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i])
655        joySticksCalibration_[0].positiveCoeff[i] =  1.0f/(marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i]);
656      else
657        joySticksCalibration_[0].positiveCoeff[i] =  1.0f;
658
659      // config value
660      ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
661      assert(cont);
662      cont->set(getConvertedValue<int, std::string>(i) + " "
663        + getConvertedValue<float, std::string>(joySticksCalibration_[0].positiveCoeff[i]));
664
665      // negative coefficient
666      if (marginalsMin_[i] == INT_MAX)
667        marginalsMin_[i] = -32768;
668      // coefficients
669      if (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i])
670        joySticksCalibration_[0].negativeCoeff[i] = -1.0f/(marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i]);
671      else
672        joySticksCalibration_[0].negativeCoeff[i] =  1.0f;
673      // config value
674      cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
675      assert(cont);
676      cont->set(getConvertedValue<int, std::string>(i) + " "
677        + getConvertedValue<float, std::string>(joySticksCalibration_[0].negativeCoeff[i]));
678
679      // zero states
680      if (i < 8)
681      {
682        if (!(i & 1))
683          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abX;
684        else
685          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abY;
686      }
687      else
688      {
689        if (i - 8 < joySticks_[0]->getJoyStickState().mAxes.size())
690          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mAxes[i - 8].abs;
691        else
692          joySticksCalibration_[0].zeroStates[i] = 0;
693      }
694      // config value
695      cont = getIdentifier()->getConfigValueContainer("Zero");
696      assert(cont);
697      cont->set(getConvertedValue<int, std::string>(i) + " "
698        + getConvertedValue<int, std::string>(joySticksCalibration_[0].zeroStates[i]));
699    }
700  }
701
702  // ###### Key Events ######
703
704  /**
705    @brief Event handler for the keyPressed Event.
706    @param e Event information
707  */
708  bool InputManager::keyPressed(const OIS::KeyEvent &e)
709  {
710    // check whether the key already is in the list (can happen when focus was lost)
711    unsigned int iKey = 0;
712    while (iKey < keysDown_.size() && keysDown_[iKey].key != (KeyCode::Enum)e.key)
713      iKey++;
714    if (iKey == keysDown_.size())
715      keysDown_.push_back(Key(e));
716
717    // update modifiers
718    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
719      keyboardModifiers_ |= KeyboardModifier::Alt;   // alt key
720    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
721      keyboardModifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
722    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
723      keyboardModifiers_ |= KeyboardModifier::Shift; // shift key
724
725    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
726      activeKeyHandlers_[i]->keyPressed(KeyEvent(e, keyboardModifiers_));
727
728    return true;
729  }
730
731  /**
732    @brief Event handler for the keyReleased Event.
733    @param e Event information
734  */
735  bool InputManager::keyReleased(const OIS::KeyEvent &e)
736  {
737    // remove the key from the keysDown_ list
738    for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
739    {
740      if (keysDown_[iKey].key == (KeyCode::Enum)e.key)
741      {
742        keysDown_.erase(keysDown_.begin() + iKey);
743        break;
744      }
745    }
746
747    // update modifiers
748    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
749      keyboardModifiers_ &= ~KeyboardModifier::Alt;   // alt key
750    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
751      keyboardModifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
752    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
753      keyboardModifiers_ &= ~KeyboardModifier::Shift; // shift key
754
755    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
756      activeKeyHandlers_[i]->keyReleased(KeyEvent(e, keyboardModifiers_));
757
758    return true;
759  }
760
761
762  // ###### Mouse Events ######
763
764  /**
765    @brief Event handler for the mouseMoved Event.
766    @param e Event information
767  */
768  bool InputManager::mouseMoved(const OIS::MouseEvent &e)
769  {
770    // check for actual moved event
771    if (e.state.X.rel != 0 || e.state.Y.rel != 0)
772    {
773      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
774        activeMouseHandlers_[i]->mouseMoved(IntVector2(e.state.X.abs, e.state.Y.abs),
775            IntVector2(e.state.X.rel, e.state.Y.rel), IntVector2(e.state.width, e.state.height));
776    }
777
778    // check for mouse scrolled event
779    if (e.state.Z.rel != 0)
780    {
781      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
782        activeMouseHandlers_[i]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
783    }
784
785    return true;
786  }
787
788  /**
789    @brief Event handler for the mousePressed Event.
790    @param e Event information
791    @param id The ID of the mouse button
792  */
793  bool InputManager::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
794  {
795    // check whether the button already is in the list (can happen when focus was lost)
796    unsigned int iButton = 0;
797    while (iButton < mouseButtonsDown_.size() && mouseButtonsDown_[iButton] != (MouseButton::Enum)id)
798      iButton++;
799    if (iButton == mouseButtonsDown_.size())
800      mouseButtonsDown_.push_back((MouseButton::Enum)id);
801
802    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
803      activeMouseHandlers_[i]->mouseButtonPressed((MouseButton::Enum)id);
804
805    return true;
806  }
807
808  /**
809    @brief Event handler for the mouseReleased Event.
810    @param e Event information
811    @param id The ID of the mouse button
812  */
813  bool InputManager::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
814  {
815    // remove the button from the keysDown_ list
816    for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
817    {
818      if (mouseButtonsDown_[iButton] == (MouseButton::Enum)id)
819      {
820        mouseButtonsDown_.erase(mouseButtonsDown_.begin() + iButton);
821        break;
822      }
823    }
824
825    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
826      activeMouseHandlers_[i]->mouseButtonReleased((MouseButton::Enum)id);
827
828    return true;
829  }
830
831
832  // ###### Joy Stick Events ######
833
834  inline unsigned int InputManager::_getJoystick(const OIS::JoyStickEvent& arg)
835  {
836    // use the device to identify which one called the method
837    OIS::JoyStick* joyStick = (OIS::JoyStick*)arg.device;
838    unsigned int iJoyStick = 0;
839    while (joySticks_[iJoyStick] != joyStick)
840    {
841      iJoyStick++;
842      if (iJoyStick == joySticksSize_)
843      {
844        CCOUT(3) << "Unknown joystick fired an event. This means there is a bug somewhere! Aborting." << std::endl;
845        abort();
846      }
847    }
848    return iJoyStick;
849  }
850
851  bool InputManager::buttonPressed(const OIS::JoyStickEvent &arg, int button)
852  {
853    unsigned int iJoyStick = _getJoystick(arg);
854
855    // check whether the button already is in the list (can happen when focus was lost)
856    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
857    unsigned int iButton = 0;
858    while (iButton < buttonsDown.size() && buttonsDown[iButton] != button)
859      iButton++;
860    if (iButton == buttonsDown.size())
861      buttonsDown.push_back(button);
862
863    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
864      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonPressed(iJoyStick, button);
865
866    return true;
867  }
868
869  bool InputManager::buttonReleased(const OIS::JoyStickEvent &arg, int button)
870  {
871    unsigned int iJoyStick = _getJoystick(arg);
872
873    // remove the button from the joyStickButtonsDown_ list
874    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
875    for (unsigned int iButton = 0; iButton < buttonsDown.size(); iButton++)
876    {
877      if (buttonsDown[iButton] == button)
878      {
879        buttonsDown.erase(buttonsDown.begin() + iButton);
880        break;
881      }
882    }
883
884    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
885      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonReleased(iJoyStick, button);
886
887    return true;
888  }
889
890  void InputManager::_fireAxis(unsigned int iJoyStick, int axis, int value)
891  {
892    if (state_ == IS_CALIBRATE)
893    {
894      if (value > marginalsMax_[axis])
895        marginalsMax_[axis] = value;
896      if (value < marginalsMin_[axis])
897        marginalsMin_[axis] = value;
898    }
899    else
900    {
901      float fValue = value - joySticksCalibration_[iJoyStick].zeroStates[axis];
902      if (fValue > 0.0f)
903        fValue *= joySticksCalibration_[iJoyStick].positiveCoeff[axis];
904      else
905        fValue *= joySticksCalibration_[iJoyStick].negativeCoeff[axis];
906
907      for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
908        activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickAxisMoved(iJoyStick, axis, fValue);
909    }   
910  }
911
912  bool InputManager::axisMoved(const OIS::JoyStickEvent &arg, int axis)
913  {
914    //if (arg.state.mAxes[axis].abs > 10000 || arg.state.mAxes[axis].abs < -10000)
915    //{ CCOUT(3) << "axis " << axis << " moved" << arg.state.mAxes[axis].abs << std::endl;}
916
917    unsigned int iJoyStick = _getJoystick(arg);
918
919    // keep in mind that the first 8 axes are reserved for the sliders
920    _fireAxis(iJoyStick, axis + 8, arg.state.mAxes[axis].abs);
921
922    return true;
923  }
924
925  bool InputManager::sliderMoved(const OIS::JoyStickEvent &arg, int id)
926  {
927    //if (arg.state.mSliders[id].abX > 10000 || arg.state.mSliders[id].abX < -10000)
928    //{CCOUT(3) << "slider " << id << " moved" << arg.state.mSliders[id].abX << std::endl;}
929    //CCOUT(3) << arg.state.mSliders[id].abX << "\t |" << arg.state.mSliders[id].abY << std::endl;
930
931    unsigned int iJoyStick = _getJoystick(arg);
932
933    if (sliderStates_[iJoyStick].sliderStates[id].x != arg.state.mSliders[id].abX)
934      _fireAxis(iJoyStick, id * 2, arg.state.mSliders[id].abX);
935    else if (sliderStates_[iJoyStick].sliderStates[id].y != arg.state.mSliders[id].abY)
936      _fireAxis(iJoyStick, id * 2 + 1, arg.state.mSliders[id].abY);
937
938    return true;
939  }
940
941  bool InputManager::povMoved(const OIS::JoyStickEvent &arg, int id)
942  {
943    unsigned int iJoyStick = _getJoystick(arg);
944
945    // translate the POV into 8 simple buttons
946    int lastState = povStates_[iJoyStick][id];
947    if (lastState & OIS::Pov::North)
948      buttonReleased(arg, 32 + id * 4 + 0);
949    if (lastState & OIS::Pov::South)
950      buttonReleased(arg, 32 + id * 4 + 1);
951    if (lastState & OIS::Pov::East)
952      buttonReleased(arg, 32 + id * 4 + 2);
953    if (lastState & OIS::Pov::West)
954      buttonReleased(arg, 32 + id * 4 + 3);
955   
956    povStates_[iJoyStick].povStates[id] = arg.state.mPOV[id].direction;
957
958    int currentState = povStates_[iJoyStick][id];
959    if (currentState & OIS::Pov::North)
960      buttonPressed(arg, 32 + id * 4 + 0);
961    if (currentState & OIS::Pov::South)
962      buttonPressed(arg, 32 + id * 4 + 1);
963    if (currentState & OIS::Pov::East)
964      buttonPressed(arg, 32 + id * 4 + 2);
965    if (currentState & OIS::Pov::West)
966      buttonPressed(arg, 32 + id * 4 + 3);
967
968    return true;
969  }
970
971  /*bool InputManager::vector3Moved(const OIS::JoyStickEvent &arg, int id)
972  {
973    unsigned int iJoyStick = _getJoystick(arg);
974
975    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
976      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickVector3Moved(JoyStickState(arg.state, iJoyStick), id);
977
978    return true;
979  }*/
980
981
982  // ################################
983  // ### Static Interface Methods ###
984  // ################################
985  // ################################
986
987  std::string InputManager::bindingCommmandString_s = "";
988
989  bool InputManager::initialise(const size_t windowHnd, int windowWidth, int windowHeight,
990    bool createKeyboard, bool createMouse, bool createJoySticks)
991  {
992    return _getSingleton()._initialise(windowHnd, windowWidth, windowHeight,
993          createKeyboard, createMouse, createJoySticks);
994  }
995
996  bool InputManager::initialiseKeyboard()
997  {
998    return _getSingleton()._initialiseKeyboard();
999  }
1000
1001  bool InputManager::initialiseMouse()
1002  {
1003    return _getSingleton()._initialiseMouse();
1004  }
1005
1006  bool InputManager::initialiseJoySticks()
1007  {
1008    return _getSingleton()._initialiseJoySticks();
1009  }
1010
1011  int InputManager::numberOfKeyboards()
1012  {
1013    if (_getSingleton().keyboard_ != 0)
1014      return 1;
1015    else
1016      return 0;
1017  }
1018
1019  int InputManager::numberOfMice()
1020  {
1021    if (_getSingleton().mouse_ != 0)
1022      return 1;
1023    else
1024      return 0;
1025  }
1026
1027  int InputManager::numberOfJoySticks()
1028  {
1029    return _getSingleton().joySticksSize_;
1030  }
1031
1032  /*bool InputManager::isKeyDown(KeyCode::Enum key)
1033  {
1034    if (_getSingleton().keyboard_)
1035      return _getSingleton().keyboard_->isKeyDown((OIS::KeyCode)key);
1036    else
1037      return false;
1038  }*/
1039
1040  /*bool InputManager::isModifierDown(KeyboardModifier::Enum modifier)
1041  {
1042    if (_getSingleton().keyboard_)
1043      return isModifierDown(modifier);
1044    else
1045      return false;
1046  }*/
1047
1048  /*const MouseState InputManager::getMouseState()
1049  {
1050    if (_getSingleton().mouse_)
1051      return _getSingleton().mouse_->getMouseState();
1052    else
1053      return MouseState();
1054  }*/
1055
1056  /*const JoyStickState InputManager::getJoyStickState(unsigned int ID)
1057  {
1058    if (ID < _getSingleton().joySticksSize_)
1059      return JoyStickState(_getSingleton().joySticks_[ID]->getJoyStickState(), ID);
1060    else
1061      return JoyStickState();
1062  }*/
1063
1064  void InputManager::destroy()
1065  {
1066    _getSingleton()._destroy();
1067  }
1068
1069  void InputManager::destroyKeyboard()
1070  {
1071    return _getSingleton()._destroyKeyboard();
1072  }
1073
1074  void InputManager::destroyMouse()
1075  {
1076    return _getSingleton()._destroyMouse();
1077  }
1078
1079  void InputManager::destroyJoySticks()
1080  {
1081    return _getSingleton()._destroyJoySticks();
1082  }
1083
1084
1085  /**
1086    @brief Adjusts the mouse window metrics.
1087    This method has to be called every time the size of the window changes.
1088    @param width The new width of the render window
1089    @param height the new height of the render window
1090  */
1091  void InputManager::setWindowExtents(const int width, const int height)
1092  {
1093    if (_getSingleton().mouse_)
1094    {
1095      // Set mouse region (if window resizes, we should alter this to reflect as well)
1096      const OIS::MouseState &mouseState = _getSingleton().mouse_->getMouseState();
1097      mouseState.width  = width;
1098      mouseState.height = height;
1099    }
1100  }
1101
1102  /**
1103    @brief Sets the input mode to either GUI, inGame or Buffer
1104    @param mode The new input mode
1105    @remark Only has an affect if the mode actually changes
1106  */
1107  void InputManager::setInputState(const InputState state)
1108  {
1109    _getSingleton().stateRequest_ = state;
1110  }
1111
1112  /**
1113    @brief Returns the current input handling method
1114    @return The current input mode.
1115  */
1116  InputManager::InputState InputManager::getInputState()
1117  {
1118    return _getSingleton().state_;
1119  }
1120
1121  void InputManager::storeKeyStroke(const std::string& name)
1122  {
1123    setInputState(IS_NODETECT);
1124    COUT(3) << "Binding string \"" << bindingCommmandString_s << "\" on key '" << name << "'" << std::endl;
1125    CommandExecutor::execute("set KeyBinder " + name + " " + bindingCommmandString_s, false);
1126  }
1127
1128  void InputManager::keyBind(const std::string& command)
1129  {
1130    bindingCommmandString_s = command;
1131    setInputState(IS_DETECT);
1132    COUT(3) << "Press any button/key or move a mouse/joystick axis" << std::endl;
1133  }
1134
1135  void InputManager::calibrate()
1136  {
1137    _getSingleton().setInputState(IS_CALIBRATE);
1138  }
1139
1140  // ###### KeyHandler ######
1141
1142  /**
1143    @brief Adds a new key handler.
1144    @param handler Pointer to the handler object.
1145    @param name Unique name of the handler.
1146    @return True if added, false if name already existed.
1147  */
1148  bool InputManager::addKeyHandler(KeyHandler* handler, const std::string& name)
1149  {
1150    if (!handler)
1151      return false;
1152    if (_getSingleton().keyHandlers_.find(name) == _getSingleton().keyHandlers_.end())
1153    {
1154      _getSingleton().keyHandlers_[name] = handler;
1155      return true;
1156    }
1157    else
1158      return false;
1159  }
1160
1161  /**
1162    @brief Removes a Key handler from the list.
1163    @param name Unique name of the handler.
1164    @return True if removal was successful, false if name was not found.
1165  */
1166  bool InputManager::removeKeyHandler(const std::string &name)
1167  {
1168    disableKeyHandler(name);
1169    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
1170    if (it != _getSingleton().keyHandlers_.end())
1171    {
1172      _getSingleton().keyHandlers_.erase(it);
1173      return true;
1174    }
1175    else
1176      return false;
1177  }
1178
1179  /**
1180    @brief Returns the pointer to a handler.
1181    @param name Unique name of the handler.
1182    @return Pointer to the instance, 0 if name was not found.
1183  */
1184  KeyHandler* InputManager::getKeyHandler(const std::string& name)
1185  {
1186    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
1187    if (it != _getSingleton().keyHandlers_.end())
1188    {
1189      return (*it).second;
1190    }
1191    else
1192      return 0;
1193  }
1194
1195  /**
1196    @brief Enables a specific key handler that has already been added.
1197    @param name Unique name of the handler.
1198    @return False if name was not found, true otherwise.
1199  */
1200  bool InputManager::enableKeyHandler(const std::string& name)
1201  {
1202    // get pointer from the map with all stored handlers
1203    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1204    if (mapIt == _getSingleton().keyHandlers_.end())
1205      return false;
1206    // see whether the handler already is in the list
1207    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1208          it != _getSingleton().activeKeyHandlers_.end(); it++)
1209    {
1210      if ((*it) == (*mapIt).second)
1211      {
1212        return true;
1213      }
1214    }
1215    _getSingleton().activeKeyHandlers_.push_back((*mapIt).second);
1216    _getSingleton().stateRequest_ = IS_CUSTOM;
1217    _getSingleton()._updateTickables();
1218    return true;
1219  }
1220
1221  /**
1222    @brief Disables a specific key handler.
1223    @param name Unique name of the handler.
1224    @return False if name was not found, true otherwise.
1225  */
1226  bool InputManager::disableKeyHandler(const std::string &name)
1227  {
1228    // get pointer from the map with all stored handlers
1229    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1230    if (mapIt == _getSingleton().keyHandlers_.end())
1231      return false;
1232    // look for the handler in the list
1233    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1234          it != _getSingleton().activeKeyHandlers_.end(); it++)
1235    {
1236      if ((*it) == (*mapIt).second)
1237      {
1238        _getSingleton().activeKeyHandlers_.erase(it);
1239        _getSingleton().stateRequest_ = IS_CUSTOM;
1240        _getSingleton()._updateTickables();
1241        return true;
1242      }
1243    }
1244    return true;
1245  }
1246
1247  /**
1248    @brief Checks whether a key handler is active
1249    @param name Unique name of the handler.
1250    @return False if key handler is not active or doesn't exist, true otherwise.
1251  */
1252  bool InputManager::isKeyHandlerActive(const std::string& name)
1253  {
1254    // get pointer from the map with all stored handlers
1255    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1256    if (mapIt == _getSingleton().keyHandlers_.end())
1257      return false;
1258    // see whether the handler already is in the list
1259    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1260          it != _getSingleton().activeKeyHandlers_.end(); it++)
1261    {
1262      if ((*it) == (*mapIt).second)
1263        return true;
1264    }
1265    return false;
1266  }
1267
1268
1269  // ###### MouseHandler ######
1270  /**
1271    @brief Adds a new mouse handler.
1272    @param handler Pointer to the handler object.
1273    @param name Unique name of the handler.
1274    @return True if added, false if name already existed.
1275  */
1276  bool InputManager::addMouseHandler(MouseHandler* handler, const std::string& name)
1277  {
1278    if (!handler)
1279      return false;
1280    if (_getSingleton().mouseHandlers_.find(name) == _getSingleton().mouseHandlers_.end())
1281    {
1282      _getSingleton().mouseHandlers_[name] = handler;
1283      return true;
1284    }
1285    else
1286      return false;
1287  }
1288
1289  /**
1290    @brief Removes a Mouse handler from the list.
1291    @param name Unique name of the handler.
1292    @return True if removal was successful, false if name was not found.
1293  */
1294  bool InputManager::removeMouseHandler(const std::string &name)
1295  {
1296    disableMouseHandler(name);
1297    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
1298    if (it != _getSingleton().mouseHandlers_.end())
1299    {
1300      _getSingleton().mouseHandlers_.erase(it);
1301      return true;
1302    }
1303    else
1304      return false;
1305  }
1306
1307  /**
1308    @brief Returns the pointer to a handler.
1309    @param name Unique name of the handler.
1310    @return Pointer to the instance, 0 if name was not found.
1311  */
1312  MouseHandler* InputManager::getMouseHandler(const std::string& name)
1313  {
1314    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
1315    if (it != _getSingleton().mouseHandlers_.end())
1316    {
1317      return (*it).second;
1318    }
1319    else
1320      return 0;
1321  }
1322
1323  /**
1324    @brief Enables a specific mouse handler that has already been added.
1325    @param name Unique name of the handler.
1326    @return False if name was not found, true otherwise.
1327  */
1328  bool InputManager::enableMouseHandler(const std::string& name)
1329  {
1330    // get pointer from the map with all stored handlers
1331    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1332    if (mapIt == _getSingleton().mouseHandlers_.end())
1333      return false;
1334    // see whether the handler already is in the list
1335    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1336          it != _getSingleton().activeMouseHandlers_.end(); it++)
1337    {
1338      if ((*it) == (*mapIt).second)
1339      {
1340        return true;
1341      }
1342    }
1343    _getSingleton().activeMouseHandlers_.push_back((*mapIt).second);
1344    _getSingleton().stateRequest_ = IS_CUSTOM;
1345    _getSingleton()._updateTickables();
1346    return true;
1347  }
1348
1349  /**
1350    @brief Disables a specific mouse handler.
1351    @param name Unique name of the handler.
1352    @return False if name was not found, true otherwise.
1353  */
1354  bool InputManager::disableMouseHandler(const std::string &name)
1355  {
1356    // get pointer from the map with all stored handlers
1357    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1358    if (mapIt == _getSingleton().mouseHandlers_.end())
1359      return false;
1360    // look for the handler in the list
1361    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1362          it != _getSingleton().activeMouseHandlers_.end(); it++)
1363    {
1364      if ((*it) == (*mapIt).second)
1365      {
1366        _getSingleton().activeMouseHandlers_.erase(it);
1367        _getSingleton().stateRequest_ = IS_CUSTOM;
1368        _getSingleton()._updateTickables();
1369        return true;
1370      }
1371    }
1372    return true;
1373  }
1374
1375  /**
1376    @brief Checks whether a mouse handler is active
1377    @param name Unique name of the handler.
1378    @return False if key handler is not active or doesn't exist, true otherwise.
1379  */
1380  bool InputManager::isMouseHandlerActive(const std::string& name)
1381  {
1382    // get pointer from the map with all stored handlers
1383    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1384    if (mapIt == _getSingleton().mouseHandlers_.end())
1385      return false;
1386    // see whether the handler already is in the list
1387    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1388          it != _getSingleton().activeMouseHandlers_.end(); it++)
1389    {
1390      if ((*it) == (*mapIt).second)
1391        return true;
1392    }
1393    return false;
1394  }
1395
1396
1397  // ###### JoyStickHandler ######
1398
1399  /**
1400    @brief Adds a new joy stick handler.
1401    @param handler Pointer to the handler object.
1402    @param name Unique name of the handler.
1403    @return True if added, false if name already existed.
1404  */
1405  bool InputManager::addJoyStickHandler(JoyStickHandler* handler, const std::string& name)
1406  {
1407    if (!handler)
1408      return false;
1409    if (_getSingleton().joyStickHandlers_.find(name) == _getSingleton().joyStickHandlers_.end())
1410    {
1411      _getSingleton().joyStickHandlers_[name] = handler;
1412      return true;
1413    }
1414    else
1415      return false;
1416  }
1417
1418  /**
1419    @brief Removes a JoyStick handler from the list.
1420    @param name Unique name of the handler.
1421    @return True if removal was successful, false if name was not found.
1422  */
1423  bool InputManager::removeJoyStickHandler(const std::string &name)
1424  {
1425    for (std::vector<OIS::JoyStick*>::iterator itstick = _getSingleton().joySticks_.begin();
1426          itstick != _getSingleton().joySticks_.end(); itstick++)
1427      disableJoyStickHandler(name, itstick - _getSingleton().joySticks_.begin());
1428
1429    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
1430    if (it != _getSingleton().joyStickHandlers_.end())
1431    {
1432      _getSingleton().joyStickHandlers_.erase(it);
1433      return true;
1434    }
1435    else
1436      return false;
1437  }
1438
1439  /**
1440    @brief Returns the pointer to a handler.
1441    @param name Unique name of the handler.
1442    @return Pointer to the instance, 0 if name was not found.
1443  */
1444  JoyStickHandler* InputManager::getJoyStickHandler(const std::string& name)
1445  {
1446    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
1447    if (it != _getSingleton().joyStickHandlers_.end())
1448    {
1449      return (*it).second;
1450    }
1451    else
1452      return 0;
1453  }
1454
1455  /**
1456    @brief Enables a specific joy stick handler that has already been added.
1457    @param name Unique name of the handler.
1458    @return False if name or id was not found, true otherwise.
1459  */
1460  bool InputManager::enableJoyStickHandler(const std::string& name, unsigned int ID)
1461  {
1462    // get handler pointer from the map with all stored handlers
1463    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1464    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1465      return false;
1466
1467    // check for existence of the ID
1468    if (ID >= _getSingleton().joySticksSize_)
1469      return false;
1470
1471    // see whether the handler already is in the list
1472    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1473          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1474    {
1475      if ((*it) == (*handlerIt).second)
1476      {
1477        return true;
1478      }
1479    }
1480    _getSingleton().activeJoyStickHandlers_[ID].push_back((*handlerIt).second);
1481    _getSingleton().stateRequest_ = IS_CUSTOM;
1482    _getSingleton()._updateTickables();
1483    return true;
1484  }
1485
1486  /**
1487    @brief Disables a specific joy stick handler.
1488    @param name Unique name of the handler.
1489    @return False if name or id was not found, true otherwise.
1490  */
1491  bool InputManager::disableJoyStickHandler(const std::string &name, unsigned int ID)
1492  {
1493    // get handler pointer from the map with all stored handlers
1494    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1495    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1496      return false;
1497
1498    // check for existence of the ID
1499    if (ID >= _getSingleton().joySticksSize_)
1500      return false;
1501
1502    // look for the handler in the list
1503    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1504          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1505    {
1506      if ((*it) == (*handlerIt).second)
1507      {
1508        _getSingleton().activeJoyStickHandlers_[ID].erase(it);
1509        _getSingleton().stateRequest_ = IS_CUSTOM;
1510        _getSingleton()._updateTickables();
1511        return true;
1512      }
1513    }
1514    return true;
1515  }
1516
1517  /**
1518    @brief Checks whether a joy stick handler is active
1519    @param name Unique name of the handler.
1520    @return False if key handler is not active or doesn't exist, true otherwise.
1521  */
1522  bool InputManager::isJoyStickHandlerActive(const std::string& name, unsigned int ID)
1523  {
1524    // get handler pointer from the map with all stored handlers
1525    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1526    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1527      return false;
1528
1529    // check for existence of the ID
1530    if (ID >= _getSingleton().joySticksSize_)
1531      return false;
1532
1533    // see whether the handler already is in the list
1534    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1535          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1536    {
1537      if ((*it) == (*handlerIt).second)
1538        return true;
1539    }
1540    return false;
1541  }
1542
1543}
Note: See TracBrowser for help on using the repository browser.