Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/core/input/KeyBinder.cc @ 2896

Last change on this file since 2896 was 2896, checked in by landauf, 15 years ago

Merged gui branch back to trunk.

I did 2 small changes in IngameManager.cc on line 777 and 888 (yes, really), because const_reverse_iterator strangely doesn't work on MinGW.

  • 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 <fstream>
37#include <string>
38
39#include "util/Convert.h"
40#include "util/Debug.h"
41#include "core/ConfigValueIncludes.h"
42#include "core/CoreIncludes.h"
43#include "core/ConfigFileManager.h"
44#include "InputCommands.h"
45#include "InputManager.h"
46
47namespace orxonox
48{
49    /**
50    @brief
51        Constructor that does as little as necessary.
52    */
53    KeyBinder::KeyBinder()
54        : numberOfJoySticks_(0)
55        , deriveTime_(0.0f)
56    {
57        mouseRelative_[0] = 0;
58        mouseRelative_[1] = 0;
59        mousePosition_[0] = 0;
60        mousePosition_[1] = 0;
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        // Get a new ConfigFileType from the ConfigFileManager
102        this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
103
104        // initialise joy sticks separatly to allow for reloading
105        numberOfJoySticks_ = InputManager::getInstance().numberOfJoySticks();
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::JoyStickDeviceNumberChanged(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 = convertToString(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        ConfigFileManager::getInstance().setFilename(this->configFile_, filename);
256
257        // Parse bindings and create the ConfigValueContainers if necessary
258        clearBindings();
259        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
260            it->second->readConfigValue(this->configFile_);
261
262        COUT(3) << "KeyBinder: Loading key bindings done." << std::endl;
263    }
264
265    bool KeyBinder::setBinding(const std::string& binding, const std::string& name, bool bTemporary)
266    {
267        std::map<std::string, Button*>::iterator it = allButtons_.find(name);
268        if (it != allButtons_.end())
269        {
270            if (bTemporary)
271                it->second->configContainer_->tset(binding);
272            else
273                it->second->configContainer_->set(binding);
274            it->second->configContainer_->getValue(&(it->second->bindingString_), it->second);
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        Overwrites all bindings with ""
287    */
288    void KeyBinder::clearBindings()
289    {
290        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
291            it->second->clear();
292
293        for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
294            delete paramCommandBuffer_[i];
295        paramCommandBuffer_.clear();
296    }
297
298    void KeyBinder::resetJoyStickAxes()
299    {
300        for (unsigned int iDev = 0; iDev < numberOfJoySticks_; ++iDev)
301        {
302            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
303            {
304                joyStickAxes_[iDev][i].absVal_ = 0.0f;
305                joyStickAxes_[iDev][i].relVal_ = 0.0f;
306            }
307        }
308    }
309
310    void KeyBinder::updateMouse(float dt)
311    {
312        if (bDeriveMouseInput_)
313        {
314            // only update when derivation dt has passed
315            if (deriveTime_ > derivePeriod_)
316            {
317                for (int i = 0; i < 2; i++)
318                {
319                    if (mouseRelative_[i] < 0)
320                    {
321                        mouseAxes_[2*i + 0].absVal_
322                            = -mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
323                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
324                    }
325                    else if (mouseRelative_[i] > 0)
326                    {
327                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
328                        mouseAxes_[2*i + 1].absVal_
329                            =  mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
330                    }
331                    else
332                    {
333                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
334                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
335                    }
336                    mouseRelative_[i] = 0;
337                    mouseAxes_[2*i + 0].hasChanged_ = true;
338                    mouseAxes_[2*i + 1].hasChanged_ = true;
339                }
340                deriveTime_ = 0.0f;
341            }
342            else
343                deriveTime_ += dt;
344        }
345
346        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
347        {
348            // Why dividing relative value by dt? The reason lies in the simple fact, that when you
349            // press a button that has relative movement, that value has to be multiplied by dt to be
350            // frame rate independent. This can easily (and only) be done in updateInput(float).
351            // Hence we need to divide by dt here for the mouse to compensate, because the relative
352            // move movements have nothing to do with dt.
353            if (dt != 0.0f)
354            {
355                // just ignore if dt == 0.0 because we have multiplied by 0.0 anyway..
356                mouseAxes_[i].relVal_ /= dt;
357            }
358
359            tickHalfAxis(mouseAxes_[i]);
360        }
361    }
362
363    void KeyBinder::updateJoyStick(float dt, unsigned int joyStick)
364    {
365        for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
366        {
367            tickHalfAxis(joyStickAxes_[joyStick][i]);
368        }
369    }
370
371    void KeyBinder::tickHalfAxis(HalfAxis& halfAxis)
372    {
373        // button mode
374        // TODO: optimize out all the half axes that don't act as a button at the moment
375        if (halfAxis.hasChanged_)
376        {
377            if (!halfAxis.pressed_ && halfAxis.absVal_ > halfAxis.buttonThreshold_)
378            {
379                // key pressed event
380                halfAxis.pressed_ = true;
381                if (halfAxis.nCommands_[KeybindMode::OnPress])
382                    halfAxis.execute(KeybindMode::OnPress);
383            }
384            else if (halfAxis.pressed_ && halfAxis.absVal_ < halfAxis.buttonThreshold_)
385            {
386                // key released event
387                halfAxis.pressed_ = false;
388                if (halfAxis.nCommands_[KeybindMode::OnRelease])
389                    halfAxis.execute(KeybindMode::OnRelease);
390            }
391            halfAxis.hasChanged_ = false;
392        }
393
394        if (halfAxis.pressed_)
395        {
396            // key held event
397            if (halfAxis.nCommands_[KeybindMode::OnHold])
398                halfAxis.execute(KeybindMode::OnHold);
399        }
400
401        // these are the actually useful axis bindings for analog input
402        if (!bFilterAnalogNoise_ || halfAxis.relVal_ > analogThreshold_ || halfAxis.absVal_ > analogThreshold_)
403        {
404            halfAxis.execute();
405        }
406    }
407
408    /**
409    @brief
410        Event handler for the mouseMoved Event.
411    @param e
412        Mouse state information
413    */
414    void KeyBinder::mouseMoved(IntVector2 abs_, IntVector2 rel_, IntVector2 clippingSize)
415    {
416        // y axis of mouse input is inverted
417        int rel[] = { rel_.x, -rel_.y };
418
419        if (bDeriveMouseInput_)
420        {
421            mouseRelative_[0] += rel[0];
422            mouseRelative_[1] += rel[1];
423        }
424        else
425        {
426            for (int i = 0; i < 2; i++)
427            {
428                if (rel[i]) // performance opt. for the case that rel[i] == 0
429                {
430                    // write absolute values
431                    mouseAxes_[2*i + 0].hasChanged_ = true;
432                    mouseAxes_[2*i + 1].hasChanged_ = true;
433                    mousePosition_[i] += rel[i];
434
435                    // clip absolute position
436                    if (mousePosition_[i] > mouseClippingSize_)
437                        mousePosition_[i] =  mouseClippingSize_;
438                    if (mousePosition_[i] < -mouseClippingSize_)
439                        mousePosition_[i] = -mouseClippingSize_;
440
441                    if (mousePosition_[i] < 0)
442                    {
443                        mouseAxes_[2*i + 0].absVal_ =  -mousePosition_[i]/(float)mouseClippingSize_ * mouseSensitivity_;
444                        mouseAxes_[2*i + 1].absVal_ =  0.0f;
445                    }
446                    else
447                    {
448                        mouseAxes_[2*i + 0].absVal_ =  0.0f;
449                        mouseAxes_[2*i + 1].absVal_ =   mousePosition_[i]/(float)mouseClippingSize_ * mouseSensitivity_;
450                    }
451                }
452            }
453        }
454
455        // relative
456        for (int i = 0; i < 2; i++)
457        {
458            if (rel[i] < 0)
459                mouseAxes_[0 + 2*i].relVal_ = -((float)rel[i])/(float)mouseClippingSize_ * mouseSensitivity_;
460            else
461                mouseAxes_[1 + 2*i].relVal_ =  ((float)rel[i])/(float)mouseClippingSize_ * mouseSensitivity_;
462        }
463    }
464
465    /**
466    @brief Event handler for the mouseScrolled Event.
467    @param e Mouse state information
468    */
469    void KeyBinder::mouseScrolled(int abs, int rel)
470    {
471        if (rel < 0)
472            for (int i = 0; i < -rel/mouseWheelStepSize_; i++)
473                mouseButtons_[8].execute(KeybindMode::OnPress, ((float)abs)/mouseWheelStepSize_);
474        else
475            for (int i = 0; i < rel/mouseWheelStepSize_; i++)
476                mouseButtons_[9].execute(KeybindMode::OnPress, ((float)abs)/mouseWheelStepSize_);
477    }
478
479    void KeyBinder::joyStickAxisMoved(unsigned int joyStickID, unsigned int axis, float value)
480    {
481        int i = axis * 2;
482        if (value < 0)
483        {
484            joyStickAxes_[joyStickID][i].absVal_ = -value;
485            joyStickAxes_[joyStickID][i].relVal_ = -value;
486            joyStickAxes_[joyStickID][i].hasChanged_ = true;
487            if (joyStickAxes_[joyStickID][i + 1].absVal_ > 0.0f)
488            {
489                joyStickAxes_[joyStickID][i + 1].absVal_ = -0.0f;
490                joyStickAxes_[joyStickID][i + 1].relVal_ = -0.0f;
491                joyStickAxes_[joyStickID][i + 1].hasChanged_ = true;
492            }
493        }
494        else
495        {
496            joyStickAxes_[joyStickID][i + 1].absVal_ = value;
497            joyStickAxes_[joyStickID][i + 1].relVal_ = value;
498            joyStickAxes_[joyStickID][i + 1].hasChanged_ = true;
499            if (joyStickAxes_[joyStickID][i].absVal_ > 0.0f)
500            {
501                joyStickAxes_[joyStickID][i].absVal_ = -0.0f;
502                joyStickAxes_[joyStickID][i].relVal_ = -0.0f;
503                joyStickAxes_[joyStickID][i].hasChanged_ = true;
504            }
505        }
506    }
507}
Note: See TracBrowser for help on using the repository browser.