Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation2/src/libraries/core/input/KeyBinder.cc @ 6261

Last change on this file since 6261 was 6214, checked in by scheusso, 15 years ago

a small fix in IOConsole
some changes in GUI-system and preparation for keybindings menu
fix in menu handling

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