Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource2/src/core/input/KeyBinder.cc @ 5663

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

Fixed a known bug that occurred when reloading the inputmanager with a new joy stick plugged in.

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