Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core4/src/core/input/KeyBinder.cc @ 3279

Last change on this file since 3279 was 3279, checked in by rgrieder, 15 years ago

Heavy clean up in the InputManager; not many real code changes though.
And temporary hack-fixed a problem in the Keybinder with std::vector.reserve(1000) ;)

  • Property svn:eol-style set to native
File size: 18.5 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 different input handlers.
32 */
33
34#include "KeyBinder.h"
35
36#include "util/Convert.h"
37#include "util/Debug.h"
38#include "core/ConfigValueIncludes.h"
39#include "core/CoreIncludes.h"
40#include "core/ConfigFileManager.h"
41#include "InputCommands.h"
42#include "InputManager.h"
43
44namespace orxonox
45{
46    /**
47    @brief
48        Constructor that does as little as necessary.
49    */
50    KeyBinder::KeyBinder()
51        : numberOfJoySticks_(0)
52        , deriveTime_(0.0f)
53    {
54        mouseRelative_[0] = 0;
55        mouseRelative_[1] = 0;
56        mousePosition_[0] = 0;
57        mousePosition_[1] = 0;
58
59        joyStickButtons_.reserve(1000);
60        joyStickAxes_.reserve(1000);
61
62        RegisterRootObject(KeyBinder);
63
64        // intialise all buttons and half axes to avoid creating everything with 'new'
65        // keys
66        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
67        {
68            std::string keyname = KeyCode::ByString[i];
69            if (!keyname.empty())
70                keys_[i].name_ = std::string("Key") + keyname;
71            else
72                keys_[i].name_ = "";
73            keys_[i].paramCommandBuffer_ = &paramCommandBuffer_;
74            keys_[i].groupName_ = "Keys";
75        }
76        // mouse buttons plus 4 mouse wheel buttons only 'generated' by KeyBinder
77        const char* const mouseWheelNames[] = { "Wheel1Down", "Wheel1Up", "Wheel2Down", "Wheel2Up" };
78        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
79        {
80            std::string nameSuffix;
81            if (i < MouseButtonCode::numberOfButtons)
82                nameSuffix = MouseButtonCode::ByString[i];
83            else
84                nameSuffix = mouseWheelNames[i - MouseButtonCode::numberOfButtons];
85            mouseButtons_[i].name_ = std::string("Mouse") + nameSuffix;
86            mouseButtons_[i].paramCommandBuffer_ = &paramCommandBuffer_;
87            mouseButtons_[i].groupName_ = "MouseButtons";
88        }
89        // mouse axes
90        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
91        {
92            mouseAxes_[i].name_ = std::string("Mouse") + MouseAxisCode::ByString[i / 2];
93            if (i & 1)
94                mouseAxes_[i].name_ += "Pos";
95            else
96                mouseAxes_[i].name_ += "Neg";
97            mouseAxes_[i].paramCommandBuffer_ = &paramCommandBuffer_;
98            mouseAxes_[i].groupName_ = "MouseAxes";
99        }
100
101        // We might not even load any bindings at all (KeyDetector for instance)
102        this->configFile_ = ConfigFileType::NoType;
103
104        // initialise joy sticks separatly to allow for reloading
105        numberOfJoySticks_ = InputManager::getInstance().getJoyStickQuantity();
106        initialiseJoyStickBindings();
107
108        // collect all Buttons and HalfAxes
109        compilePointerLists();
110
111        // set them here to use allHalfAxes_
112        setConfigValues();
113    }
114
115    /**
116    @brief
117        Destructor
118    */
119    KeyBinder::~KeyBinder()
120    {
121        // almost no destructors required because most of the arrays are static.
122        clearBindings(); // does some destruction work
123    }
124
125    /**
126    @brief
127        Loader for the key bindings, managed by config values.
128    */
129    void KeyBinder::setConfigValues()
130    {
131        SetConfigValue(analogThreshold_, 0.05f)
132            .description("Threshold for analog axes until which the state is 0.");
133        SetConfigValue(bFilterAnalogNoise_, false)
134            .description("Specifies whether to filter small analog values like joy stick fluctuations.");
135        SetConfigValue(mouseSensitivity_, 1.0f)
136            .description("Mouse sensitivity.");
137        SetConfigValue(bDeriveMouseInput_, false)
138            .description("Whether or not to derive moues movement for the absolute value.");
139        SetConfigValue(derivePeriod_, 0.05f)
140            .description("Accuracy of the mouse input deriver. The higher the more precise, but laggier.");
141        SetConfigValue(mouseSensitivityDerived_, 1.0f)
142            .description("Mouse sensitivity if mouse input is derived.");
143        SetConfigValue(mouseWheelStepSize_, 120)
144            .description("Equals one step of the mousewheel.");
145        SetConfigValue(buttonThreshold_, 0.80f)
146            .description("Threshold for analog axes until which the button is not pressed.")
147            .callback(this, &KeyBinder::buttonThresholdChanged);
148    }
149
150    void KeyBinder::buttonThresholdChanged()
151    {
152        for (unsigned int i = 0; i < allHalfAxes_.size(); i++)
153            if (!allHalfAxes_[i]->bButtonThresholdUser_)
154                allHalfAxes_[i]->buttonThreshold_ = this->buttonThreshold_;
155    }
156
157    void KeyBinder::JoyStickQuantityChanged(unsigned int value)
158    {
159        unsigned int oldValue = numberOfJoySticks_;
160        numberOfJoySticks_ = value;
161
162        // initialise joy stick bindings
163        initialiseJoyStickBindings();
164
165        // collect all Buttons and HalfAxes again
166        compilePointerLists();
167
168        // load the bindings if required
169        if (configFile_ != ConfigFileType::NoType)
170        {
171            for (unsigned int iDev = oldValue; iDev < numberOfJoySticks_; ++iDev)
172            {
173                for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; ++i)
174                    joyStickButtons_[iDev][i].readConfigValue(this->configFile_);
175                for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; ++i)
176                    joyStickAxes_[iDev][i].readConfigValue(this->configFile_);
177            }
178        }
179
180        // Set the button threshold for potential new axes
181        buttonThresholdChanged();
182    }
183
184    void KeyBinder::initialiseJoyStickBindings()
185    {
186        this->joyStickAxes_.resize(numberOfJoySticks_);
187        this->joyStickButtons_.resize(numberOfJoySticks_);
188
189        // reinitialise all joy stick binings (doesn't overwrite the old ones)
190        for (unsigned int iDev = 0; iDev < numberOfJoySticks_; iDev++)
191        {
192            std::string deviceNumber = multi_cast<std::string>(iDev);
193            // joy stick buttons
194            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
195            {
196                joyStickButtons_[iDev][i].name_ = std::string("JoyStick") + deviceNumber + JoyStickButtonCode::ByString[i];
197                joyStickButtons_[iDev][i].paramCommandBuffer_ = &paramCommandBuffer_;
198                joyStickButtons_[iDev][i].groupName_ = std::string("JoyStick") + deviceNumber + "Buttons";
199            }
200            // joy stick axes
201            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
202            {
203                joyStickAxes_[iDev][i].name_ = std::string("JoyStick") + deviceNumber + JoyStickAxisCode::ByString[i >> 1];
204                if (i & 1)
205                    joyStickAxes_[iDev][i].name_ += "Pos";
206                else
207                    joyStickAxes_[iDev][i].name_ += "Neg";
208                joyStickAxes_[iDev][i].paramCommandBuffer_ = &paramCommandBuffer_;
209                joyStickAxes_[iDev][i].groupName_ = std::string("JoyStick") + deviceNumber + "Axes";
210            }
211        }
212    }
213
214    void KeyBinder::compilePointerLists()
215    {
216        allButtons_.clear();
217        allHalfAxes_.clear();
218
219        // Note: Don't include the dummy keys which don't actually exist in OIS but have a number
220        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
221            if (!keys_[i].name_.empty())
222                allButtons_[keys_[i].name_] = keys_ + i;
223        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
224            allButtons_[mouseButtons_[i].name_] = mouseButtons_ + i;
225        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
226        {
227            allButtons_[mouseAxes_[i].name_] = mouseAxes_ + i;
228            allHalfAxes_.push_back(mouseAxes_ + i);
229        }
230        for (unsigned int iDev = 0; iDev < numberOfJoySticks_; iDev++)
231        {
232            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
233                allButtons_[joyStickButtons_[iDev][i].name_] = &(joyStickButtons_[iDev][i]);
234            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
235            {
236                allButtons_[joyStickAxes_[iDev][i].name_] = &(joyStickAxes_[iDev][i]);
237                allHalfAxes_.push_back(&(joyStickAxes_[iDev][i]));
238            }
239        }
240    }
241
242    /**
243    @brief
244        Loads the key and button bindings.
245    @return
246        True if loading succeeded.
247    */
248    void KeyBinder::loadBindings(const std::string& filename)
249    {
250        COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
251
252        if (filename.empty())
253            return;
254
255        if (this->configFile_ == ConfigFileType::NoType)
256        {
257            // Get a new ConfigFileType from the ConfigFileManager
258            this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
259        }
260
261        ConfigFileManager::getInstance().setFilename(this->configFile_, filename);
262
263        // Parse bindings and create the ConfigValueContainers if necessary
264        clearBindings();
265        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
266            it->second->readConfigValue(this->configFile_);
267
268        COUT(3) << "KeyBinder: Loading key bindings done." << std::endl;
269    }
270
271    bool KeyBinder::setBinding(const std::string& binding, const std::string& name, bool bTemporary)
272    {
273        std::map<std::string, Button*>::iterator it = allButtons_.find(name);
274        if (it != allButtons_.end())
275        {
276            if (bTemporary)
277                it->second->configContainer_->tset(binding);
278            else
279                it->second->configContainer_->set(binding);
280            it->second->configContainer_->getValue(&(it->second->bindingString_), it->second);
281            return true;
282        }
283        else
284        {
285            COUT(2) << "Could not find key/button/axis with name '" << name << "'." << std::endl;
286            return false;
287        }
288    }
289
290    /**
291    @brief
292        Overwrites all bindings with ""
293    */
294    void KeyBinder::clearBindings()
295    {
296        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
297            it->second->clear();
298
299        for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
300            delete paramCommandBuffer_[i];
301        paramCommandBuffer_.clear();
302    }
303
304    void KeyBinder::resetJoyStickAxes()
305    {
306        for (unsigned int iDev = 0; iDev < numberOfJoySticks_; ++iDev)
307        {
308            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
309            {
310                joyStickAxes_[iDev][i].absVal_ = 0.0f;
311                joyStickAxes_[iDev][i].relVal_ = 0.0f;
312            }
313        }
314    }
315
316    void KeyBinder::mouseUpdated(float dt)
317    {
318        if (bDeriveMouseInput_)
319        {
320            // only update when derivation dt has passed
321            if (deriveTime_ > derivePeriod_)
322            {
323                for (int i = 0; i < 2; i++)
324                {
325                    if (mouseRelative_[i] < 0)
326                    {
327                        mouseAxes_[2*i + 0].absVal_
328                            = -mouseRelative_[i] / deriveTime_ * 0.0005f * mouseSensitivityDerived_;
329                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
330                    }
331                    else if (mouseRelative_[i] > 0)
332                    {
333                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
334                        mouseAxes_[2*i + 1].absVal_
335                            =  mouseRelative_[i] / deriveTime_ * 0.0005f * mouseSensitivityDerived_;
336                    }
337                    else
338                    {
339                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
340                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
341                    }
342                    mouseRelative_[i] = 0;
343                    mouseAxes_[2*i + 0].hasChanged_ = true;
344                    mouseAxes_[2*i + 1].hasChanged_ = true;
345                }
346                deriveTime_ = 0.0f;
347            }
348            else
349                deriveTime_ += dt;
350        }
351
352        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
353        {
354            // Why dividing relative value by dt? The reason lies in the simple fact, that when you
355            // press a button that has relative movement, that value has to be multiplied by dt to be
356            // frame rate independent. This can easily (and only) be done in updateInput(float).
357            // Hence we need to divide by dt here for the mouse to compensate, because the relative
358            // move movements have nothing to do with dt.
359            if (dt != 0.0f)
360            {
361                // just ignore if dt == 0.0 because we have multiplied by 0.0 anyway..
362                mouseAxes_[i].relVal_ /= dt;
363            }
364
365            tickHalfAxis(mouseAxes_[i]);
366        }
367    }
368
369    void KeyBinder::joyStickUpdated(unsigned int joyStick, float dt)
370    {
371        for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
372        {
373            tickHalfAxis(joyStickAxes_[joyStick][i]);
374        }
375    }
376
377    void KeyBinder::tickHalfAxis(HalfAxis& halfAxis)
378    {
379        // button mode
380        // TODO: optimize out all the half axes that don't act as a button at the moment
381        if (halfAxis.hasChanged_)
382        {
383            if (!halfAxis.pressed_ && halfAxis.absVal_ > halfAxis.buttonThreshold_)
384            {
385                // key pressed event
386                halfAxis.pressed_ = true;
387                if (halfAxis.nCommands_[KeybindMode::OnPress])
388                    halfAxis.execute(KeybindMode::OnPress);
389            }
390            else if (halfAxis.pressed_ && halfAxis.absVal_ < halfAxis.buttonThreshold_)
391            {
392                // key released event
393                halfAxis.pressed_ = false;
394                if (halfAxis.nCommands_[KeybindMode::OnRelease])
395                    halfAxis.execute(KeybindMode::OnRelease);
396            }
397            halfAxis.hasChanged_ = false;
398        }
399
400        if (halfAxis.pressed_)
401        {
402            // key held event
403            if (halfAxis.nCommands_[KeybindMode::OnHold])
404                halfAxis.execute(KeybindMode::OnHold);
405        }
406
407        // these are the actually useful axis bindings for analog input
408        if (!bFilterAnalogNoise_ || halfAxis.relVal_ > analogThreshold_ || halfAxis.absVal_ > analogThreshold_)
409        {
410            halfAxis.execute();
411        }
412    }
413
414    /**
415    @brief
416        Event handler for the mouseMoved Event.
417    @param e
418        Mouse state information
419    */
420    void KeyBinder::mouseMoved(IntVector2 abs_, IntVector2 rel_, IntVector2 clippingSize)
421    {
422        // y axis of mouse input is inverted
423        int rel[] = { rel_.x, -rel_.y };
424
425        if (bDeriveMouseInput_)
426        {
427            mouseRelative_[0] += rel[0];
428            mouseRelative_[1] += rel[1];
429        }
430        else
431        {
432            for (int i = 0; i < 2; i++)
433            {
434                if (rel[i]) // performance opt. for the case that rel[i] == 0
435                {
436                    // write absolute values
437                    mouseAxes_[2*i + 0].hasChanged_ = true;
438                    mouseAxes_[2*i + 1].hasChanged_ = true;
439                    mousePosition_[i] += rel[i];
440
441                    // clip absolute position
442                    if (mousePosition_[i] > mouseClippingSize_)
443                        mousePosition_[i] =  mouseClippingSize_;
444                    if (mousePosition_[i] < -mouseClippingSize_)
445                        mousePosition_[i] = -mouseClippingSize_;
446
447                    if (mousePosition_[i] < 0)
448                    {
449                        mouseAxes_[2*i + 0].absVal_ =  -mousePosition_[i]/(float)mouseClippingSize_ * mouseSensitivity_;
450                        mouseAxes_[2*i + 1].absVal_ =  0.0f;
451                    }
452                    else
453                    {
454                        mouseAxes_[2*i + 0].absVal_ =  0.0f;
455                        mouseAxes_[2*i + 1].absVal_ =   mousePosition_[i]/(float)mouseClippingSize_ * mouseSensitivity_;
456                    }
457                }
458            }
459        }
460
461        // relative
462        for (int i = 0; i < 2; i++)
463        {
464            if (rel[i] < 0)
465                mouseAxes_[0 + 2*i].relVal_ = -((float)rel[i])/(float)mouseClippingSize_ * mouseSensitivity_;
466            else
467                mouseAxes_[1 + 2*i].relVal_ =  ((float)rel[i])/(float)mouseClippingSize_ * mouseSensitivity_;
468        }
469    }
470
471    /**
472    @brief Event handler for the mouseScrolled Event.
473    @param e Mouse state information
474    */
475    void KeyBinder::mouseScrolled(int abs, int rel)
476    {
477        if (rel < 0)
478            for (int i = 0; i < -rel/mouseWheelStepSize_; i++)
479                mouseButtons_[8].execute(KeybindMode::OnPress, ((float)abs)/mouseWheelStepSize_);
480        else
481            for (int i = 0; i < rel/mouseWheelStepSize_; i++)
482                mouseButtons_[9].execute(KeybindMode::OnPress, ((float)abs)/mouseWheelStepSize_);
483    }
484
485    void KeyBinder::axisMoved(unsigned int device, unsigned int axisID, float value)
486    {
487        int i = axisID * 2;
488        JoyStickAxisVector& axis = joyStickAxes_[device];
489        if (value < 0)
490        {
491            axis[i].absVal_ = -value;
492            axis[i].relVal_ = -value;
493            axis[i].hasChanged_ = true;
494            if (axis[i + 1].absVal_ > 0.0f)
495            {
496                axis[i + 1].absVal_ = -0.0f;
497                axis[i + 1].relVal_ = -0.0f;
498                axis[i + 1].hasChanged_ = true;
499            }
500        }
501        else
502        {
503            axis[i + 1].absVal_ = value;
504            axis[i + 1].relVal_ = value;
505            axis[i + 1].hasChanged_ = true;
506            if (axis[i].absVal_ > 0.0f)
507            {
508                axis[i].absVal_ = -0.0f;
509                axis[i].relVal_ = -0.0f;
510                axis[i].hasChanged_ = true;
511            }
512        }
513    }
514}
Note: See TracBrowser for help on using the repository browser.