Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 12066 was 11106, checked in by muemart, 8 years ago

Fix a memory leak. Also fix some potentially invalid references to vector elements after the vector resized.

  • Property svn:eol-style set to native
File size: 26.4 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
[1413]29#include "KeyBinder.h"
[2662]30
[6417]31#include <algorithm>
32#include <sstream>
[1293]33#include "util/Convert.h"
[8858]34#include "util/Output.h"
[5929]35#include "util/Exception.h"
[1519]36#include "core/CoreIncludes.h"
[9667]37#include "core/config/ConfigValueIncludes.h"
38#include "core/config/ConfigFile.h"
[10624]39#include "core/ApplicationPaths.h"
40#include "core/ConfigurablePaths.h"
[1520]41#include "InputCommands.h"
[3327]42#include "JoyStick.h"
[971]43
44namespace orxonox
45{
[10624]46    RegisterAbstractClass(KeyBinder).inheritsFrom<JoyStickQuantityListener>();
47
[1755]48    /**
49    @brief
50        Constructor that does as little as necessary.
51    */
[5929]52    KeyBinder::KeyBinder(const std::string& filename)
[3327]53        : deriveTime_(0.0f)
[5929]54        , filename_(filename)
[11071]55        , configFile_(nullptr)
56        , fallbackConfigFile_(nullptr)
[1755]57    {
58        mouseRelative_[0] = 0;
59        mouseRelative_[1] = 0;
[6417]60        mousePosition_[0] = 0.0;
61        mousePosition_[1] = 0.0;
[1391]62
[9667]63        RegisterObject(KeyBinder);
[1293]64
[6428]65        // initialise all buttons and half axes to avoid creating everything with 'new'
[1755]66        // keys
[1887]67        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
[1755]68        {
[11083]69            const std::string keyname = KeyCode::ByString[i];
[1887]70            if (!keyname.empty())
71                keys_[i].name_ = std::string("Key") + keyname;
72            else
[6417]73                keys_[i].name_.clear();
[1887]74            keys_[i].paramCommandBuffer_ = &paramCommandBuffer_;
75            keys_[i].groupName_ = "Keys";
[1755]76        }
[1887]77        // mouse buttons plus 4 mouse wheel buttons only 'generated' by KeyBinder
78        const char* const mouseWheelNames[] = { "Wheel1Down", "Wheel1Up", "Wheel2Down", "Wheel2Up" };
79        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
[1755]80        {
[1887]81            std::string nameSuffix;
82            if (i < MouseButtonCode::numberOfButtons)
83                nameSuffix = MouseButtonCode::ByString[i];
84            else
85                nameSuffix = mouseWheelNames[i - MouseButtonCode::numberOfButtons];
[3327]86            mouseButtons_[i].name_ = nameSuffix;
[1887]87            mouseButtons_[i].paramCommandBuffer_ = &paramCommandBuffer_;
88            mouseButtons_[i].groupName_ = "MouseButtons";
[1755]89        }
[1887]90        // mouse axes
91        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
92        {
[3327]93            mouseAxes_[i].name_ = MouseAxisCode::ByString[i / 2];
[1887]94            if (i & 1)
95                mouseAxes_[i].name_ += "Pos";
96            else
97                mouseAxes_[i].name_ += "Neg";
98            mouseAxes_[i].paramCommandBuffer_ = &paramCommandBuffer_;
99            mouseAxes_[i].groupName_ = "MouseAxes";
100        }
[1755]101
[1887]102        // initialise joy sticks separatly to allow for reloading
[3327]103        this->JoyStickQuantityChanged(this->getJoyStickList());
[1887]104
105        // set them here to use allHalfAxes_
106        setConfigValues();
[5929]107
108        // Load the bindings if filename was given
109        if (!this->filename_.empty())
110            this->loadBindings();
[1413]111    }
112
[1755]113    /**
114    @brief
115        Destructor
116    */
117    KeyBinder::~KeyBinder()
[1413]118    {
[1755]119        // almost no destructors required because most of the arrays are static.
120        clearBindings(); // does some destruction work
[6536]121        if (this->configFile_)
122            delete this->configFile_;
123        if (this->fallbackConfigFile_)
124            delete this->fallbackConfigFile_;
[1413]125    }
126
[1755]127    /**
128    @brief
129        Loader for the key bindings, managed by config values.
130    */
131    void KeyBinder::setConfigValues()
132    {
133        SetConfigValue(analogThreshold_, 0.05f)
134            .description("Threshold for analog axes until which the state is 0.");
[2087]135        SetConfigValue(bFilterAnalogNoise_, false)
136            .description("Specifies whether to filter small analog values like joy stick fluctuations.");
[6417]137        SetConfigValue(mouseSensitivity_, 3.0f)
[1755]138            .description("Mouse sensitivity.");
[6417]139        this->totalMouseSensitivity_ = this->mouseSensitivity_ / this->mouseClippingSize_;
[1755]140        SetConfigValue(bDeriveMouseInput_, false)
141            .description("Whether or not to derive moues movement for the absolute value.");
142        SetConfigValue(derivePeriod_, 0.05f)
143            .description("Accuracy of the mouse input deriver. The higher the more precise, but laggier.");
144        SetConfigValue(mouseSensitivityDerived_, 1.0f)
145            .description("Mouse sensitivity if mouse input is derived.");
[2087]146        SetConfigValue(mouseWheelStepSize_, 120)
[1887]147            .description("Equals one step of the mousewheel.");
[1755]148        SetConfigValue(buttonThreshold_, 0.80f)
[1887]149            .description("Threshold for analog axes until which the button is not pressed.")
150            .callback(this, &KeyBinder::buttonThresholdChanged);
151    }
[973]152
[1887]153    void KeyBinder::buttonThresholdChanged()
154    {
[11071]155        for (HalfAxis* halfAxis : allHalfAxes_)
156            if (!halfAxis->bButtonThresholdUser_)
157                halfAxis->buttonThreshold_ = this->buttonThreshold_;
[1755]158    }
[1293]159
[3327]160    void KeyBinder::JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList)
[1755]161    {
[3327]162        unsigned int oldValue = joySticks_.size();
163        joySticks_ = joyStickList;
[1887]164
165        // initialise joy stick bindings
166        initialiseJoyStickBindings();
167
168        // collect all Buttons and HalfAxes again
169        compilePointerLists();
170
171        // load the bindings if required
[11071]172        if (configFile_ != nullptr)
[1755]173        {
[3327]174            for (unsigned int iDev = oldValue; iDev < joySticks_.size(); ++iDev)
[1887]175            {
176                for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; ++i)
[6536]177                    (*joyStickButtons_[iDev])[i].readBinding(this->configFile_, this->fallbackConfigFile_);
[1887]178                for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; ++i)
[6536]179                    (*joyStickAxes_[iDev])[i].readBinding(this->configFile_, this->fallbackConfigFile_);
[1887]180            }
[1755]181        }
[1293]182
[1887]183        // Set the button threshold for potential new axes
184        buttonThresholdChanged();
185    }
186
187    void KeyBinder::initialiseJoyStickBindings()
188    {
[5695]189        while (joyStickAxes_.size() < joySticks_.size())
[11071]190            joyStickAxes_.push_back(std::make_shared<JoyStickAxisVector>());
[5695]191        while (joyStickButtons_.size() < joySticks_.size())
[11071]192            joyStickButtons_.push_back(std::make_shared<JoyStickButtonVector>());
[5695]193        // For the case the new size is smaller
[3327]194        this->joyStickAxes_.resize(joySticks_.size());
195        this->joyStickButtons_.resize(joySticks_.size());
[1887]196
[6417]197        // reinitialise all joy stick bindings (doesn't overwrite the old ones)
[3327]198        for (unsigned int iDev = 0; iDev < joySticks_.size(); iDev++)
[1755]199        {
[6417]200            const std::string& deviceName = joySticks_[iDev]->getDeviceName();
[1887]201            // joy stick buttons
202            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
203            {
[5695]204                (*joyStickButtons_[iDev])[i].name_ = JoyStickButtonCode::ByString[i];
205                (*joyStickButtons_[iDev])[i].paramCommandBuffer_ = &paramCommandBuffer_;
206                (*joyStickButtons_[iDev])[i].groupName_ = "JoyStickButtons_" + deviceName;
[1887]207            }
208            // joy stick axes
209            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
210            {
[5695]211                (*joyStickAxes_[iDev])[i].name_ = JoyStickAxisCode::ByString[i / 2];
[1887]212                if (i & 1)
[5695]213                    (*joyStickAxes_[iDev])[i].name_ += "Pos";
[1887]214                else
[5695]215                    (*joyStickAxes_[iDev])[i].name_ += "Neg";
216                (*joyStickAxes_[iDev])[i].paramCommandBuffer_ = &paramCommandBuffer_;
217                (*joyStickAxes_[iDev])[i].groupName_ = "JoyStickAxes_" + deviceName;
[1887]218            }
219        }
220    }
[973]221
[1887]222    void KeyBinder::compilePointerLists()
223    {
224        allButtons_.clear();
225        allHalfAxes_.clear();
226
[2662]227        // Note: Don't include the dummy keys which don't actually exist in OIS but have a number
[1887]228        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
[2662]229            if (!keys_[i].name_.empty())
[6417]230                allButtons_[keys_[i].groupName_ + '.' + keys_[i].name_] = keys_ + i;
[1887]231        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
[6417]232            allButtons_[mouseButtons_[i].groupName_ + '.' + mouseButtons_[i].name_] = mouseButtons_ + i;
[1887]233        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
234        {
[6417]235            allButtons_[mouseAxes_[i].groupName_ + '.' + mouseAxes_[i].name_] = mouseAxes_ + i;
[1887]236            allHalfAxes_.push_back(mouseAxes_ + i);
[1755]237        }
[3327]238        for (unsigned int iDev = 0; iDev < joySticks_.size(); iDev++)
[1887]239        {
240            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
[6417]241                allButtons_[(*joyStickButtons_[iDev])[i].groupName_ + '.' + (*joyStickButtons_[iDev])[i].name_] = &((*joyStickButtons_[iDev])[i]);
[1887]242            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
243            {
[6417]244                allButtons_[(*joyStickAxes_[iDev])[i].groupName_ + '.' + (*joyStickAxes_[iDev])[i].name_] = &((*joyStickAxes_[iDev])[i]);
[5695]245                allHalfAxes_.push_back(&((*joyStickAxes_[iDev])[i]));
[1887]246            }
247        }
[1349]248    }
249
[1755]250    /**
251    @brief
[1887]252        Loads the key and button bindings.
[1755]253    */
[5929]254    void KeyBinder::loadBindings()
[1349]255    {
[8858]256        orxout(internal_info, context::input) << "KeyBinder: Loading key bindings..." << endl;
[1428]257
[10624]258        this->configFile_ = new ConfigFile(this->filename_, !ApplicationPaths::buildDirectoryRun());
[6536]259        this->configFile_->load();
[1293]260
[10624]261        if (ApplicationPaths::buildDirectoryRun())
[6536]262        {
263            // Dev users should have combined key bindings files
[10624]264            std::string defaultFilepath(ConfigurablePaths::getDataPathString() + ConfigFile::DEFAULT_CONFIG_FOLDER + '/' + this->filename_);
[6536]265            std::ifstream file(defaultFilepath.c_str());
266            if (file.is_open())
267            {
268                file.close();
269                // Open the default file for later use (use absolute path!)
270                this->fallbackConfigFile_ = new ConfigFile(defaultFilepath, false);
271                this->fallbackConfigFile_->load();
272            }
273        }
[3280]274
[1887]275        // Parse bindings and create the ConfigValueContainers if necessary
[11071]276        for (const auto& mapEntry : allButtons_)
[6417]277        {
[11071]278            mapEntry.second->readBinding(this->configFile_, this->fallbackConfigFile_);
279            addButtonToCommand(mapEntry.second->bindingString_, mapEntry.second);
[6417]280        }
[1349]281
[8858]282        orxout(internal_info, context::input) << "KeyBinder: Loading key bindings done." << endl;
[1887]283    }
284
285    bool KeyBinder::setBinding(const std::string& binding, const std::string& name, bool bTemporary)
286    {
287        std::map<std::string, Button*>::iterator it = allButtons_.find(name);
288        if (it != allButtons_.end())
289        {
[6417]290            addButtonToCommand(binding, it->second);
[6536]291            std::string str = binding;
[10624]292            if (ApplicationPaths::buildDirectoryRun() && binding.empty())
[6536]293                str = "NoBinding";
294            it->second->setBinding(this->configFile_, this->fallbackConfigFile_, binding, bTemporary);
[1887]295            return true;
296        }
297        else
298        {
[8858]299            orxout(internal_warning, context::input) << "Could not find key/button/axis with name '" << name << "'." << endl;
[1887]300            return false;
301        }
302    }
303
[6417]304     void KeyBinder::addButtonToCommand(const std::string& command, Button* button)
305     {
306        std::ostringstream stream;
307        stream << button->groupName_  << '.' << button->name_;
308
309        std::vector<std::string>& oldKeynames = this->allCommands_[button->bindingString_];
310        std::vector<std::string>::iterator it = std::find(oldKeynames.begin(), oldKeynames.end(), stream.str());
[6422]311        if (it != oldKeynames.end())
[6417]312            oldKeynames.erase(it);
313
314        if (!command.empty())
315        {
316            std::vector<std::string>& keynames = this->allCommands_[command];
[6422]317            if (std::find(keynames.begin(), keynames.end(), stream.str()) == keynames.end())
[6417]318                this->allCommands_[command].push_back(stream.str());
319        }
320     }
321
[1887]322    /**
323    @brief
[6417]324        Return the first key name for a specific command
325    */
[11106]326    std::string KeyBinder::getBinding(const std::string& commandName)
[6417]327    {
[6422]328        if (this->allCommands_.find(commandName) != this->allCommands_.end())
[6417]329        {
330            std::vector<std::string>& keynames = this->allCommands_[commandName];
331            return keynames.front();
332        }
333
334        return BLANKSTRING;
335    }
336
337    /**
338    @brief
339        Return the key name for a specific command at a given index.
340    @param commandName
341        The command name the key name is returned for.
342    @param index
343        The index at which the key name is returned for.
344    */
[11106]345    std::string KeyBinder::getBinding(const std::string& commandName, unsigned int index)
[6417]346    {
[6422]347        if (this->allCommands_.find(commandName) != this->allCommands_.end())
[6417]348        {
349            std::vector<std::string>& keynames = this->allCommands_[commandName];
[6422]350            if (index < keynames.size())
[6417]351                return keynames[index];
352
353            return BLANKSTRING;
354        }
355
356        return BLANKSTRING;
357    }
358
359    /**
360    @brief
[11052]361        Return the first key name for a specific command in a human readable form
362    */
[11106]363    std::string KeyBinder::getBindingReadable(const std::string& commandName)
[11052]364    {
[11106]365        std::string binding = this->getBinding(commandName);
[11052]366
367        SubString substring = SubString(binding, ".");
368        std::string name;
369        std::string group;
370        switch(substring.size())
371        {
372            case 0:
373                return binding;
374            case 1:
375                return binding;
376            case 2:
377                group = substring[0];
378            default:
379                name = substring.subSet(1).join(".");
380        }
381
382        std::stringstream stream;
383        if(group.compare("Keys") == 0)
384            stream << "Key " << name.substr(3);
385        else if(group.compare("MouseButtons") == 0)
386            stream << "Mouse " << name;
387        else if(group.compare("JoyStickButtons") == 0)
388            stream << "Joystick " << name;
389        else if(group.compare("JoyStickAxes") == 0)
390            stream << "Joystick Axis" << name.substr(5, 6) << name.substr(name.find("Axis")+6);
391        else if(group.compare("MouseAxes") == 0)
392            stream << "Mouse " << name.substr(1,3) << " " << name.substr(0, 1) << "-Axis";
393        else
394            return binding;
395
[11106]396        binding = stream.str();
397        return binding;
[11052]398    }
399
400    /**
401    @brief
[6417]402        Get the number of different key bindings of a specific command.
403    @param commandName
404        The command.
405    */
406    unsigned int KeyBinder::getNumberOfBindings(const std::string& commandName)
407    {
[6422]408        if (this->allCommands_.find(commandName) != this->allCommands_.end())
[6417]409        {
410            std::vector<std::string>& keynames = this->allCommands_[commandName];
411            return keynames.size();
412        }
413
414        return 0;
415    }
416
417    /**
418    @brief
[1887]419        Overwrites all bindings with ""
420    */
421    void KeyBinder::clearBindings()
422    {
[11071]423        for (const auto& mapEntry : allButtons_)
424            mapEntry.second->clear();
[1887]425
[11071]426        for (BufferedParamCommand* command : paramCommandBuffer_)
427            delete command;
[1755]428        paramCommandBuffer_.clear();
429    }
[1349]430
[7861]431    /**
432        @brief Changes the keybind mode of a given console command.
433    */
434    void KeyBinder::changeMode(ConsoleCommand* command, KeybindMode::Value new_mode)
435    {
436        // iterate over all buttons
[11071]437        for (const auto& mapEntry : this->allButtons_)
[7861]438        {
[11071]439            Button* button = mapEntry.second;
[7861]440
441            // iterate over all modes
[8351]442            for (int mode_index = 0; mode_index < 3; ++mode_index)
[7861]443            {
[8351]444                if (mode_index == new_mode) // skip commands that are already in the desired mode
[7861]445                    continue;
446
447                // iterate over all commands of the given mode at the given button
448                for (size_t command_index = 0; command_index < button->nCommands_[mode_index]; ++command_index)
449                {
[7891]450                    if (button->commands_[mode_index][command_index]->hasFixedKeybindMode())
451                        continue;
452
[7861]453                    CommandEvaluation* evaluation = button->commands_[mode_index][command_index]->getEvaluation();
454
455                    // compare the command
456                    if (evaluation && evaluation->getConsoleCommand() == command)
457                    {
458                        // increase array of new mode
459                        BaseCommand** array_new_mode = new BaseCommand*[button->nCommands_[new_mode] + 1];
460                        // copy array content
461                        for (size_t c = 0; c < button->nCommands_[new_mode]; ++c)
462                            array_new_mode[c] = button->commands_[new_mode][c];
463                        // insert changed command at the end
464                        array_new_mode[button->nCommands_[new_mode]] = button->commands_[mode_index][command_index];
465                        // delete old array
466                        delete[] button->commands_[new_mode];
467                        // assign new array
468                        button->commands_[new_mode] = array_new_mode;
469                        // increase counter
470                        button->nCommands_[new_mode]++;
471
472                        // erase command from old array
473                        for (size_t c = command_index; c < button->nCommands_[mode_index] - 1; ++c)
474                            button->commands_[mode_index][c] = button->commands_[mode_index][c + 1];
475                        // decrease counter
476                        button->nCommands_[mode_index]--;
[8079]477                        // old array would not get deleted if nCommands_ is now 0
478                        // otherwise: nobody cares about an array that is one element too large - nCommands_ defines the size
479                        if (button->nCommands_[mode_index] == 0)
480                        {
481                            delete[] button->commands_[mode_index];
[11071]482                            button->commands_[mode_index] = nullptr;
[8079]483                        }
[7861]484
485                        // decrement the index since we shifted the array and continue searching for more occurrences of the command
486                        command_index--;
487                    }
488                }
489            }
490        }
491    }
492
[1755]493    void KeyBinder::resetJoyStickAxes()
[1461]494    {
[3327]495        for (unsigned int iDev = 0; iDev < joySticks_.size(); ++iDev)
[1887]496            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
[7859]497                (*joyStickAxes_[iDev])[i].reset();
[1461]498    }
499
[7859]500    /**
501        @brief Sets the position of the mouse back to 0/0.
502    */
503    void KeyBinder::resetMouseAxes()
504    {
505        this->mousePosition_[0] = 0.0f;
506        this->mousePosition_[1] = 0.0f;
507
[11071]508        for (HalfAxis& axis : mouseAxes_)
509            axis.reset();
[7859]510    }
511
[3327]512    void KeyBinder::mouseUpdated(float dt)
[1349]513    {
[1755]514        if (bDeriveMouseInput_)
[1349]515        {
[2662]516            // only update when derivation dt has passed
[1755]517            if (deriveTime_ > derivePeriod_)
518            {
519                for (int i = 0; i < 2; i++)
520                {
[2662]521                    if (mouseRelative_[i] < 0)
[1755]522                    {
[1887]523                        mouseAxes_[2*i + 0].absVal_
[3196]524                            = -mouseRelative_[i] / deriveTime_ * 0.0005f * mouseSensitivityDerived_;
[1887]525                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
[1755]526                    }
[2662]527                    else if (mouseRelative_[i] > 0)
[1755]528                    {
[1887]529                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
530                        mouseAxes_[2*i + 1].absVal_
[3196]531                            =  mouseRelative_[i] / deriveTime_ * 0.0005f * mouseSensitivityDerived_;
[1755]532                    }
533                    else
534                    {
[1887]535                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
536                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
[1755]537                    }
538                    mouseRelative_[i] = 0;
[1887]539                    mouseAxes_[2*i + 0].hasChanged_ = true;
540                    mouseAxes_[2*i + 1].hasChanged_ = true;
[1755]541                }
542                deriveTime_ = 0.0f;
543            }
544            else
545                deriveTime_ += dt;
[1349]546        }
[1219]547
[11071]548        for (HalfAxis& axis : mouseAxes_)
[1349]549        {
[2087]550            // Why dividing relative value by dt? The reason lies in the simple fact, that when you
551            // press a button that has relative movement, that value has to be multiplied by dt to be
[2896]552            // frame rate independent. This can easily (and only) be done in updateInput(float).
[2087]553            // Hence we need to divide by dt here for the mouse to compensate, because the relative
554            // move movements have nothing to do with dt.
555            if (dt != 0.0f)
[1755]556            {
[2087]557                // just ignore if dt == 0.0 because we have multiplied by 0.0 anyway..
[11071]558                axis.relVal_ /= dt;
[1755]559            }
560
[11071]561            tickHalfAxis(axis);
[2087]562        }
563    }
564
[3327]565    void KeyBinder::joyStickUpdated(unsigned int joyStick, float dt)
[2087]566    {
567        for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
568        {
[5695]569            tickHalfAxis((*joyStickAxes_[joyStick])[i]);
[2087]570        }
571    }
572
573    void KeyBinder::tickHalfAxis(HalfAxis& halfAxis)
574    {
575        // button mode
576        // TODO: optimize out all the half axes that don't act as a button at the moment
577        if (halfAxis.hasChanged_)
578        {
579            if (!halfAxis.pressed_ && halfAxis.absVal_ > halfAxis.buttonThreshold_)
[1755]580            {
[2087]581                // key pressed event
582                halfAxis.pressed_ = true;
583                if (halfAxis.nCommands_[KeybindMode::OnPress])
584                    halfAxis.execute(KeybindMode::OnPress);
[1755]585            }
[2087]586            else if (halfAxis.pressed_ && halfAxis.absVal_ < halfAxis.buttonThreshold_)
[1755]587            {
[2087]588                // key released event
589                halfAxis.pressed_ = false;
590                if (halfAxis.nCommands_[KeybindMode::OnRelease])
591                    halfAxis.execute(KeybindMode::OnRelease);
[1755]592            }
[2087]593            halfAxis.hasChanged_ = false;
[1349]594        }
[2087]595
596        if (halfAxis.pressed_)
597        {
598            // key held event
599            if (halfAxis.nCommands_[KeybindMode::OnHold])
600                halfAxis.execute(KeybindMode::OnHold);
601        }
602
603        // these are the actually useful axis bindings for analog input
[6417]604        halfAxis.execute();
[1349]605    }
606
[1755]607    /**
608    @brief
609        Event handler for the mouseMoved Event.
[7401]610    @param abs_
611        The absolute position of the mouse
612    @param rel_
613        The relative movement of the mouse
614    @param clippingSize
615        Mouse screen area in pixels (usually 1024x1024)
[1755]616    */
617    void KeyBinder::mouseMoved(IntVector2 abs_, IntVector2 rel_, IntVector2 clippingSize)
618    {
619        // y axis of mouse input is inverted
620        int rel[] = { rel_.x, -rel_.y };
[1349]621
[2087]622        if (bDeriveMouseInput_)
[1755]623        {
[2087]624            mouseRelative_[0] += rel[0];
625            mouseRelative_[1] += rel[1];
626        }
627        else
628        {
[1755]629            for (int i = 0; i < 2; i++)
630            {
[2662]631                if (rel[i]) // performance opt. for the case that rel[i] == 0
[1755]632                {
[1887]633                    // write absolute values
634                    mouseAxes_[2*i + 0].hasChanged_ = true;
635                    mouseAxes_[2*i + 1].hasChanged_ = true;
[6417]636                    mousePosition_[i] += rel[i] * totalMouseSensitivity_;
[1349]637
[1887]638                    // clip absolute position
[6417]639                    if (mousePosition_[i] > 1.0)
640                        mousePosition_[i] =  1.0;
641                    if (mousePosition_[i] < -1.0)
642                        mousePosition_[i] = -1.0;
[1428]643
[6417]644                    if (mousePosition_[i] < 0.0)
[1755]645                    {
[6417]646                        mouseAxes_[2*i + 0].absVal_ = -mousePosition_[i];
[3301]647                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
[1755]648                    }
649                    else
650                    {
[3301]651                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
[6417]652                        mouseAxes_[2*i + 1].absVal_ =  mousePosition_[i];
[1755]653                    }
654                }
655            }
656        }
[1428]657
[1755]658        // relative
659        for (int i = 0; i < 2; i++)
660        {
[2662]661            if (rel[i] < 0)
[6417]662                mouseAxes_[0 + 2*i].relVal_ = -rel[i] * totalMouseSensitivity_;
[1755]663            else
[6417]664                mouseAxes_[1 + 2*i].relVal_ =  rel[i] * totalMouseSensitivity_;
[1349]665        }
666    }
[1428]667
[1755]668    /**
[1349]669    @brief Event handler for the mouseScrolled Event.
[7401]670    @param abs The absolute position of the scroll wheel
671    @param rel The relative movement of the scroll wheel
[1755]672    */
673    void KeyBinder::mouseScrolled(int abs, int rel)
[1349]674    {
[2662]675        if (rel < 0)
676            for (int i = 0; i < -rel/mouseWheelStepSize_; i++)
[3301]677                mouseButtons_[8].execute(KeybindMode::OnPress, static_cast<float>(abs)/mouseWheelStepSize_);
[1755]678        else
[2662]679            for (int i = 0; i < rel/mouseWheelStepSize_; i++)
[3301]680                mouseButtons_[9].execute(KeybindMode::OnPress, static_cast<float>(abs)/mouseWheelStepSize_);
[1349]681    }
[1755]682
[3327]683    void KeyBinder::axisMoved(unsigned int device, unsigned int axisID, float value)
[1349]684    {
[6417]685        // Filter analog noise
686        if (this->bFilterAnalogNoise_ && std::abs(value) < this->analogThreshold_)
687            value = 0.0;
[3327]688        int i = axisID * 2;
[5695]689        JoyStickAxisVector& axis = *joyStickAxes_[device];
[2662]690        if (value < 0)
[1755]691        {
[3327]692            axis[i].absVal_ = -value;
693            axis[i].relVal_ = -value;
694            axis[i].hasChanged_ = true;
695            if (axis[i + 1].absVal_ > 0.0f)
[1755]696            {
[3327]697                axis[i + 1].absVal_ = -0.0f;
698                axis[i + 1].relVal_ = -0.0f;
699                axis[i + 1].hasChanged_ = true;
[1755]700            }
701        }
702        else
703        {
[3327]704            axis[i + 1].absVal_ = value;
705            axis[i + 1].relVal_ = value;
706            axis[i + 1].hasChanged_ = true;
707            if (axis[i].absVal_ > 0.0f)
[1755]708            {
[3327]709                axis[i].absVal_ = -0.0f;
710                axis[i].relVal_ = -0.0f;
711                axis[i].hasChanged_ = true;
[1755]712            }
713        }
[1349]714    }
[971]715}
Note: See TracBrowser for help on using the repository browser.