Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6155 was 6155, checked in by rgrieder, 14 years ago

Fixed mouse position problem: Internal value could still be larger than 1.

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