1
0
Fork 0

Compare commits

...

10 Commits

Author SHA1 Message Date
Michał Janiszewski 96eeb784c5
Merge 7b0028db03 into 1d38cbafcb 2025-07-13 23:12:27 +00:00
Peter Nelson 1d38cbafcb Codechange: Use unique_ptr for ScriptInfo instances.
Replaces raw pointers, slightly.
2025-07-14 00:10:14 +01:00
Peter Nelson 992d58d799 Codechange: Pass ScriptInfo by reference to IsSameScript. 2025-07-14 00:10:14 +01:00
Peter Nelson 8f34b7a821 Codechange: Keep Squirrel engine in unique_ptr. 2025-07-14 00:10:14 +01:00
Peter Nelson bf6d0c4934
Codechange: Don't pre-fill font metrics when loading fonts. (#14436)
Each font cache implementation sets its own metrics based on the loaded font, so there is no need to pre-fill with (unscaled, invalid) default metrics.
2025-07-13 23:38:31 +01:00
Michael Lutz 3c4fb21a5e
Fix: [Win32] Link failure with newer Windows SDK version due to WinRT changes. (#14432) 2025-07-13 22:34:32 +01:00
Michał Janiszewski 7b0028db03 Change: Limit gamepad scroll only to windows that don't follow vehicles 2025-06-29 11:09:52 +02:00
Michał Janiszewski 54767e0349 Add: Select viewport under the cursor for gamepad scrolling 2025-06-29 11:09:52 +02:00
Michał Janiszewski 1fc2481340 Feature: Win32 driver support for gamepad scrolling 2025-06-29 11:09:52 +02:00
Michał Janiszewski ebd2b45753 Feature: Add gamepad scrolling support (SDL2) 2025-06-29 11:09:52 +02:00
19 changed files with 511 additions and 53 deletions

View File

@ -449,6 +449,7 @@ if(WIN32)
psapi
winhttp
bcrypt
xinput
)
endif()

View File

@ -90,7 +90,7 @@ template <> SQInteger PushClassName<AIInfo, ScriptType::AI>(HSQUIRRELVM vm) { sq
/* Remove the link to the real instance, else it might get deleted by RegisterAI() */
sq_setinstanceup(vm, 2, nullptr);
/* Register the AI to the base system */
info->GetScanner()->RegisterScript(info);
info->GetScanner()->RegisterScript(std::unique_ptr<AIInfo>{info});
return 0;
}
@ -136,22 +136,21 @@ bool AIInfo::CanLoadFromVersion(int version) const
/* static */ SQInteger AILibrary::Constructor(HSQUIRRELVM vm)
{
/* Create a new library */
AILibrary *library = new AILibrary();
auto library = std::make_unique<AILibrary>();
SQInteger res = ScriptInfo::Constructor(vm, *library);
if (res != 0) {
delete library;
return res;
}
/* Cache the category */
if (!library->CheckMethod("GetCategory") || !library->engine->CallStringMethod(library->SQ_instance, "GetCategory", &library->category, MAX_GET_OPS)) {
delete library;
return SQ_ERROR;
}
/* Register the Library to the base system */
library->GetScanner()->RegisterScript(library);
ScriptScanner *scanner = library->GetScanner();
scanner->RegisterScript(std::move(library));
return 0;
}

View File

@ -29,7 +29,7 @@ void AIScannerInfo::Initialize()
{
ScriptScanner::Initialize("AIScanner");
ScriptAllocatorScope alloc_scope(this->engine);
ScriptAllocatorScope alloc_scope(this->engine.get());
/* Create the dummy AI */
this->main_script = "%_dummy";

View File

@ -22,9 +22,10 @@
#include "safeguards.h"
/** Default heights for the different sizes of fonts. */
static const int _default_font_height[FS_END] = {10, 6, 18, 10};
static const int _default_font_ascender[FS_END] = { 8, 5, 15, 8};
/** Default unscaled heights for the different sizes of fonts. */
/* static */ const int FontCache::DEFAULT_FONT_HEIGHT[FS_END] = {10, 6, 18, 10};
/** Default unscaled ascenders for the different sizes of fonts. */
/* static */ const int FontCache::DEFAULT_FONT_ASCENDER[FS_END] = {8, 5, 15, 8};
FontCacheSettings _fcsettings;
@ -32,8 +33,7 @@ FontCacheSettings _fcsettings;
* Create a new font cache.
* @param fs The size of the font.
*/
FontCache::FontCache(FontSize fs) : parent(FontCache::Get(fs)), fs(fs), height(_default_font_height[fs]),
ascender(_default_font_ascender[fs]), descender(_default_font_ascender[fs] - _default_font_height[fs])
FontCache::FontCache(FontSize fs) : parent(FontCache::Get(fs)), fs(fs)
{
assert(this->parent == nullptr || this->fs == this->parent->fs);
FontCache::caches[this->fs] = this;
@ -50,7 +50,7 @@ FontCache::~FontCache()
int FontCache::GetDefaultFontHeight(FontSize fs)
{
return _default_font_height[fs];
return FontCache::DEFAULT_FONT_HEIGHT[fs];
}
/**

View File

@ -23,9 +23,9 @@ protected:
static FontCache *caches[FS_END]; ///< All the font caches.
FontCache *parent; ///< The parent of this font cache.
const FontSize fs; ///< The size of the font.
int height; ///< The height of the font.
int ascender; ///< The ascender value of the font.
int descender; ///< The descender value of the font.
int height = 0; ///< The height of the font.
int ascender = 0; ///< The ascender value of the font.
int descender = 0; ///< The descender value of the font.
public:
FontCache(FontSize fs);
@ -33,6 +33,11 @@ public:
static void InitializeFontCaches();
/** Default unscaled font heights. */
static const int DEFAULT_FONT_HEIGHT[FS_END];
/** Default unscaled font ascenders. */
static const int DEFAULT_FONT_ASCENDER[FS_END];
static int GetDefaultFontHeight(FontSize fs);
/**

View File

@ -78,7 +78,7 @@ template <> SQInteger PushClassName<GameInfo, ScriptType::GS>(HSQUIRRELVM vm) {
/* Remove the link to the real instance, else it might get deleted by RegisterGame() */
sq_setinstanceup(vm, 2, nullptr);
/* Register the Game to the base system */
info->GetScanner()->RegisterScript(info);
info->GetScanner()->RegisterScript(std::unique_ptr<GameInfo>{info});
return 0;
}
@ -106,22 +106,21 @@ bool GameInfo::CanLoadFromVersion(int version) const
/* static */ SQInteger GameLibrary::Constructor(HSQUIRRELVM vm)
{
/* Create a new library */
GameLibrary *library = new GameLibrary();
auto library = std::make_unique<GameLibrary>();
SQInteger res = ScriptInfo::Constructor(vm, *library);
if (res != 0) {
delete library;
return res;
}
/* Cache the category */
if (!library->CheckMethod("GetCategory") || !library->engine->CallStringMethod(library->SQ_instance, "GetCategory", &library->category, MAX_GET_OPS)) {
delete library;
return SQ_ERROR;
}
/* Register the Library to the base system */
library->GetScanner()->RegisterScript(library);
ScriptScanner *scanner = library->GetScanner();
scanner->RegisterScript(std::move(library));
return 0;
}

View File

@ -92,8 +92,8 @@ GameLibrary *GameScannerLibrary::FindLibrary(const std::string &library, int ver
std::string library_name = fmt::format("{}.{}", library, version);
/* Check if the library + version exists */
ScriptInfoList::iterator it = this->info_list.find(library_name);
auto it = this->info_list.find(library_name);
if (it == this->info_list.end()) return nullptr;
return static_cast<GameLibrary *>((*it).second);
return static_cast<GameLibrary *>(it->second);
}

View File

@ -75,6 +75,7 @@ void HandleTextInput(std::string_view str, bool marked = false,
std::optional<size_t> insert_location = std::nullopt, std::optional<size_t> replacement_end = std::nullopt);
void HandleCtrlChanged();
void HandleMouseEvents();
void HandleGamepadScrolling(int stick_x, int stick_y, int max_axis_value);
void UpdateWindows();
void ChangeGameSpeed(bool enable_fast_forward);

View File

@ -1698,6 +1698,25 @@ STR_CONFIG_SETTING_SCROLLWHEEL_ZOOM :Zoom map
STR_CONFIG_SETTING_SCROLLWHEEL_SCROLL :Scroll map
STR_CONFIG_SETTING_SCROLLWHEEL_OFF :Off
STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION :Gamepad stick for scrolling: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION_HELPTEXT :Select which analog stick to use for map scrolling
###length 3
STR_CONFIG_SETTING_GAMEPAD_STICK_DISABLED :Disabled
STR_CONFIG_SETTING_GAMEPAD_STICK_LEFT :Left stick
STR_CONFIG_SETTING_GAMEPAD_STICK_RIGHT :Right stick
STR_CONFIG_SETTING_GAMEPAD_DEADZONE :Gamepad deadzone: {STRING2}%
STR_CONFIG_SETTING_GAMEPAD_DEADZONE_HELPTEXT :Minimum stick movement required before scrolling starts (0-100%)
STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY :Gamepad sensitivity: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY_HELPTEXT :Control the sensitivity of gamepad analog stick scrolling
STR_CONFIG_SETTING_GAMEPAD_INVERT_X :Invert gamepad X-axis: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_INVERT_X_HELPTEXT :Invert the horizontal axis movement of the gamepad analog stick
STR_CONFIG_SETTING_GAMEPAD_INVERT_Y :Invert gamepad Y-axis: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_INVERT_Y_HELPTEXT :Invert the vertical axis movement of the gamepad analog stick
STR_CONFIG_SETTING_OSK_ACTIVATION :On screen keyboard: {STRING2}
STR_CONFIG_SETTING_OSK_ACTIVATION_HELPTEXT :Select the method to open the on screen keyboard for entering text into editboxes only using the pointing device. This is meant for small devices without actual keyboard
###length 4

View File

@ -44,10 +44,7 @@ bool ScriptScanner::AddFile(const std::string &filename, size_t, const std::stri
return true;
}
ScriptScanner::ScriptScanner() :
engine(nullptr)
{
}
ScriptScanner::ScriptScanner() = default;
void ScriptScanner::ResetEngine()
{
@ -58,7 +55,7 @@ void ScriptScanner::ResetEngine()
void ScriptScanner::Initialize(std::string_view name)
{
this->engine = new Squirrel(name);
this->engine = std::make_unique<Squirrel>(name);
this->RescanDir();
@ -68,8 +65,6 @@ void ScriptScanner::Initialize(std::string_view name)
ScriptScanner::~ScriptScanner()
{
this->Reset();
delete this->engine;
}
void ScriptScanner::RescanDir()
@ -83,15 +78,12 @@ void ScriptScanner::RescanDir()
void ScriptScanner::Reset()
{
for (const auto &item : this->info_list) {
delete item.second;
}
this->info_list.clear();
this->info_single_list.clear();
this->info_vector.clear();
}
void ScriptScanner::RegisterScript(ScriptInfo *info)
void ScriptScanner::RegisterScript(std::unique_ptr<ScriptInfo> &&info)
{
std::string script_original_name = this->GetScriptName(*info);
std::string script_name = fmt::format("{}.{}", script_original_name, info->GetVersion());
@ -99,7 +91,6 @@ void ScriptScanner::RegisterScript(ScriptInfo *info)
/* Check if GetShortName follows the rules */
if (info->GetShortName().size() != 4) {
Debug(script, 0, "The script '{}' returned a string from GetShortName() which is not four characters. Unable to load the script.", info->GetName());
delete info;
return;
}
@ -111,7 +102,6 @@ void ScriptScanner::RegisterScript(ScriptInfo *info)
#else
if (it->second->GetMainScript() == info->GetMainScript()) {
#endif
delete info;
return;
}
@ -120,20 +110,20 @@ void ScriptScanner::RegisterScript(ScriptInfo *info)
Debug(script, 1, " 2: {}", info->GetMainScript());
Debug(script, 1, "The first is taking precedence.");
delete info;
return;
}
this->info_list[script_name] = info;
ScriptInfo *script_info = this->info_vector.emplace_back(std::move(info)).get();
this->info_list[script_name] = script_info;
if (!info->IsDeveloperOnly() || _settings_client.gui.ai_developer_tools) {
if (!script_info->IsDeveloperOnly() || _settings_client.gui.ai_developer_tools) {
/* Add the script to the 'unique' script list, where only the highest version
* of the script is registered. */
auto it = this->info_single_list.find(script_original_name);
if (it == this->info_single_list.end()) {
this->info_single_list[script_original_name] = info;
} else if (it->second->GetVersion() < info->GetVersion()) {
it->second = info;
this->info_single_list[script_original_name] = script_info;
} else if (it->second->GetVersion() < script_info->GetVersion()) {
it->second = script_info;
}
}
}
@ -195,17 +185,17 @@ struct ScriptFileChecksumCreator : FileScanner {
* @param info The script to get the shortname and md5 sum from.
* @return True iff they're the same.
*/
static bool IsSameScript(const ContentInfo &ci, bool md5sum, ScriptInfo *info, Subdirectory dir)
static bool IsSameScript(const ContentInfo &ci, bool md5sum, const ScriptInfo &info, Subdirectory dir)
{
uint32_t id = 0;
auto str = std::string_view{info->GetShortName()}.substr(0, 4);
auto str = std::string_view{info.GetShortName()}.substr(0, 4);
for (size_t j = 0; j < str.size(); j++) id |= static_cast<uint8_t>(str[j]) << (8 * j);
if (id != ci.unique_id) return false;
if (!md5sum) return true;
ScriptFileChecksumCreator checksum(dir);
const auto &tar_filename = info->GetTarFile();
const auto &tar_filename = info.GetTarFile();
TarList::iterator iter;
if (!tar_filename.empty() && (iter = _tar_list[dir].find(tar_filename)) != _tar_list[dir].end()) {
/* The main script is in a tar file, so find all files that
@ -224,7 +214,7 @@ static bool IsSameScript(const ContentInfo &ci, bool md5sum, ScriptInfo *info, S
/* There'll always be at least 1 path separator character in a script
* main script name as the search algorithm requires the main script to
* be in a subdirectory of the script directory; so <dir>/<path>/main.nut. */
const std::string &main_script = info->GetMainScript();
const std::string &main_script = info.GetMainScript();
std::string path = main_script.substr(0, main_script.find_last_of(PATHSEPCHAR));
checksum.Scan(".nut", path);
}
@ -235,7 +225,7 @@ static bool IsSameScript(const ContentInfo &ci, bool md5sum, ScriptInfo *info, S
bool ScriptScanner::HasScript(const ContentInfo &ci, bool md5sum)
{
for (const auto &item : this->info_list) {
if (IsSameScript(ci, md5sum, item.second, this->GetDirectory())) return true;
if (IsSameScript(ci, md5sum, *item.second, this->GetDirectory())) return true;
}
return false;
}
@ -243,7 +233,7 @@ bool ScriptScanner::HasScript(const ContentInfo &ci, bool md5sum)
std::optional<std::string_view> ScriptScanner::FindMainScript(const ContentInfo &ci, bool md5sum)
{
for (const auto &item : this->info_list) {
if (IsSameScript(ci, md5sum, item.second, this->GetDirectory())) return item.second->GetMainScript();
if (IsSameScript(ci, md5sum, *item.second, this->GetDirectory())) return item.second->GetMainScript();
}
return std::nullopt;
}

View File

@ -13,7 +13,7 @@
#include "../fileio_func.h"
#include "../string_func.h"
typedef std::map<std::string, class ScriptInfo *, CaseInsensitiveComparator> ScriptInfoList; ///< Type for the list of scripts.
using ScriptInfoList = std::map<std::string, class ScriptInfo *, CaseInsensitiveComparator>; ///< Type for the list of scripts.
/** Scanner to help finding scripts. */
class ScriptScanner : public FileScanner {
@ -26,7 +26,7 @@ public:
/**
* Get the engine of the main squirrel handler (it indexes all available scripts).
*/
class Squirrel *GetEngine() { return this->engine; }
class Squirrel *GetEngine() { return this->engine.get(); }
/**
* Get the current main script the ScanDir is currently tracking.
@ -51,7 +51,7 @@ public:
/**
* Register a ScriptInfo to the scanner.
*/
void RegisterScript(class ScriptInfo *info);
void RegisterScript(std::unique_ptr<class ScriptInfo> &&info);
/**
* Get the list of registered scripts to print on the console.
@ -84,11 +84,13 @@ public:
void RescanDir();
protected:
class Squirrel *engine; ///< The engine we're scanning with.
std::unique_ptr<class Squirrel> engine; ///< The engine we're scanning with.
std::string main_script; ///< The full path of the script.
std::string tar_file; ///< If, which tar file the script was in.
ScriptInfoList info_list; ///< The list of all script.
std::vector<std::unique_ptr<ScriptInfo>> info_vector;
ScriptInfoList info_list; ///< The list of all script.
ScriptInfoList info_single_list; ///< The list of all unique script. The best script (highest version) is shown.
/**

View File

@ -681,6 +681,11 @@ SettingsContainer &GetSettingsTree()
* Since it's also able to completely disable the scrollwheel will we display it on all platforms anyway */
viewports->Add(new SettingEntry("gui.scrollwheel_scrolling"));
viewports->Add(new SettingEntry("gui.scrollwheel_multiplier"));
viewports->Add(new SettingEntry("gui.gamepad_stick_selection"));
viewports->Add(new SettingEntry("gui.gamepad_deadzone"));
viewports->Add(new SettingEntry("gui.gamepad_sensitivity"));
viewports->Add(new SettingEntry("gui.gamepad_invert_x"));
viewports->Add(new SettingEntry("gui.gamepad_invert_y"));
#ifdef __APPLE__
/* We might need to emulate a right mouse button on mac */
viewports->Add(new SettingEntry("gui.right_mouse_btn_emulation"));

View File

@ -140,6 +140,13 @@ enum ScrollWheelScrollingSetting : uint8_t {
SWS_OFF = 2 ///< Scroll wheel has no effect.
};
/** Settings related to gamepad stick selection. */
enum GamepadStickSelection : uint8_t {
GSS_DISABLED = 0, ///< Gamepad scrolling disabled.
GSS_LEFT_STICK = 1, ///< Use left analog stick for scrolling.
GSS_RIGHT_STICK = 2, ///< Use right analog stick for scrolling.
};
/** Settings related to the GUI and other stuff that is not saved in the savegame. */
struct GUISettings {
bool sg_full_load_any; ///< new full load calculation, any cargo must be full read from pre v93 savegames
@ -183,6 +190,11 @@ struct GUISettings {
uint8_t right_mouse_btn_emulation; ///< should we emulate right mouse clicking?
uint8_t scrollwheel_scrolling; ///< scrolling using the scroll wheel?
uint8_t scrollwheel_multiplier; ///< how much 'wheel' per incoming event from the OS?
uint8_t gamepad_deadzone; ///< deadzone for gamepad analog sticks (0-100)
uint8_t gamepad_sensitivity; ///< sensitivity multiplier for gamepad scrolling
bool gamepad_invert_x; ///< invert X axis for gamepad scrolling?
bool gamepad_invert_y; ///< invert Y axis for gamepad scrolling?
uint8_t gamepad_stick_selection; ///< which stick to use for scrolling (left/right/disabled)
bool timetable_arrival_departure; ///< show arrivals and departures in vehicle timetables
RightClickClose right_click_wnd_close; ///< close window with right click
bool pause_on_newgame; ///< whether to start new games paused or not

View File

@ -912,3 +912,62 @@ post_cb = [](auto) { SetupWidgetDimensions(); ReInitAllWindows(true); }
cat = SC_BASIC
startup = true
[SDTC_VAR]
var = gui.gamepad_deadzone
type = SLE_UINT8
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = 10
min = 0
max = 100
interval = 5
str = STR_CONFIG_SETTING_GAMEPAD_DEADZONE
strhelp = STR_CONFIG_SETTING_GAMEPAD_DEADZONE_HELPTEXT
strval = STR_JUST_COMMA
cat = SC_BASIC
startup = true
[SDTC_VAR]
var = gui.gamepad_sensitivity
type = SLE_UINT8
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = 10
min = 1
max = 100
interval = 5
str = STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY
strhelp = STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY_HELPTEXT
strval = STR_JUST_COMMA
cat = SC_BASIC
startup = true
[SDTC_BOOL]
var = gui.gamepad_invert_x
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = false
str = STR_CONFIG_SETTING_GAMEPAD_INVERT_X
strhelp = STR_CONFIG_SETTING_GAMEPAD_INVERT_X_HELPTEXT
cat = SC_BASIC
startup = true
[SDTC_BOOL]
var = gui.gamepad_invert_y
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = false
str = STR_CONFIG_SETTING_GAMEPAD_INVERT_Y
strhelp = STR_CONFIG_SETTING_GAMEPAD_INVERT_Y_HELPTEXT
cat = SC_BASIC
startup = true
[SDTC_VAR]
var = gui.gamepad_stick_selection
type = SLE_UINT8
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync, SettingFlag::GuiDropdown
def = GSS_LEFT_STICK
min = GSS_DISABLED
max = GSS_RIGHT_STICK
str = STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION
strhelp = STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION_HELPTEXT
strval = STR_CONFIG_SETTING_GAMEPAD_STICK_DISABLED
cat = SC_BASIC
startup = true

View File

@ -20,6 +20,7 @@
#include "../fileio_func.h"
#include "../framerate_type.h"
#include "../window_func.h"
#include "../zoom_func.h"
#include "sdl2_v.h"
#include <SDL.h>
#ifdef __EMSCRIPTEN__
@ -524,6 +525,27 @@ bool VideoDriver_SDL_Base::PollEvent()
}
break;
}
case SDL_CONTROLLERDEVICEADDED: {
Debug(driver, 1, "SDL2: Gamepad device added, index: {}", ev.cdevice.which);
/* Try to open the newly connected gamepad */
if (this->gamepad == nullptr) {
this->OpenGamepad();
}
break;
}
case SDL_CONTROLLERDEVICEREMOVED: {
Debug(driver, 1, "SDL2: Gamepad device removed, instance ID: {}", ev.cdevice.which);
/* Close gamepad if it was removed */
if (this->gamepad != nullptr && ev.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(this->gamepad))) {
Debug(driver, 1, "SDL2: Current gamepad was removed, closing and reopening");
this->CloseGamepad();
/* Try to open another gamepad if available */
this->OpenGamepad();
}
break;
}
}
return true;
@ -539,6 +561,12 @@ static std::optional<std::string_view> InitializeSDL()
#endif
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) return SDL_GetError();
/* Initialize gamepad subsystem for gamepad scrolling support */
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) < 0) {
Debug(driver, 1, "SDL2: Failed to initialize gamepad subsystem: {}", SDL_GetError());
}
return std::nullopt;
}
@ -590,6 +618,11 @@ std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &pa
SDL_StopTextInput();
this->edit_box_focused = false;
/* Initialize gamepad for scrolling */
Debug(driver, 1, "SDL2: Attempting to initialize gamepad support");
Debug(driver, 1, "SDL2: Gamepad stick selection setting: {}", _settings_client.gui.gamepad_stick_selection);
this->OpenGamepad();
#ifdef __EMSCRIPTEN__
this->is_game_threaded = false;
#else
@ -601,6 +634,8 @@ std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &pa
void VideoDriver_SDL_Base::Stop()
{
this->CloseGamepad();
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
SDL_Quit(); // If there's nothing left, quit SDL
@ -629,6 +664,9 @@ void VideoDriver_SDL_Base::InputLoop()
(keys[SDL_SCANCODE_DOWN] ? 8 : 0);
if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
/* Process gamepad input for scrolling */
this->ProcessGamepadInput();
}
void VideoDriver_SDL_Base::LoopOnce()
@ -755,3 +793,84 @@ void VideoDriver_SDL_Base::UnlockVideoBuffer()
this->buffer_locked = false;
}
void VideoDriver_SDL_Base::OpenGamepad()
{
/* Don't open gamepad if already open or if gamepad scrolling is disabled */
if (this->gamepad != nullptr) {
Debug(driver, 1, "SDL2: Gamepad already open, skipping");
return;
}
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
Debug(driver, 1, "SDL2: Gamepad scrolling disabled, not opening gamepad");
return;
}
/* Check if any gamepads are available */
int num_gamepads = SDL_NumJoysticks();
Debug(driver, 1, "SDL2: Found {} joystick(s)", num_gamepads);
for (int i = 0; i < num_gamepads; i++) {
if (SDL_IsGameController(i)) {
Debug(driver, 1, "SDL2: Joystick {} is a gamepad, attempting to open", i);
this->gamepad = SDL_GameControllerOpen(i);
if (this->gamepad != nullptr) {
Debug(driver, 1, "SDL2: Opened gamepad: {}", SDL_GameControllerName(this->gamepad));
break;
} else {
Debug(driver, 1, "SDL2: Failed to open gamepad {}: {}", i, SDL_GetError());
}
} else {
Debug(driver, 1, "SDL2: Joystick {} is not a gamepad", i);
}
}
if (this->gamepad == nullptr) {
Debug(driver, 1, "SDL2: No gamepad opened");
}
}
void VideoDriver_SDL_Base::CloseGamepad()
{
if (this->gamepad != nullptr) {
SDL_GameControllerClose(this->gamepad);
this->gamepad = nullptr;
Debug(driver, 1, "SDL2: Closed gamepad");
}
}
void VideoDriver_SDL_Base::ProcessGamepadInput()
{
/* Skip if gamepad is not available */
if (this->gamepad == nullptr) {
static bool logged_no_gamepad = false;
if (!logged_no_gamepad) {
Debug(driver, 2, "SDL2: No gamepad available for input processing");
logged_no_gamepad = true;
}
return;
}
/* Check if gamepad is still connected */
if (!SDL_GameControllerGetAttached(this->gamepad)) {
Debug(driver, 1, "SDL2: Gamepad disconnected, closing and reopening");
this->CloseGamepad();
return;
}
/* Get analog stick values based on stick selection */
Sint16 stick_x = 0, stick_y = 0;
if (_settings_client.gui.gamepad_stick_selection == GSS_LEFT_STICK) {
stick_x = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_LEFTX);
stick_y = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_LEFTY);
Debug(driver, 3, "SDL2: Left stick raw values: x={}, y={}", stick_x, stick_y);
} else if (_settings_client.gui.gamepad_stick_selection == GSS_RIGHT_STICK) {
stick_x = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_RIGHTX);
stick_y = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_RIGHTY);
Debug(driver, 3, "SDL2: Right stick raw values: x={}, y={}", stick_x, stick_y);
}
/* Use the common gamepad handling function */
HandleGamepadScrolling(stick_x, stick_y, 32767);
}

View File

@ -14,6 +14,10 @@
#include "video_driver.hpp"
/* Forward declaration of SDL_GameController */
struct _SDL_GameController;
typedef struct _SDL_GameController SDL_GameController;
/** The SDL video driver. */
class VideoDriver_SDL_Base : public VideoDriver {
public:
@ -69,6 +73,13 @@ protected:
/** Create the main window. */
virtual bool CreateMainWindow(uint w, uint h, uint flags = 0);
protected:
/** Gamepad support for map scrolling */
SDL_GameController *gamepad = nullptr; ///< Currently opened gamepad.
void OpenGamepad();
void CloseGamepad();
void ProcessGamepadInput();
private:
void LoopOnce();
void MainLoopCleanup();

View File

@ -28,6 +28,7 @@
#include <windows.h>
#include <imm.h>
#include <versionhelpers.h>
#include <xinput.h>
#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
#include <winrt/Windows.UI.ViewManagement.h>
#endif
@ -401,6 +402,40 @@ static void CancelIMEComposition(HWND hwnd)
HandleTextInput({}, true);
}
#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
/* We only use WinRT functions on Windows 10 or later. Unfortunately, newer Windows SDKs are now
* linking the two functions below directly instead of using dynamic linking as previously.
* To avoid any runtime linking errors on Windows 7 or older, we stub in our own dynamic
* linking trampoline. */
static LibraryLoader _combase("combase.dll");
extern "C" int32_t __stdcall WINRT_IMPL_RoOriginateLanguageException(int32_t error, void *message, void *languageException) noexcept
{
typedef BOOL(WINAPI *PFNRoOriginateLanguageException)(int32_t, void *, void *);
static PFNRoOriginateLanguageException RoOriginateLanguageException = _combase.GetFunction("RoOriginateLanguageException");
if (RoOriginateLanguageException != nullptr) {
return RoOriginateLanguageException(error, message, languageException);
} else {
return TRUE;
}
}
extern "C" int32_t __stdcall WINRT_IMPL_RoGetActivationFactory(void *classId, winrt::guid const &iid, void **factory) noexcept
{
typedef BOOL(WINAPI *PFNRoGetActivationFactory)(void *, winrt::guid const &, void **);
static PFNRoGetActivationFactory RoGetActivationFactory = _combase.GetFunction("RoGetActivationFactory");
if (RoGetActivationFactory != nullptr) {
return RoGetActivationFactory(classId, iid, factory);
} else {
*factory = nullptr;
return winrt::impl::error_class_not_available;
}
}
#endif
static bool IsDarkModeEnabled()
{
/* Only build if SDK is Windows 10 1803 or later. */
@ -950,6 +985,9 @@ void VideoDriver_Win32Base::InputLoop()
}
if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
/* Process gamepad input for scrolling */
this->ProcessGamepadInput();
}
bool VideoDriver_Win32Base::PollEvent()
@ -1109,6 +1147,106 @@ void VideoDriver_Win32Base::UnlockVideoBuffer()
this->buffer_locked = false;
}
void VideoDriver_Win32Base::OpenGamepad()
{
/* Don't open gamepad if already open or if gamepad scrolling is disabled */
if (this->gamepad_user_index != XUSER_MAX_COUNT) {
Debug(driver, 1, "Win32: Gamepad already open, skipping");
return;
}
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
Debug(driver, 1, "Win32: Gamepad scrolling disabled, not opening gamepad");
return;
}
/* Check for any connected gamepads */
for (DWORD i = 0; i < XUSER_MAX_COUNT; i++) {
XINPUT_STATE state = {};
if (XInputGetState(i, &state) == ERROR_SUCCESS) {
this->gamepad_user_index = i;
Debug(driver, 1, "Win32: Opened gamepad at index {}", i);
return;
}
}
}
void VideoDriver_Win32Base::CloseGamepad()
{
if (this->gamepad_user_index != XUSER_MAX_COUNT) {
this->gamepad_user_index = XUSER_MAX_COUNT;
Debug(driver, 1, "Win32: Closed gamepad");
}
}
void VideoDriver_Win32Base::ProcessGamepadInput()
{
/* Skip if gamepad scrolling is disabled */
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
return;
}
/* If no gamepad is currently open, try to reconnect periodically */
if (this->gamepad_user_index == XUSER_MAX_COUNT) {
static bool logged_no_gamepad = false;
/* Only try to reconnect every 60 frames (~1 second at 60 FPS) to avoid spam */
if (this->gamepad_reconnect_timer > 0) {
this->gamepad_reconnect_timer--;
if (!logged_no_gamepad) {
Debug(driver, 2, "Win32: No gamepad available for input processing");
logged_no_gamepad = true;
}
return;
}
/* Try to open gamepad */
this->OpenGamepad();
/* If still no gamepad, set timer for next retry */
if (this->gamepad_user_index == XUSER_MAX_COUNT) {
this->gamepad_reconnect_timer = 60; /* Retry in ~1 second */
if (!logged_no_gamepad) {
Debug(driver, 2, "Win32: No gamepad available for input processing");
logged_no_gamepad = true;
}
return;
} else {
/* Successfully reconnected */
logged_no_gamepad = false;
}
}
/* Get gamepad state */
XINPUT_STATE state = {};
if (XInputGetState(this->gamepad_user_index, &state) != ERROR_SUCCESS) {
Debug(driver, 1, "Win32: Gamepad disconnected, closing and will retry connection");
this->CloseGamepad();
this->gamepad_reconnect_timer = 60; /* Start retry timer */
return;
}
/* Get analog stick values based on stick selection
* Note: XInput uses SHORT values for stick positions, but we have to extend to INT
* to avoid overflow when inverting the Y-axis value */
INT stick_x = 0, stick_y = 0;
if (_settings_client.gui.gamepad_stick_selection == GSS_LEFT_STICK) {
stick_x = state.Gamepad.sThumbLX;
stick_y = state.Gamepad.sThumbLY;
Debug(driver, 3, "Win32: Left stick raw values: x={}, y={}", stick_x, stick_y);
} else if (_settings_client.gui.gamepad_stick_selection == GSS_RIGHT_STICK) {
stick_x = state.Gamepad.sThumbRX;
stick_y = state.Gamepad.sThumbRY;
Debug(driver, 3, "Win32: Right stick raw values: x={}, y={}", stick_x, stick_y);
}
stick_y = -stick_y; // Xinput Y-axis is inverted from other libraries
/* Use the common gamepad handling function */
HandleGamepadScrolling(stick_x, stick_y, 32767);
}
static FVideoDriver_Win32GDI iFVideoDriver_Win32GDI;
@ -1124,6 +1262,11 @@ std::optional<std::string_view> VideoDriver_Win32GDI::Start(const StringList &pa
MarkWholeScreenDirty();
/* Initialize gamepad for scrolling */
Debug(driver, 1, "Win32: Attempting to initialize gamepad support");
Debug(driver, 1, "Win32: Gamepad stick selection setting: {}", _settings_client.gui.gamepad_stick_selection);
this->OpenGamepad();
this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
return std::nullopt;
@ -1131,6 +1274,7 @@ std::optional<std::string_view> VideoDriver_Win32GDI::Start(const StringList &pa
void VideoDriver_Win32GDI::Stop()
{
this->CloseGamepad();
DeleteObject(this->gdi_palette);
DeleteObject(this->dib_sect);
@ -1438,6 +1582,11 @@ std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(const StringList
MarkWholeScreenDirty();
/* Initialize gamepad for scrolling */
Debug(driver, 1, "Win32: Attempting to initialize gamepad support");
Debug(driver, 1, "Win32: Gamepad stick selection setting: {}", _settings_client.gui.gamepad_stick_selection);
this->OpenGamepad();
this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
return std::nullopt;
@ -1445,6 +1594,7 @@ std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(const StringList
void VideoDriver_Win32OpenGL::Stop()
{
this->CloseGamepad();
this->DestroyContext();
this->VideoDriver_Win32Base::Stop();
}

View File

@ -14,6 +14,7 @@
#include <mutex>
#include <condition_variable>
#include <windows.h>
#include <xinput.h>
/** Base class for Windows video drivers. */
class VideoDriver_Win32Base : public VideoDriver {
@ -48,6 +49,13 @@ protected:
bool buffer_locked; ///< Video buffer was locked by the main thread.
/** Gamepad support for map scrolling */
DWORD gamepad_user_index = XUSER_MAX_COUNT; ///< Index of currently opened gamepad (XUSER_MAX_COUNT = no gamepad).
uint32_t gamepad_reconnect_timer = 0; ///< Timer for retrying gamepad connection after disconnect.
void OpenGamepad();
void CloseGamepad();
void ProcessGamepadInput();
Dimension GetScreenSize() const override;
float GetDPIScale() override;
void InputLoop() override;

View File

@ -3572,3 +3572,81 @@ void PickerWindowBase::Close([[maybe_unused]] int data)
ResetObjectToPlace();
this->Window::Close();
}
/**
* Process gamepad analog stick input for viewport scrolling.
* This is a common function that can be used by any video driver that supports gamepads.
* @param stick_x Raw analog stick X value (typically -32768 to 32767 range)
* @param stick_y Raw analog stick Y value (typically -32768 to 32767 range)
* @param max_axis_value Maximum value for the analog stick axes (e.g., 32767 for SDL2)
*/
void HandleGamepadScrolling(int stick_x, int stick_y, int max_axis_value)
{
/* Skip if gamepad stick selection is disabled */
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
return;
}
/* Apply deadzone (convert percentage to axis range) */
const int deadzone = (_settings_client.gui.gamepad_deadzone * max_axis_value) / 100;
if (abs(stick_x) < deadzone) stick_x = 0;
if (abs(stick_y) < deadzone) stick_y = 0;
/* Skip if no movement after deadzone */
if (stick_x == 0 && stick_y == 0) {
return;
}
/* Calculate scroll delta with sensitivity */
float sensitivity = _settings_client.gui.gamepad_sensitivity / 10.0f;
int delta_x = (int)(stick_x * sensitivity / (max_axis_value / 16)); // Scale down from axis range
int delta_y = (int)(stick_y * sensitivity / (max_axis_value / 16));
/* Apply axis inversion */
if (_settings_client.gui.gamepad_invert_x) delta_x = -delta_x;
if (_settings_client.gui.gamepad_invert_y) delta_y = -delta_y;
/* Skip if deltas are too small */
if (abs(delta_x) < 1 && abs(delta_y) < 1) {
return;
}
/* Apply scrolling based on cursor position */
if (_game_mode != GM_MENU && _game_mode != GM_BOOTSTRAP) {
Window *target_window = nullptr;
/* Check if cursor is over a window with a viewport */
Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
if (w != nullptr && w->viewport != nullptr) {
/* Check if cursor is actually over the viewport area within the window */
Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
if (pt.x >= w->viewport->left - w->left &&
pt.x < w->viewport->left - w->left + w->viewport->width &&
pt.y >= w->viewport->top - w->top &&
pt.y < w->viewport->top - w->top + w->viewport->height) {
target_window = w;
}
}
/* If no viewport under cursor, use main window */
if (target_window == nullptr) {
target_window = GetMainWindow();
}
/* Apply scrolling to the target viewport */
if (target_window != nullptr && target_window->viewport != nullptr) {
/* Check if the viewport is following a vehicle (similar to mouse scroll behavior) */
if (target_window == GetMainWindow() && target_window->viewport->follow_vehicle != VehicleID::Invalid()) {
/* If following a vehicle, center on it and stop following (like mouse scroll) */
const Vehicle *veh = Vehicle::Get(target_window->viewport->follow_vehicle);
ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
return; // Don't apply gamepad scroll, just like mouse scroll returns ES_NOT_HANDLED
}
/* Apply the scroll using the same method as keyboard scrolling */
target_window->viewport->dest_scrollpos_x += ScaleByZoom(delta_x, target_window->viewport->zoom);
target_window->viewport->dest_scrollpos_y += ScaleByZoom(delta_y, target_window->viewport->zoom);
}
}
}