InputCore overhaul

This commit is contained in:
Anon 2016-07-30 09:39:02 -05:00
parent e91327c86a
commit 5e69b76f92
27 changed files with 1401 additions and 1046 deletions

View File

@ -4,6 +4,7 @@ include_directories(.)
add_subdirectory(common)
add_subdirectory(core)
add_subdirectory(video_core)
add_subdirectory(input_core)
add_subdirectory(audio_core)
add_subdirectory(tests)
if (ENABLE_SDL2)

View File

@ -16,7 +16,7 @@ create_directory_groups(${SRCS} ${HEADERS})
include_directories(${SDL2_INCLUDE_DIR})
add_executable(citra ${SRCS} ${HEADERS})
target_link_libraries(citra core video_core audio_core common)
target_link_libraries(citra core video_core audio_core input_core common)
target_link_libraries(citra ${SDL2_LIBRARY} ${OPENGL_gl_LIBRARY} inih glad)
if (MSVC)
target_link_libraries(citra getopt)

View File

@ -52,15 +52,14 @@ static const std::array<int, Settings::NativeInput::NUM_INPUTS> defaults = {
SDL_SCANCODE_I, SDL_SCANCODE_K, SDL_SCANCODE_J, SDL_SCANCODE_L,
// indirectly mapped keys
SDL_SCANCODE_UP, SDL_SCANCODE_DOWN, SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT,
SDL_SCANCODE_D,
SDL_SCANCODE_UP, SDL_SCANCODE_DOWN, SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT
};
void Config::ReadValues() {
// Controls
for (int i = 0; i < Settings::NativeInput::NUM_INPUTS; ++i) {
Settings::values.input_mappings[Settings::NativeInput::All[i]] =
sdl2_config->GetInteger("Controls", Settings::NativeInput::Mapping[i], defaults[i]);
//Settings::values.input_mappings[Settings::NativeInput::All[i]] =
// sdl2_config->GetInteger("Controls", Settings::NativeInput::Mapping[i], defaults[i]);
}
Settings::values.pad_circle_modifier_scale = (float)sdl2_config->GetReal("Controls", "pad_circle_modifier_scale", 0.5);

View File

@ -11,7 +11,6 @@
#include <glad/glad.h>
#include "common/key_map.h"
#include "common/logging/log.h"
#include "common/scm_rev.h"
#include "common/string_util.h"
@ -33,16 +32,18 @@ void EmuWindow_SDL2::OnMouseButton(u32 button, u8 state, s32 x, s32 y) {
if (state == SDL_PRESSED) {
TouchPressed((unsigned)std::max(x, 0), (unsigned)std::max(y, 0));
} else {
}
else {
TouchReleased();
}
}
void EmuWindow_SDL2::OnKeyEvent(int key, u8 state) {
if (state == SDL_PRESSED) {
KeyMap::PressKey(*this, { key, keyboard_id });
} else if (state == SDL_RELEASED) {
KeyMap::ReleaseKey(*this, { key, keyboard_id });
//KeyMap::PressKey(*this, key);
}
else if (state == SDL_RELEASED) {
//KeyMap::ReleaseKey(*this, key);
}
}
@ -59,7 +60,7 @@ void EmuWindow_SDL2::OnResize() {
}
EmuWindow_SDL2::EmuWindow_SDL2() {
keyboard_id = KeyMap::NewDeviceId();
keyboard_id = 0;
ReloadSetKeymaps();
@ -168,9 +169,9 @@ void EmuWindow_SDL2::DoneCurrent() {
}
void EmuWindow_SDL2::ReloadSetKeymaps() {
KeyMap::ClearKeyMapping(keyboard_id);
//KeyMap::ClearKeyMapping();
for (int i = 0; i < Settings::NativeInput::NUM_INPUTS; ++i) {
KeyMap::SetKeyMapping({ Settings::values.input_mappings[Settings::NativeInput::All[i]], keyboard_id }, KeyMap::mapping_targets[i]);
//KeyMap::SetKeyMapping( Settings::values.input_mappings[Settings::NativeInput::All[i]] , KeyMap::mapping_targets[i]);
}
}

View File

@ -22,8 +22,8 @@ set(SRCS
configure_debug.cpp
configure_dialog.cpp
configure_general.cpp
configure_system.cpp
configure_input.cpp
configure_system.cpp
game_list.cpp
hotkeys.cpp
main.cpp
@ -54,8 +54,8 @@ set(HEADERS
configure_debug.h
configure_dialog.h
configure_general.h
configure_system.h
configure_input.h
configure_system.h
game_list.h
game_list_p.h
hotkeys.h
@ -73,8 +73,8 @@ set(UIS
configure_audio.ui
configure_debug.ui
configure_general.ui
configure_system.ui
configure_input.ui
configure_system.ui
hotkeys.ui
main.ui
)
@ -95,7 +95,7 @@ if (APPLE)
else()
add_executable(citra-qt ${SRCS} ${HEADERS} ${UI_HDRS})
endif()
target_link_libraries(citra-qt core video_core audio_core common qhexedit)
target_link_libraries(citra-qt core video_core audio_core input_core common qhexedit)
target_link_libraries(citra-qt ${OPENGL_gl_LIBRARY} ${CITRA_QT_LIBS})
target_link_libraries(citra-qt ${PLATFORM_LIBRARIES} Threads::Threads)

View File

@ -10,7 +10,6 @@
#include "citra_qt/bootmanager.h"
#include "common/key_map.h"
#include "common/microprofile.h"
#include "common/scm_rev.h"
#include "common/string_util.h"
@ -18,6 +17,8 @@
#include "core/core.h"
#include "core/settings.h"
#include "core/system.h"
#include "input_core/input_core.h"
#include "input_core\devices\Keyboard.h"
#include "video_core/debug_utils/debug_utils.h"
#include "video_core/video_core.h"
@ -52,7 +53,8 @@ void EmuThread::run() {
was_active = running || exec_step;
if (!was_active && !stop_run)
emit DebugModeEntered();
} else if (exec_step) {
}
else if (exec_step) {
if (!was_active)
emit DebugModeLeft();
@ -62,9 +64,10 @@ void EmuThread::run() {
yieldCurrentThread();
was_active = false;
} else {
}
else {
std::unique_lock<std::mutex> lock(running_mutex);
running_cv.wait(lock, [this]{ return IsRunning() || exec_step || stop_run; });
running_cv.wait(lock, [this] { return IsRunning() || exec_step || stop_run; });
}
}
@ -80,8 +83,7 @@ void EmuThread::run() {
// This class overrides paintEvent and resizeEvent to prevent the GUI thread from stealing GL context.
// The corresponding functionality is handled in EmuThread instead
class GGLWidgetInternal : public QGLWidget
{
class GGLWidgetInternal : public QGLWidget {
public:
GGLWidgetInternal(QGLFormat fmt, GRenderWindow* parent)
: QGLWidget(fmt, parent), parent(parent) {
@ -108,16 +110,15 @@ private:
GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread) :
QWidget(parent), keyboard_id(0), emu_thread(emu_thread) {
std::string window_title = Common::StringFromFormat("Citra | %s-%s", Common::g_scm_branch, Common::g_scm_desc);
setWindowTitle(QString::fromStdString(window_title));
keyboard_id = KeyMap::NewDeviceId();
keyboard_id = 0;
ReloadSetKeymaps();
// TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground, WA_DontShowOnScreen, WA_DeleteOnClose
QGLFormat fmt;
fmt.setVersion(3,3);
fmt.setVersion(3, 3);
fmt.setProfile(QGLFormat::CoreProfile);
// Requests a forward-compatible context, which is required to get a 3.2+ context on OS X
fmt.setOption(QGL::NoDeprecatedFunctions);
@ -133,14 +134,12 @@ GRenderWindow::GRenderWindow(QWidget* parent, EmuThread* emu_thread) :
OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
OnFramebufferSizeChanged();
NotifyClientAreaSizeChanged(std::pair<unsigned,unsigned>(child->width(), child->height()));
NotifyClientAreaSizeChanged(std::pair<unsigned, unsigned>(child->width(), child->height()));
BackupGeometry();
}
void GRenderWindow::moveContext()
{
void GRenderWindow::moveContext() {
DoneCurrent();
// We need to move GL context to the swapping thread in Qt5
#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
@ -150,8 +149,7 @@ void GRenderWindow::moveContext()
#endif
}
void GRenderWindow::SwapBuffers()
{
void GRenderWindow::SwapBuffers() {
#if !defined(QT_NO_DEBUG)
// Qt debug runtime prints a bogus warning on the console if you haven't called makeCurrent
// since the last time you called swapBuffers. This presumably means something if you're using
@ -162,13 +160,11 @@ void GRenderWindow::SwapBuffers()
child->swapBuffers();
}
void GRenderWindow::MakeCurrent()
{
void GRenderWindow::MakeCurrent() {
child->makeCurrent();
}
void GRenderWindow::DoneCurrent()
{
void GRenderWindow::DoneCurrent() {
child->doneCurrent();
}
@ -180,8 +176,7 @@ void GRenderWindow::PollEvents() {
// Older versions get the window size (density independent pixels),
// and hence, do not support DPI scaling ("retina" displays).
// The result will be a viewport that is smaller than the extent of the window.
void GRenderWindow::OnFramebufferSizeChanged()
{
void GRenderWindow::OnFramebufferSizeChanged() {
// Screen changes potentially incur a change in screen DPI, hence we should update the framebuffer size
qreal pixelRatio = windowPixelRatio();
unsigned width = child->QPaintDevice::width() * pixelRatio;
@ -190,26 +185,22 @@ void GRenderWindow::OnFramebufferSizeChanged()
NotifyFramebufferLayoutChanged(EmuWindow::FramebufferLayout::DefaultScreenLayout(width, height));
}
void GRenderWindow::BackupGeometry()
{
void GRenderWindow::BackupGeometry() {
geometry = ((QGLWidget*)this)->saveGeometry();
}
void GRenderWindow::RestoreGeometry()
{
void GRenderWindow::RestoreGeometry() {
// We don't want to back up the geometry here (obviously)
QWidget::restoreGeometry(geometry);
}
void GRenderWindow::restoreGeometry(const QByteArray& geometry)
{
void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
// Make sure users of this class don't need to deal with backing up the geometry themselves
QWidget::restoreGeometry(geometry);
BackupGeometry();
}
QByteArray GRenderWindow::saveGeometry()
{
QByteArray GRenderWindow::saveGeometry() {
// If we are a top-level widget, store the current geometry
// otherwise, store the last backup
if (parent() == nullptr)
@ -218,8 +209,7 @@ QByteArray GRenderWindow::saveGeometry()
return geometry;
}
qreal GRenderWindow::windowPixelRatio()
{
qreal GRenderWindow::windowPixelRatio() {
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
// windowHandle() might not be accessible until the window is displayed to screen.
return windowHandle() ? windowHandle()->screen()->devicePixelRatio() : 1.0f;
@ -233,20 +223,20 @@ void GRenderWindow::closeEvent(QCloseEvent* event) {
QWidget::closeEvent(event);
}
void GRenderWindow::keyPressEvent(QKeyEvent* event)
{
KeyMap::PressKey(*this, { event->key(), keyboard_id });
void GRenderWindow::keyPressEvent(QKeyEvent* event) {
auto& keyboard = InputCore::main_keyboard;
KeyboardKey param = KeyboardKey(event->key(), event->nativeScanCode(), QKeySequence(event->key()).toString().toStdString());
keyboard->KeyPressed(param);
}
void GRenderWindow::keyReleaseEvent(QKeyEvent* event)
{
KeyMap::ReleaseKey(*this, { event->key(), keyboard_id });
void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
auto& keyboard = InputCore::main_keyboard;
KeyboardKey param = KeyboardKey(event->key(), event->nativeScanCode(), QKeySequence(event->key()).toString().toStdString());
keyboard->KeyReleased(param);
}
void GRenderWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
void GRenderWindow::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
auto pos = event->pos();
qreal pixelRatio = windowPixelRatio();
this->TouchPressed(static_cast<unsigned>(pos.x() * pixelRatio),
@ -254,34 +244,30 @@ void GRenderWindow::mousePressEvent(QMouseEvent *event)
}
}
void GRenderWindow::mouseMoveEvent(QMouseEvent *event)
{
void GRenderWindow::mouseMoveEvent(QMouseEvent *event) {
auto pos = event->pos();
qreal pixelRatio = windowPixelRatio();
this->TouchMoved(std::max(static_cast<unsigned>(pos.x() * pixelRatio), 0u),
std::max(static_cast<unsigned>(pos.y() * pixelRatio), 0u));
}
void GRenderWindow::mouseReleaseEvent(QMouseEvent *event)
{
void GRenderWindow::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton)
this->TouchReleased();
}
void GRenderWindow::ReloadSetKeymaps()
{
KeyMap::ClearKeyMapping(keyboard_id);
void GRenderWindow::ReloadSetKeymaps() {
//KeyMap::ClearKeyMapping();
for (int i = 0; i < Settings::NativeInput::NUM_INPUTS; ++i) {
KeyMap::SetKeyMapping({ Settings::values.input_mappings[Settings::NativeInput::All[i]], keyboard_id }, KeyMap::mapping_targets[i]);
//KeyMap::SetKeyMapping( Settings::values.input_mappings[Settings::NativeInput::All[i]], KeyMap::mapping_targets[i]);
}
}
void GRenderWindow::OnClientAreaResized(unsigned width, unsigned height)
{
void GRenderWindow::OnClientAreaResized(unsigned width, unsigned height) {
NotifyClientAreaSizeChanged(std::make_pair(width, height));
}
void GRenderWindow::OnMinimalClientAreaChangeRequest(const std::pair<unsigned,unsigned>& minimal_size) {
void GRenderWindow::OnMinimalClientAreaChangeRequest(const std::pair<unsigned, unsigned>& minimal_size) {
setMinimumSize(minimal_size.first, minimal_size.second);
}
@ -299,7 +285,7 @@ void GRenderWindow::showEvent(QShowEvent * event) {
QWidget::showEvent(event);
// windowHandle() is not initialized until the Window is shown, so we connect it here.
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
connect(this->windowHandle(), SIGNAL(screenChanged(QScreen*)), this, SLOT(OnFramebufferSizeChanged()), Qt::UniqueConnection);
#endif
#endif
}

View File

@ -2,8 +2,6 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <QSettings>
#include "citra_qt/config.h"
#include "citra_qt/ui_settings.h"
@ -27,15 +25,14 @@ const std::array<QVariant, Settings::NativeInput::NUM_INPUTS> Config::defaults =
Qt::Key_I, Qt::Key_K, Qt::Key_J, Qt::Key_L,
// indirectly mapped keys
Qt::Key_Up, Qt::Key_Down, Qt::Key_Left, Qt::Key_Right,
Qt::Key_D,
Qt::Key_Up, Qt::Key_Down, Qt::Key_Left, Qt::Key_Right
};
void Config::ReadValues() {
qt_config->beginGroup("Controls");
for (int i = 0; i < Settings::NativeInput::NUM_INPUTS; ++i) {
Settings::values.input_mappings[Settings::NativeInput::All[i]] =
qt_config->value(QString::fromStdString(Settings::NativeInput::Mapping[i]), defaults[i]).toInt();
Settings::InputDeviceMapping(qt_config->value(Settings::NativeInput::Mapping[i], defaults[i]).toString().toStdString());
}
Settings::values.pad_circle_modifier_scale = qt_config->value("pad_circle_modifier_scale", 0.5).toFloat();
qt_config->endGroup();
@ -126,7 +123,7 @@ void Config::SaveValues() {
qt_config->beginGroup("Controls");
for (int i = 0; i < Settings::NativeInput::NUM_INPUTS; ++i) {
qt_config->setValue(QString::fromStdString(Settings::NativeInput::Mapping[i]),
Settings::values.input_mappings[Settings::NativeInput::All[i]]);
QString::fromStdString(Settings::values.input_mappings[Settings::NativeInput::All[i]].Save()));
}
qt_config->setValue("pad_circle_modifier_scale", (double)Settings::values.pad_circle_modifier_scale);
qt_config->endGroup();

View File

@ -1,4 +1,4 @@
// Copyright 2016 Citra Emulator Project
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

View File

@ -6,7 +6,6 @@ set(SRCS
emu_window.cpp
file_util.cpp
hash.cpp
key_map.cpp
logging/filter.cpp
logging/text_formatter.cpp
logging/backend.cpp
@ -36,7 +35,6 @@ set(HEADERS
emu_window.h
file_util.h
hash.h
key_map.h
linear_disk_cache.h
logging/text_formatter.h
logging/filter.h

View File

@ -6,7 +6,6 @@
#include <cmath>
#include "common/assert.h"
#include "common/key_map.h"
#include "emu_window.h"
#include "video_core/video_core.h"
@ -51,11 +50,12 @@ static bool IsWithinTouchscreen(const EmuWindow::FramebufferLayout& layout, unsi
}
std::tuple<unsigned,unsigned> EmuWindow::ClipToTouchScreen(unsigned new_x, unsigned new_y) {
new_x = std::max(new_x, framebuffer_layout.bottom_screen.left);
new_x = std::min(new_x, framebuffer_layout.bottom_screen.right-1);
new_x = std::min(new_x, framebuffer_layout.bottom_screen.right - 1);
new_y = std::max(new_y, framebuffer_layout.bottom_screen.top);
new_y = std::min(new_y, framebuffer_layout.bottom_screen.bottom-1);
new_y = std::min(new_y, framebuffer_layout.bottom_screen.bottom - 1);
return std::make_tuple(new_x, new_y);
}
@ -118,7 +118,8 @@ EmuWindow::FramebufferLayout EmuWindow::FramebufferLayout::DefaultScreenLayout(u
res.bottom_screen.right = res.bottom_screen.left + bottom_width;
res.bottom_screen.top = res.top_screen.bottom;
res.bottom_screen.bottom = res.bottom_screen.top + viewport_height / 2;
} else {
}
else {
// Otherwise, apply borders to the left and right sides of the window.
int viewport_width = static_cast<int>(std::round(height / emulation_aspect_ratio));

View File

@ -1,139 +0,0 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <map>
#include "common/emu_window.h"
#include "common/key_map.h"
namespace KeyMap {
// TODO (wwylele): currently we treat c-stick as four direction buttons
// and map it directly to EmuWindow::ButtonPressed.
// It should go the analog input way like circle pad does.
const std::array<KeyTarget, Settings::NativeInput::NUM_INPUTS> mapping_targets = {{
Service::HID::PAD_A, Service::HID::PAD_B, Service::HID::PAD_X, Service::HID::PAD_Y,
Service::HID::PAD_L, Service::HID::PAD_R, Service::HID::PAD_ZL, Service::HID::PAD_ZR,
Service::HID::PAD_START, Service::HID::PAD_SELECT, Service::HID::PAD_NONE,
Service::HID::PAD_UP, Service::HID::PAD_DOWN, Service::HID::PAD_LEFT, Service::HID::PAD_RIGHT,
Service::HID::PAD_C_UP, Service::HID::PAD_C_DOWN, Service::HID::PAD_C_LEFT, Service::HID::PAD_C_RIGHT,
IndirectTarget::CirclePadUp,
IndirectTarget::CirclePadDown,
IndirectTarget::CirclePadLeft,
IndirectTarget::CirclePadRight,
IndirectTarget::CirclePadModifier,
}};
static std::map<HostDeviceKey, KeyTarget> key_map;
static int next_device_id = 0;
static bool circle_pad_up = false;
static bool circle_pad_down = false;
static bool circle_pad_left = false;
static bool circle_pad_right = false;
static bool circle_pad_modifier = false;
static void UpdateCirclePad(EmuWindow& emu_window) {
constexpr float SQRT_HALF = 0.707106781;
int x = 0, y = 0;
if (circle_pad_right)
++x;
if (circle_pad_left)
--x;
if (circle_pad_up)
++y;
if (circle_pad_down)
--y;
float modifier = circle_pad_modifier ? Settings::values.pad_circle_modifier_scale : 1.0;
emu_window.CirclePadUpdated(x * modifier * (y == 0 ? 1.0 : SQRT_HALF), y * modifier * (x == 0 ? 1.0 : SQRT_HALF));
}
int NewDeviceId() {
return next_device_id++;
}
void SetKeyMapping(HostDeviceKey key, KeyTarget target) {
key_map[key] = target;
}
void ClearKeyMapping(int device_id) {
auto iter = key_map.begin();
while (iter != key_map.end()) {
if (iter->first.device_id == device_id)
key_map.erase(iter++);
else
++iter;
}
}
void PressKey(EmuWindow& emu_window, HostDeviceKey key) {
auto target = key_map.find(key);
if (target == key_map.end())
return;
if (target->second.direct) {
emu_window.ButtonPressed({{target->second.target.direct_target_hex}});
} else {
switch (target->second.target.indirect_target) {
case IndirectTarget::CirclePadUp:
circle_pad_up = true;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadDown:
circle_pad_down = true;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadLeft:
circle_pad_left = true;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadRight:
circle_pad_right = true;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadModifier:
circle_pad_modifier = true;
UpdateCirclePad(emu_window);
break;
}
}
}
void ReleaseKey(EmuWindow& emu_window,HostDeviceKey key) {
auto target = key_map.find(key);
if (target == key_map.end())
return;
if (target->second.direct) {
emu_window.ButtonReleased({{target->second.target.direct_target_hex}});
} else {
switch (target->second.target.indirect_target) {
case IndirectTarget::CirclePadUp:
circle_pad_up = false;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadDown:
circle_pad_down = false;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadLeft:
circle_pad_left = false;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadRight:
circle_pad_right = false;
UpdateCirclePad(emu_window);
break;
case IndirectTarget::CirclePadModifier:
circle_pad_modifier = false;
UpdateCirclePad(emu_window);
break;
}
}
}
}

View File

@ -1,96 +0,0 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <array>
#include <tuple>
#include "core/hle/service/hid/hid.h"
class EmuWindow;
namespace KeyMap {
/**
* Represents key mapping targets that are not real 3DS buttons.
* They will be handled by KeyMap and translated to 3DS input.
*/
enum class IndirectTarget {
CirclePadUp,
CirclePadDown,
CirclePadLeft,
CirclePadRight,
CirclePadModifier,
};
/**
* Represents a key mapping target. It can be a PadState that represents real 3DS buttons,
* or an IndirectTarget.
*/
struct KeyTarget {
bool direct;
union {
u32 direct_target_hex;
IndirectTarget indirect_target;
} target;
KeyTarget() : direct(true) {
target.direct_target_hex = 0;
}
KeyTarget(Service::HID::PadState pad) : direct(true) {
target.direct_target_hex = pad.hex;
}
KeyTarget(IndirectTarget i) : direct(false) {
target.indirect_target = i;
}
};
/**
* Represents a key for a specific host device.
*/
struct HostDeviceKey {
int key_code;
int device_id; ///< Uniquely identifies a host device
bool operator<(const HostDeviceKey &other) const {
return std::tie(key_code, device_id) <
std::tie(other.key_code, other.device_id);
}
bool operator==(const HostDeviceKey &other) const {
return std::tie(key_code, device_id) ==
std::tie(other.key_code, other.device_id);
}
};
extern const std::array<KeyTarget, Settings::NativeInput::NUM_INPUTS> mapping_targets;
/**
* Generates a new device id, which uniquely identifies a host device within KeyMap.
*/
int NewDeviceId();
/**
* Maps a device-specific key to a target (a PadState or an IndirectTarget).
*/
void SetKeyMapping(HostDeviceKey key, KeyTarget target);
/**
* Clears all key mappings belonging to one device.
*/
void ClearKeyMapping(int device_id);
/**
* Maps a key press action and call the corresponding function in EmuWindow
*/
void PressKey(EmuWindow& emu_window, HostDeviceKey key);
/**
* Maps a key release action and call the corresponding function in EmuWindow
*/
void ReleaseKey(EmuWindow& emu_window, HostDeviceKey key);
}

View File

@ -82,6 +82,7 @@ enum class Class : ClassType {
Audio_DSP, ///< The HLE implementation of the DSP
Audio_Sink, ///< Emulator audio output backend
Loader, ///< ROM loader
Input, ///< Input backend
Count ///< Total number of logging classes
};

View File

@ -15,31 +15,31 @@
#include "core/core_timing.h"
#include "core/hle/kernel/event.h"
#include "core/hle/kernel/shared_memory.h"
#include "input_core\input_core.h"
#include "video_core/video_core.h"
namespace Service {
namespace HID {
namespace HID {
// Handle to shared memory region designated to HID_User service
static Kernel::SharedPtr<Kernel::SharedMemory> shared_mem;
// Handle to shared memory region designated to HID_User service
static Kernel::SharedPtr<Kernel::SharedMemory> shared_mem;
// Event handles
static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_1;
static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_2;
static Kernel::SharedPtr<Kernel::Event> event_accelerometer;
static Kernel::SharedPtr<Kernel::Event> event_gyroscope;
static Kernel::SharedPtr<Kernel::Event> event_debug_pad;
// Event handles
static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_1;
static Kernel::SharedPtr<Kernel::Event> event_pad_or_touch_2;
static Kernel::SharedPtr<Kernel::Event> event_accelerometer;
static Kernel::SharedPtr<Kernel::Event> event_gyroscope;
static Kernel::SharedPtr<Kernel::Event> event_debug_pad;
static u32 next_pad_index;
static u32 next_touch_index;
static u32 next_accelerometer_index;
static u32 next_gyroscope_index;
static u32 next_pad_index;
static u32 next_touch_index;
static u32 next_accelerometer_index;
static u32 next_gyroscope_index;
static int enable_accelerometer_count = 0; // positive means enabled
static int enable_gyroscope_count = 0; // positive means enabled
static int enable_accelerometer_count = 0; // positive means enabled
static int enable_gyroscope_count = 0; // positive means enabled
static PadState GetCirclePadDirectionState(s16 circle_pad_x, s16 circle_pad_y) {
static PadState GetCirclePadDirectionState(s16 circle_pad_x, s16 circle_pad_y) {
constexpr float TAN30 = 0.577350269, TAN60 = 1 / TAN30; // 30 degree and 60 degree are angular thresholds for directions
constexpr int CIRCLE_PAD_THRESHOLD_SQUARE = 40 * 40; // a circle pad radius greater than 40 will trigger circle pad direction
PadState state;
@ -64,9 +64,13 @@ static PadState GetCirclePadDirectionState(s16 circle_pad_x, s16 circle_pad_y) {
}
return state;
}
}
void Update() {
void Update() {
if (shared_mem == nullptr) {
LOG_DEBUG(Service_HID, "shared_mem is null!");
return;
}
SharedMem* mem = reinterpret_cast<SharedMem*>(shared_mem->GetPointer());
if (mem == nullptr) {
@ -74,11 +78,11 @@ void Update() {
return;
}
PadState state = VideoCore::g_emu_window->GetPadState();
PadState state = InputCore::pad_state;
// Get current circle pad position and update circle pad direction
s16 circle_pad_x, circle_pad_y;
std::tie(circle_pad_x, circle_pad_y) = VideoCore::g_emu_window->GetCirclePadState();
std::tie(circle_pad_x, circle_pad_y) = InputCore::circle_pad;
state.hex |= GetCirclePadDirectionState(circle_pad_x, circle_pad_y).hex;
mem->pad.current_state.hex = state.hex;
@ -183,9 +187,9 @@ void Update() {
event_gyroscope->Signal();
}
}
}
void GetIPCHandles(Service::Interface* self) {
void GetIPCHandles(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
cmd_buff[1] = 0; // No error
@ -197,9 +201,9 @@ void GetIPCHandles(Service::Interface* self) {
cmd_buff[6] = Kernel::g_handle_table.Create(Service::HID::event_accelerometer).MoveFrom();
cmd_buff[7] = Kernel::g_handle_table.Create(Service::HID::event_gyroscope).MoveFrom();
cmd_buff[8] = Kernel::g_handle_table.Create(Service::HID::event_debug_pad).MoveFrom();
}
}
void EnableAccelerometer(Service::Interface* self) {
void EnableAccelerometer(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
++enable_accelerometer_count;
@ -208,9 +212,9 @@ void EnableAccelerometer(Service::Interface* self) {
cmd_buff[1] = RESULT_SUCCESS.raw;
LOG_DEBUG(Service_HID, "called");
}
}
void DisableAccelerometer(Service::Interface* self) {
void DisableAccelerometer(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
--enable_accelerometer_count;
@ -219,9 +223,9 @@ void DisableAccelerometer(Service::Interface* self) {
cmd_buff[1] = RESULT_SUCCESS.raw;
LOG_DEBUG(Service_HID, "called");
}
}
void EnableGyroscopeLow(Service::Interface* self) {
void EnableGyroscopeLow(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
++enable_gyroscope_count;
@ -230,9 +234,9 @@ void EnableGyroscopeLow(Service::Interface* self) {
cmd_buff[1] = RESULT_SUCCESS.raw;
LOG_DEBUG(Service_HID, "called");
}
}
void DisableGyroscopeLow(Service::Interface* self) {
void DisableGyroscopeLow(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
--enable_gyroscope_count;
@ -241,18 +245,18 @@ void DisableGyroscopeLow(Service::Interface* self) {
cmd_buff[1] = RESULT_SUCCESS.raw;
LOG_DEBUG(Service_HID, "called");
}
}
void GetGyroscopeLowRawToDpsCoefficient(Service::Interface* self) {
void GetGyroscopeLowRawToDpsCoefficient(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
cmd_buff[1] = RESULT_SUCCESS.raw;
f32 coef = VideoCore::g_emu_window->GetGyroscopeRawToDpsCoefficient();
memcpy(&cmd_buff[2], &coef, 4);
}
}
void GetGyroscopeLowCalibrateParam(Service::Interface* self) {
void GetGyroscopeLowCalibrateParam(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
cmd_buff[1] = RESULT_SUCCESS.raw;
@ -266,9 +270,9 @@ void GetGyroscopeLowCalibrateParam(Service::Interface* self) {
memcpy(&cmd_buff[2], &param, sizeof(param));
LOG_WARNING(Service_HID, "(STUBBED) called");
}
}
void GetSoundVolume(Service::Interface* self) {
void GetSoundVolume(Service::Interface* self) {
u32* cmd_buff = Kernel::GetCommandBuffer();
const u8 volume = 0x3F; // TODO(purpasmart): Find out if this is the max value for the volume
@ -277,9 +281,9 @@ void GetSoundVolume(Service::Interface* self) {
cmd_buff[2] = volume;
LOG_WARNING(Service_HID, "(STUBBED) called");
}
}
void Init() {
void Init() {
using namespace Kernel;
AddService(new HID_U_Interface);
@ -299,17 +303,15 @@ void Init() {
event_accelerometer = Event::Create(ResetType::OneShot, "HID:EventAccelerometer");
event_gyroscope = Event::Create(ResetType::OneShot, "HID:EventGyroscope");
event_debug_pad = Event::Create(ResetType::OneShot, "HID:EventDebugPad");
}
}
void Shutdown() {
void Shutdown() {
shared_mem = nullptr;
event_pad_or_touch_1 = nullptr;
event_pad_or_touch_2 = nullptr;
event_accelerometer = nullptr;
event_gyroscope = nullptr;
event_debug_pad = nullptr;
}
} // namespace HID
}
} // namespace HID
} // namespace Service

View File

@ -32,24 +32,22 @@
#include "video_core/debug_utils/debug_utils.h"
namespace GPU {
Regs g_regs;
Regs g_regs;
/// True if the current frame was skipped
bool g_skip_frame;
/// 268MHz CPU clocks / 60Hz frames per second
const u64 frame_ticks = 268123480ull / 60;
/// Event id for CoreTiming
static int vblank_event;
/// Total number of frames drawn
static u64 frame_count;
/// True if the last frame was skipped
static bool last_skip_frame;
/// True if the current frame was skipped
bool g_skip_frame;
/// 268MHz CPU clocks / 60Hz frames per second
const u64 frame_ticks = 268123480ull / 60;
/// Event id for CoreTiming
static int vblank_event;
/// Total number of frames drawn
static u64 frame_count;
/// True if the last frame was skipped
static bool last_skip_frame;
template <typename T>
inline void Read(T &var, const u32 raw_addr) {
template <typename T>
inline void Read(T &var, const u32 raw_addr) {
u32 addr = raw_addr - HW::VADDR_GPU;
u32 index = addr / 4;
@ -60,9 +58,9 @@ inline void Read(T &var, const u32 raw_addr) {
}
var = g_regs[addr / 4];
}
}
static Math::Vec4<u8> DecodePixel(Regs::PixelFormat input_format, const u8* src_pixel) {
static Math::Vec4<u8> DecodePixel(Regs::PixelFormat input_format, const u8* src_pixel) {
switch (input_format) {
case Regs::PixelFormat::RGBA8:
return Color::DecodeRGBA8(src_pixel);
@ -81,15 +79,15 @@ static Math::Vec4<u8> DecodePixel(Regs::PixelFormat input_format, const u8* src_
default:
LOG_ERROR(HW_GPU, "Unknown source framebuffer format %x", input_format);
return {0, 0, 0, 0};
return{ 0, 0, 0, 0 };
}
}
}
MICROPROFILE_DEFINE(GPU_DisplayTransfer, "GPU", "DisplayTransfer", MP_RGB(100, 100, 255));
MICROPROFILE_DEFINE(GPU_CmdlistProcessing, "GPU", "Cmdlist Processing", MP_RGB(100, 255, 100));
MICROPROFILE_DEFINE(GPU_DisplayTransfer, "GPU", "DisplayTransfer", MP_RGB(100, 100, 255));
MICROPROFILE_DEFINE(GPU_CmdlistProcessing, "GPU", "Cmdlist Processing", MP_RGB(100, 255, 100));
template <typename T>
inline void Write(u32 addr, const T data) {
template <typename T>
inline void Write(u32 addr, const T data) {
addr -= HW::VADDR_GPU;
u32 index = addr / 4;
@ -102,7 +100,6 @@ inline void Write(u32 addr, const T data) {
g_regs[index] = static_cast<u32>(data);
switch (index) {
// Memory fills are triggered once the fill value is written.
case GPU_REG_INDEX_WORKAROUND(memory_fill_config[0].trigger, 0x00004 + 0x3):
case GPU_REG_INDEX_WORKAROUND(memory_fill_config[1].trigger, 0x00008 + 0x3):
@ -134,7 +131,8 @@ inline void Write(u32 addr, const T data) {
ptr[1] = config.value_24bit_g;
ptr[2] = config.value_24bit_b;
}
} else if (config.fill_32bit) {
}
else if (config.fill_32bit) {
// fill with 32-bit values
if (end > start) {
u32 value = config.value_32bit;
@ -142,7 +140,8 @@ inline void Write(u32 addr, const T data) {
for (size_t i = 0; i < len; ++i)
memcpy(&start[i * sizeof(u32)], &value, sizeof(u32));
}
} else {
}
else {
// fill with 16-bit values
u16 value_16bit = config.value_16bit.Value();
for (u8* ptr = start; ptr < end; ptr += sizeof(u16))
@ -154,7 +153,8 @@ inline void Write(u32 addr, const T data) {
if (!is_second_filler) {
GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PSC0);
} else {
}
else {
GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PSC1);
}
}
@ -173,7 +173,6 @@ inline void Write(u32 addr, const T data) {
const auto& config = g_regs.display_transfer_config;
if (config.trigger & 1) {
if (Pica::g_debug_context)
Pica::g_debug_context->OnEvent(Pica::DebugContext::Event::IncomingDisplayTransfer, nullptr);
@ -280,12 +279,14 @@ inline void Write(u32 addr, const T data) {
src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel;
dst_offset = VideoCore::GetMortonOffset(x, y, dst_bytes_per_pixel) + coarse_y * stride;
} else {
}
else {
// Both input and output are linear
src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel;
dst_offset = (x + y * output_width) * dst_bytes_per_pixel;
}
} else {
}
else {
if (!config.dont_swizzle) {
// Interpret the input as tiled and the output as linear
u32 coarse_y = input_y & ~7;
@ -293,7 +294,8 @@ inline void Write(u32 addr, const T data) {
src_offset = VideoCore::GetMortonOffset(input_x, input_y, src_bytes_per_pixel) + coarse_y * stride;
dst_offset = (x + y * output_width) * dst_bytes_per_pixel;
} else {
}
else {
// Both input and output are tiled
u32 out_coarse_y = y & ~7;
u32 out_stride = output_width * dst_bytes_per_pixel;
@ -311,7 +313,8 @@ inline void Write(u32 addr, const T data) {
if (config.scaling == config.ScaleX) {
Math::Vec4<u8> pixel = DecodePixel(config.input_format, src_pixel + src_bytes_per_pixel);
src_color = ((src_color + pixel) / 2).Cast<u8>();
} else if (config.scaling == config.ScaleXY) {
}
else if (config.scaling == config.ScaleXY) {
Math::Vec4<u8> pixel1 = DecodePixel(config.input_format, src_pixel + 1 * src_bytes_per_pixel);
Math::Vec4<u8> pixel2 = DecodePixel(config.input_format, src_pixel + 2 * src_bytes_per_pixel);
Math::Vec4<u8> pixel3 = DecodePixel(config.input_format, src_pixel + 3 * src_bytes_per_pixel);
@ -364,8 +367,7 @@ inline void Write(u32 addr, const T data) {
case GPU_REG_INDEX(command_processor_config.trigger):
{
const auto& config = g_regs.command_processor_config;
if (config.trigger & 1)
{
if (config.trigger & 1) {
MICROPROFILE_SCOPE(GPU_CmdlistProcessing);
u32* buffer = (u32*)Memory::GetPhysicalPointer(config.GetPhysicalAddress());
@ -391,22 +393,22 @@ inline void Write(u32 addr, const T data) {
// addr + GPU VBase - IO VBase + IO PBase
Pica::g_debug_context->recorder->RegisterWritten<T>(addr + 0x1EF00000 - 0x1EC00000 + 0x10100000, data);
}
}
}
// Explicitly instantiate template functions because we aren't defining this in the header:
// Explicitly instantiate template functions because we aren't defining this in the header:
template void Read<u64>(u64 &var, const u32 addr);
template void Read<u32>(u32 &var, const u32 addr);
template void Read<u16>(u16 &var, const u32 addr);
template void Read<u8>(u8 &var, const u32 addr);
template void Read<u64>(u64 &var, const u32 addr);
template void Read<u32>(u32 &var, const u32 addr);
template void Read<u16>(u16 &var, const u32 addr);
template void Read<u8>(u8 &var, const u32 addr);
template void Write<u64>(u32 addr, const u64 data);
template void Write<u32>(u32 addr, const u32 data);
template void Write<u16>(u32 addr, const u16 data);
template void Write<u8>(u32 addr, const u8 data);
template void Write<u64>(u32 addr, const u64 data);
template void Write<u32>(u32 addr, const u32 data);
template void Write<u16>(u32 addr, const u16 data);
template void Write<u8>(u32 addr, const u8 data);
/// Update hardware
static void VBlankCallback(u64 userdata, int cycles_late) {
/// Update hardware
static void VBlankCallback(u64 userdata, int cycles_late) {
frame_count++;
last_skip_frame = g_skip_frame;
g_skip_frame = (frame_count & Settings::values.frame_skip) != 0;
@ -430,15 +432,12 @@ static void VBlankCallback(u64 userdata, int cycles_late) {
GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PDC0);
GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PDC1);
// Check for user input updates
Service::HID::Update();
// Reschedule recurrent event
CoreTiming::ScheduleEvent(frame_ticks - cycles_late, vblank_event);
}
}
/// Initialize hardware
void Init() {
/// Initialize hardware
void Init() {
memset(&g_regs, 0, sizeof(g_regs));
auto& framebuffer_top = g_regs.framebuffer_config[0];
@ -475,11 +474,10 @@ void Init() {
CoreTiming::ScheduleEvent(frame_ticks, vblank_event);
LOG_DEBUG(HW_GPU, "initialized OK");
}
}
/// Shutdown hardware
void Shutdown() {
/// Shutdown hardware
void Shutdown() {
LOG_DEBUG(HW_GPU, "shutdown OK");
}
}
} // namespace

View File

@ -6,13 +6,12 @@
#include <string>
#include <array>
#include "common/common_types.h"
#include "common/string_util.h"
namespace Settings {
namespace NativeInput {
enum Values {
namespace NativeInput {
enum Values {
// directly mapped keys
A, B, X, Y,
L, R, ZL, ZR,
@ -22,12 +21,10 @@ enum Values {
// indirectly mapped keys
CIRCLE_UP, CIRCLE_DOWN, CIRCLE_LEFT, CIRCLE_RIGHT,
CIRCLE_MODIFIER,
NUM_INPUTS
};
static const std::array<const char*, NUM_INPUTS> Mapping = {{
};
static const std::array<const char*, NUM_INPUTS> Mapping = { {
// directly mapped keys
"pad_a", "pad_b", "pad_x", "pad_y",
"pad_l", "pad_r", "pad_zl", "pad_zr",
@ -36,27 +33,91 @@ static const std::array<const char*, NUM_INPUTS> Mapping = {{
"pad_cup", "pad_cdown", "pad_cleft", "pad_cright",
// indirectly mapped keys
"pad_circle_up", "pad_circle_down", "pad_circle_left", "pad_circle_right",
"pad_circle_modifier",
}};
static const std::array<Values, NUM_INPUTS> All = {{
"pad_circle_up", "pad_circle_down", "pad_circle_left", "pad_circle_right"
} };
static const std::array<Values, NUM_INPUTS> All = { {
A, B, X, Y,
L, R, ZL, ZR,
START, SELECT, HOME,
DUP, DDOWN, DLEFT, DRIGHT,
CUP, CDOWN, CLEFT, CRIGHT,
CIRCLE_UP, CIRCLE_DOWN, CIRCLE_LEFT, CIRCLE_RIGHT,
CIRCLE_MODIFIER,
}};
}
CIRCLE_UP, CIRCLE_DOWN, CIRCLE_LEFT, CIRCLE_RIGHT
} };
}
enum class DeviceFramework {
Qt, SDL
};
enum class Device {
Keyboard, Gamepad
};
struct InputDeviceMapping {
DeviceFramework framework;
int number;
Device device;
std::string key;
InputDeviceMapping() {
this->framework = DeviceFramework::Qt;
this->number = 0;
this->device = Device::Keyboard;
this->key = "";
}
InputDeviceMapping(std::string input) {
std::vector<std::string> parts;
Common::SplitString(input, '/', parts);
if (parts.size() == 4) {
if (parts[0] == "Qt")
this->framework = DeviceFramework::Qt;
else if (parts[0] == "SDL")
this->framework = DeviceFramework::SDL;
struct Values {
this->number = std::stoi(parts[1]);
if (parts[2] == "Keyboard")
this->device = Device::Keyboard;
else if (parts[2] == "Gamepad")
this->device = Device::Gamepad;
this->key = parts[3];
}
else {
//default if can't read properly
this->framework = DeviceFramework::Qt;
this->number = 0;
this->device = Device::Keyboard;
this->key = "";
}
}
bool operator==(const InputDeviceMapping& rhs) const {
return (this->device == rhs.device) && (this->framework == rhs.framework) && (this->number == rhs.number);
}
std::string Save() {
std::string result = "";
if (this->framework == DeviceFramework::Qt)
result = "Qt";
else if (this->framework == DeviceFramework::SDL)
result = "SDL";
result += "/";
result += std::to_string(this->number);
result += "/";
if (this->device == Device::Keyboard)
result += "Keyboard";
else if (this->device == Device::Gamepad)
result += "Gamepad";
result += "/";
result += this->key;
return result;
}
};
struct Values {
// CheckNew3DS
bool is_new_3ds;
// Controls
std::array<int, NativeInput::NUM_INPUTS> input_mappings;
std::array<InputDeviceMapping, NativeInput::NUM_INPUTS> input_mappings;
float pad_circle_modifier_scale;
// Core
@ -85,8 +146,7 @@ struct Values {
// Debugging
bool use_gdbstub;
u16 gdbstub_port;
} extern values;
void Apply();
} extern values;
void Apply();
}

View File

@ -14,6 +14,7 @@
#include "core/hle/kernel/memory.h"
#include "video_core/video_core.h"
#include "input_core/input_core.h"
namespace System {
@ -28,6 +29,7 @@ Result Init(EmuWindow* emu_window) {
return Result::ErrorInitVideoCore;
}
AudioCore::Init();
InputCore::Init();
GDBStub::Init();
return Result::Success;
@ -35,6 +37,7 @@ Result Init(EmuWindow* emu_window) {
void Shutdown() {
GDBStub::Shutdown();
InputCore::Shutdown();
AudioCore::Shutdown();
VideoCore::Shutdown();
HLE::Shutdown();

View File

@ -0,0 +1,28 @@
set(SRCS
input_core.cpp
devices/Keyboard.cpp
devices/SDLGamepad.cpp
key_map.cpp
)
set(HEADERS
input_core.h
key_map.h
devices/IDevice.h
devices/Keyboard.h
devices/SDLGamepad.h
)
if(SDL2_FOUND)
include_directories(${SDL2_INCLUDE_DIR})
endif()
create_directory_groups(${SRCS} ${HEADERS})
add_library(input_core STATIC ${SRCS} ${HEADERS})
if(SDL2_FOUND)
target_link_libraries(input_core ${SDL2_LIBRARY})
set_property(TARGET input_core APPEND PROPERTY COMPILE_DEFINITIONS HAVE_SDL2)
endif()

View File

@ -0,0 +1,18 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <map>
#include "core/settings.h"
#include "input_core\key_map.h"
class IDevice {
public:
std::map<std::string, std::vector<KeyMap::KeyTarget>> keyMapping; /// Maps the string in the settings file to the HID Padstate object
virtual bool InitDevice(int number, std::map<std::string, std::vector<KeyMap::KeyTarget>> keyMap) = 0;
virtual void ProcessInput() = 0;
virtual bool CloseDevice() = 0;
};

View File

@ -0,0 +1,55 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "Keyboard.h"
#include <SDL_keyboard.h>
Keyboard::Keyboard() {
}
Keyboard::~Keyboard() {
}
bool Keyboard::InitDevice(int number, std::map<std::string, std::vector<KeyMap::KeyTarget>> keyMap) {
keyMapping = keyMap;
return true;
}
void Keyboard::ProcessInput() {
m.lock();
auto keysPressedCopy = keysPressed;
m.unlock();
for (auto const &ent1 : keyMapping) {
int scancode = std::stoul(ent1.first, nullptr, 16);
KeyboardKey proxy = KeyboardKey(0, scancode, "");
if (keysPressedCopy[proxy] == true && keysPressedLast[scancode] == false) {
for (auto& key : ent1.second) {
KeyMap::PressKey(key, 1.0);
}
keysPressedLast[scancode] = true;
}
else if (keysPressedCopy[proxy] == false && keysPressedLast[scancode] == true) {
for (auto& key : ent1.second) {
KeyMap::ReleaseKey(key);
}
keysPressedLast[scancode] = false;
}
}
}
bool Keyboard::CloseDevice() {
return true;
}
void Keyboard::KeyPressed(KeyboardKey key) {
m.lock();
keysPressed[key] = true;
m.unlock();
}
void Keyboard::KeyReleased(KeyboardKey key) {
m.lock();
keysPressed[key] = false;
m.unlock();
}

View File

@ -0,0 +1,48 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include "IDevice.h"
struct KeyboardKey;
class Keyboard : public IDevice {
private:
std::map<KeyboardKey, bool> keysPressed;
std::map<int, bool> keysPressedLast;
std::mutex m; /// Keys pressed from frontend is on a separate thread.
public:
Keyboard();
~Keyboard();
bool InitDevice(int number, std::map<std::string, std::vector<KeyMap::KeyTarget>> keyMap) override;
void ProcessInput() override;
bool CloseDevice() override;
void KeyPressed(KeyboardKey key);
void KeyReleased(KeyboardKey key);
};
struct KeyboardKey {
uint32_t key;
uint32_t scancode;
std::string character;
KeyboardKey(uint32_t Key, uint32_t Scancode, std::string Character) {
key = Key;
scancode = Scancode;
character = Character;
}
bool operator==(KeyboardKey& other) {
return (this->scancode == other.scancode);
}
bool operator==(uint32_t other) {
return (this->scancode == other);
}
bool operator<(const KeyboardKey &o) const {
return (this->scancode < o.scancode);
}
};

View File

@ -0,0 +1,86 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <memory>
#include <cmath>
#include "SDLGamepad.h"
#include <SDL.h>
#include "common/assert.h"
#include "common/logging/log.h"
bool SDLGamepad::SDLInitialized = false;
SDLGamepad::SDLGamepad() {
}
SDLGamepad::~SDLGamepad() {
CloseDevice();
}
bool SDLGamepad::InitDevice(int number, std::map<std::string, std::vector<KeyMap::KeyTarget>> keyMap) {
if (!SDLGamepad::SDLInitialized && SDL_Init(SDL_INIT_GAMECONTROLLER) < 0) {
LOG_CRITICAL(Input, "SDL_Init(SDL_INIT_GAMECONTROLLER) failed");
return false;
}
SDL_GameControllerEventState(SDL_IGNORE);
SDLGamepad::SDLInitialized = true;
if (SDL_IsGameController(number)) {
gamepad = SDL_GameControllerOpen(number);
if (gamepad == nullptr) {
LOG_ERROR(Input, "Controller found but unable to open connection.");
return false;
}
}
keyMapping = keyMap;
for (auto& entry : keyMapping) {
keysPressed[entry.first] = false;
}
return true;
}
void SDLGamepad::ProcessInput() {
if (gamepad == nullptr)
return;
SDL_GameControllerUpdate();
for (auto const &ent1 : keyMapping) {
SDL_GameControllerButton button = SDL_GameControllerGetButtonFromString(friendlyNameMapping[ent1.first].c_str());
if (button != SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_INVALID) {
Uint8 pressed = SDL_GameControllerGetButton(gamepad, button);
if (pressed == 1 && keysPressed[ent1.first] == false) {
for (auto& padstate : ent1.second) {
KeyMap::PressKey(padstate, 1.0);
keysPressed[ent1.first] = true;
}
}
else if (pressed == 0 && keysPressed[ent1.first] == true) {
for (auto& padstate : ent1.second) {
KeyMap::ReleaseKey(padstate);
keysPressed[ent1.first] = false;
}
}
}
else {
//Try axis if button isn't valid
SDL_GameControllerAxis axis = SDL_GameControllerGetAxisFromString(friendlyNameMapping[ent1.first].c_str());
if (axis != SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_INVALID) {
Sint16 value = SDL_GameControllerGetAxis(gamepad, axis);
for (auto& padstate : ent1.second) {
if (abs(value) < 0.2 * 32767.0) // dont process if in deadzone. Replace later with settings for deadzone.
KeyMap::ReleaseKey(padstate);
else
KeyMap::PressKey(padstate, (float)value / 32767.0);
}
}
}
}
}
bool SDLGamepad::CloseDevice() {
if (gamepad != nullptr) {
SDL_GameControllerClose(gamepad);
}
return true;
}

View File

@ -0,0 +1,48 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <SDL_gamecontroller.h>
#include "IDevice.h"
class SDLGamepad : public IDevice {
private:
std::map<std::string, std::string> friendlyNameMapping = { /// Maps the friendly name shown on GUI with the string name for getting the SDL button instance.
{ "Button A","a" },
{ "Button B","b" },
{ "Button X","x" },
{ "Button Y","y" },
{ "Left Shoulder","leftshoulder" },
{ "Right Shoulder","rightshoulder" },
{ "Start","start" },
{ "Back","back" },
{ "D-pad Up","dpup" },
{ "D-pad Down","dpdown" },
{ "D-pad Left","dpleft" },
{ "D-pad Right","dpright" },
{ "L3","leftstick" },
{ "R3","rightstick" },
{ "Left Trigger","lefttrigger" },
{ "Right Trigger","righttrigger" },
{ "Left Y+","lefty" },
{ "Left Y-","lefty" },
{ "Left X+","leftx" },
{ "Left X-","leftx" },
{ "Right Y+","righty" },
{ "Right Y-","righty" },
{ "Right X+","rightx" },
{ "Right X-","rightx" },
};
static bool SDLInitialized;
std::map<std::string, bool> keysPressed;
SDL_GameController* gamepad;
public:
SDLGamepad();
~SDLGamepad();
virtual bool InitDevice(int number, std::map<std::string, std::vector<KeyMap::KeyTarget>> keyMap) override;
virtual void ProcessInput() override;
bool CloseDevice() override;
};

View File

@ -0,0 +1,108 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <map>
#include "core/core_timing.h"
#include "input_core/input_core.h"
#include "input_core/devices/Keyboard.h"
#include "input_core/devices/SDLGamepad.h"
namespace InputCore {
using std::vector;
using std::shared_ptr;
using std::string;
constexpr u64 frame_ticks = 268123480ull / 60;
static int tick_event;
Service::HID::PadState pad_state;
std::tuple<s16, s16> circle_pad = { 0,0 };
shared_ptr<Keyboard> main_keyboard; /// Instance of main keyboard device. Always initialized regardless of settings.
vector<shared_ptr<IDevice>> devices; ///Devices that are handling input for the game
static void InputTickCallback(u64, int cycles_late) {
for (auto& device : devices)
device->ProcessInput();
Service::HID::Update();
// Reschedule recurrent event
CoreTiming::ScheduleEvent(frame_ticks - cycles_late, tick_event);
}
void InputCore::Init() {
devices = ParseSettings();
tick_event = CoreTiming::RegisterEvent("InputCore::tick_event", InputTickCallback);
CoreTiming::ScheduleEvent(frame_ticks, tick_event);
}
void InputCore::Shutdown() {
devices.clear();
}
///Parse the settings to initialize necessary devices to handle input
vector<shared_ptr<IDevice>> InputCore::ParseSettings() {
vector<shared_ptr<IDevice>> devices;
vector<Settings::InputDeviceMapping> uniqueMappings; //unique mappings from settings file, used to init devices.
//Get Unique input mappings from settings
for (auto& mapping : Settings::values.input_mappings) {
if (!CheckIfMappingExists(uniqueMappings, mapping)) {
uniqueMappings.push_back(mapping);
}
}
//Generate a device for each unique mapping
shared_ptr<IDevice> input;
for (auto& mapping : uniqueMappings) {
switch (mapping.framework) {
case Settings::DeviceFramework::Qt:
{
main_keyboard = std::make_shared<Keyboard>();
input = main_keyboard;
break;
}
case Settings::DeviceFramework::SDL:
{
if (mapping.device == Settings::Device::Keyboard) {
main_keyboard = std::make_shared<Keyboard>();
input = main_keyboard;
break;
}
else if (mapping.device == Settings::Device::Gamepad) {
input = std::make_shared<SDLGamepad>();
break;
}
}
}
devices.push_back(input);
//Build list of inputs to listen for, for this device
std::map<std::string, vector<KeyMap::KeyTarget>> keyMapping;
for (int i = 0; i < Settings::values.input_mappings.size(); i++) {
KeyMap::KeyTarget val = KeyMap::mapping_targets[i];
std::string key = Settings::values.input_mappings[i].key;
if (Settings::values.input_mappings[i] == mapping) {
keyMapping[key].push_back(val);
}
}
input->InitDevice(mapping.number, keyMapping);
}
if (main_keyboard == nullptr)
main_keyboard = std::make_shared<Keyboard>();
return devices;
}
///Helper method to check if device has already been initialized from the mapping.
bool InputCore::CheckIfMappingExists(vector<Settings::InputDeviceMapping> uniqueMapping, Settings::InputDeviceMapping mappingToCheck) {
for (auto& mapping : uniqueMapping) {
if (mapping == mappingToCheck)
return true;
}
return false;
}
}

View File

@ -0,0 +1,26 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <memory>
#include <tuple>
#include "core/hle/service/hid/hid.h"
#include "core/settings.h"
#include "input_core\devices\IDevice.h"
class Keyboard;
namespace InputCore {
extern Service::HID::PadState pad_state;
extern std::tuple<s16, s16> circle_pad;
extern std::shared_ptr<Keyboard> main_keyboard;
void Init();
void Shutdown();
std::vector<std::shared_ptr<IDevice>> ParseSettings();
bool CheckIfMappingExists(std::vector<Settings::InputDeviceMapping> uniqueMapping, Settings::InputDeviceMapping mappingToCheck);
} // namespace

View File

@ -0,0 +1,63 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <map>
#include <algorithm>
#include <iterator>
#include "common/emu_window.h"
#include "input_core/key_map.h"
#include "input_core/input_core.h"
namespace KeyMap {
constexpr int MAX_CIRCLEPAD_POS = 0x9C; /// Max value for a circle pad position
const std::array<KeyTarget, Settings::NativeInput::NUM_INPUTS> mapping_targets = { {
Service::HID::PAD_A, Service::HID::PAD_B, Service::HID::PAD_X, Service::HID::PAD_Y,
Service::HID::PAD_L, Service::HID::PAD_R, Service::HID::PAD_ZL, Service::HID::PAD_ZR,
Service::HID::PAD_START, Service::HID::PAD_SELECT, Service::HID::PAD_TOUCH,
Service::HID::PAD_UP, Service::HID::PAD_DOWN, Service::HID::PAD_LEFT, Service::HID::PAD_RIGHT,
Service::HID::PAD_C_UP, Service::HID::PAD_C_DOWN, Service::HID::PAD_C_LEFT, Service::HID::PAD_C_RIGHT,
Service::HID::PAD_CIRCLE_UP,
Service::HID::PAD_CIRCLE_DOWN,
Service::HID::PAD_CIRCLE_LEFT,
Service::HID::PAD_CIRCLE_RIGHT,
} };
///Array of inputs that are analog only, and require a strength when set
const std::array<KeyTarget, 4> analog_inputs = {
Service::HID::PAD_CIRCLE_UP,
Service::HID::PAD_CIRCLE_DOWN,
Service::HID::PAD_CIRCLE_LEFT,
Service::HID::PAD_CIRCLE_RIGHT
};
void PressKey(KeyTarget target, const float strength) {
if (std::find(std::begin(analog_inputs), std::end(analog_inputs), target) == std::end(analog_inputs)) { // If is digital keytarget
InputCore::pad_state.hex |= target.target.direct_target_hex;
}
else { // it is analog input
if (target == Service::HID::PAD_CIRCLE_UP || target == Service::HID::PAD_CIRCLE_DOWN) {
std::get<1>(InputCore::circle_pad) = MAX_CIRCLEPAD_POS * strength * -1;
}
else if (target == Service::HID::PAD_CIRCLE_LEFT || target == Service::HID::PAD_CIRCLE_RIGHT) {
std::get<0>(InputCore::circle_pad) = MAX_CIRCLEPAD_POS * strength;
}
}
}
void ReleaseKey(KeyTarget target) {
if (std::find(std::begin(analog_inputs), std::end(analog_inputs), target) == std::end(analog_inputs)) { // If is digital keytarget
InputCore::pad_state.hex &= ~target.target.direct_target_hex;
}
else { // it is analog input
if (target == Service::HID::PAD_CIRCLE_UP || target == Service::HID::PAD_CIRCLE_DOWN) {
std::get<1>(InputCore::circle_pad) = 0;
}
else if (target == Service::HID::PAD_CIRCLE_LEFT || target == Service::HID::PAD_CIRCLE_RIGHT) {
std::get<0>(InputCore::circle_pad) = 0;
}
}
}
}

63
src/input_core/key_map.h Normal file
View File

@ -0,0 +1,63 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <array>
#include <tuple>
#include "core/hle/service/hid/hid.h"
class EmuWindow;
namespace KeyMap {
/**
* Represents key mapping targets that are not real 3DS buttons.
* They will be handled by KeyMap and translated to 3DS input.
*/
enum class IndirectTarget {
CirclePadUp,
CirclePadDown,
CirclePadLeft,
CirclePadRight,
CirclePadModifier
};
/**
* Represents a key mapping target. It can be a PadState that represents real 3DS buttons,
* or an IndirectTarget.
*/
struct KeyTarget {
bool direct;
union {
u32 direct_target_hex;
IndirectTarget indirect_target;
} target;
KeyTarget() : direct(true) {
target.direct_target_hex = 0;
}
KeyTarget(Service::HID::PadState pad) : direct(true) {
target.direct_target_hex = pad.hex;
}
KeyTarget(IndirectTarget i) : direct(false) {
target.indirect_target = i;
}
const bool operator==(const Service::HID::PadState &other) const {
return this->target.direct_target_hex == other.hex;
}
const bool operator==(const KeyTarget &other) const {
return this->target.direct_target_hex == other.target.direct_target_hex;
}
};
extern const std::array<KeyTarget, Settings::NativeInput::NUM_INPUTS> mapping_targets;
///Handles the pressing of a key and modifies InputCore state
void PressKey(KeyTarget target, float strength);
///Handles the releasing of a key and modifies InputCore state
void ReleaseKey(KeyTarget target);
}