diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 0000000..d2ff733 --- /dev/null +++ b/.clang-format-ignore @@ -0,0 +1,5 @@ +# Repository-relative exclusions for shared FormatValidation. +# Only src/, include/, and tests/ are selected; dependencies and artifacts are excluded. +**/thirdparty/** +**/build/** +**/install/** diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml new file mode 100644 index 0000000..e7736b0 --- /dev/null +++ b/.github/workflows/clang-format.yml @@ -0,0 +1,31 @@ +name: clang-format + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: clang-format-${{ github.ref }} + cancel-in-progress: true + +jobs: + clang-format: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install pinned formatter + run: python -m pip install clang-format==23.1.3 + - name: Configure formatting targets + run: cmake -S . -B build/format -DFORMAT_VALIDATION_ONLY=ON + - name: Check all owned C/C++ sources + run: cmake --build build/format --target format-check diff --git a/.gitignore b/.gitignore index 81c7fe9..376022b 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,6 @@ /thirdparty/cache/ *.user __pycache__/ + +# Generated from the shared FormatValidation source during CMake configuration. +/.clang-format diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a3add9..f9c19e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,10 @@ cmake_minimum_required(VERSION 3.21) +option(FORMAT_VALIDATION_ONLY "Configure only clang-format targets without native dependencies" OFF) +if(FORMAT_VALIDATION_ONLY) + project(FormatValidation LANGUAGES NONE) + include(cmake/FormatValidation.cmake) + return() +endif() cmake_policy(SET CMP0091 NEW) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") project(ResourceReplacer LANGUAGES CXX) @@ -87,3 +93,6 @@ if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) metahooksv_add_launch_game() endif() endif() + +# Shared formatting targets are explicit; ordinary native builds do not run them. +include(cmake/FormatValidation.cmake) diff --git a/README.md b/README.md index 340566c..6b47d90 100644 --- a/README.md +++ b/README.md @@ -75,3 +75,36 @@ python scripts\validate-gamedata.py install\x86\Release\svencoop\metahook\gameda ## License Licensed under the [MIT License](LICENSE); each dependency retains its own license. + +## C/C++ formatting + +Formatting uses [MetaHookSv/FormatValidation](https://github.com/MetaHookSv/FormatValidation) +and clang-format **23.1.3**, with the DiligentCore style (4 spaces, preserved include +order). Install the formatter for the Python interpreter used by CMake: + +```sh +python -m pip install clang-format==23.1.3 +cmake -S . -B build/format "-DFORMAT_VALIDATION_ONLY=ON" +cmake --build build/format --target format-check +cmake --build build/format --target format +``` + +The format-only configuration needs CMake 3.21+, Git, Python 3.9+ (CI uses 3.12), +and a build generator; `-G Ninja` works without Visual Studio. It prepares no native +SDK or game dependencies. Formatting targets are explicit and are not part of a +normal DLL build. With a Visual Studio generator, add `--config Debug` or +`--config Release` when building a formatting target. + +The aggregate provides `FORMAT_VALIDATION_SOURCE_PATH=thirdparty/FormatValidation`. +Standalone components accept that CMake variable or its environment counterpart; +if empty, FetchContent downloads the fixed tooling commit. Quote relative paths, +for example `"-DFORMAT_VALIDATION_SOURCE_PATH=../../thirdparty/FormatValidation"`. +Configuration generates the ignored root `.clang-format` for editors; change the +shared style rather than that generated copy. An optional +`FORMAT_VALIDATION_CLANG_FORMAT_EXECUTABLE` selects an explicit formatter, whose +version must still match the pin. + +Checks cover owned C/C++ files in `src/`, `include/`, and `tests/`, including +non-ignored new files. Repository-relative exclusions live in `.clang-format-ignore`. +Third-party sources and build artifacts are excluded. The `clang-format` workflow +checks the full scope on pushes, pull requests, and manual runs. diff --git a/README.zh-CN.md b/README.zh-CN.md index 5676a73..4e47279 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -70,3 +70,33 @@ python scripts\validate-gamedata.py install\x86\Release\svencoop\metahook\gameda ## 许可证 使用 [MIT License](LICENSE),各依赖保留其自身许可证。 + +## C/C++ 格式化 + +使用 [MetaHookSv/FormatValidation](https://github.com/MetaHookSv/FormatValidation) +共享工具及固定版本 **clang-format 23.1.3**,采用 DiligentCore 风格(4 空格,保留 +include 顺序)。为 CMake 使用的 Python 解释器安装格式工具: + +```sh +python -m pip install clang-format==23.1.3 +cmake -S . -B build/format "-DFORMAT_VALIDATION_ONLY=ON" +cmake --build build/format --target format-check +cmake --build build/format --target format +``` + +格式专用配置需要 CMake 3.21+、Git、Python 3.9+(CI 使用 3.12)及构建生成器; +使用 `-G Ninja` 可无需 Visual Studio。它不准备原生 SDK 或游戏依赖。 +格式目标需显式执行,不加入普通 DLL 构建。使用 Visual Studio 生成器时,执行目标 +需追加 `--config Debug` 或 `--config Release`。 + +聚合仓库注入 `FORMAT_VALIDATION_SOURCE_PATH=thirdparty/FormatValidation`。 +独立组件支持该 CMake 参数及同名环境变量;为空时通过 FetchContent 获取固定工具 +提交。相对路径应加引号,例如 +`"-DFORMAT_VALIDATION_SOURCE_PATH=../../thirdparty/FormatValidation"`。 +配置时在仓库根目录生成被 gitignore 的 `.clang-format` 供编辑器使用;格式规则应 +在共享仓库修改,不修改生成副本。可通过 `FORMAT_VALIDATION_CLANG_FORMAT_EXECUTABLE` +指定工具路径,但版本仍须与固定版本一致。 + +检查覆盖 `src/`、`include/`、`tests/` 中维护的 C/C++ 文件,包括未被 Git 忽略的新文件。 +相对仓库根目录的排除规则位于 `.clang-format-ignore`;第三方源和构建产物不纳入检查。 +`clang-format` workflow 在 push、pull request 和手动运行时执行全量检查。 diff --git a/cmake/FormatValidation.cmake b/cmake/FormatValidation.cmake new file mode 100644 index 0000000..eb23b93 --- /dev/null +++ b/cmake/FormatValidation.cmake @@ -0,0 +1,26 @@ +# Shared tool implementation; only this dependency bootstrap belongs to the consumer. +if(NOT DEFINED FORMAT_VALIDATION_SOURCE_PATH) + set(FORMAT_VALIDATION_SOURCE_PATH "$ENV{FORMAT_VALIDATION_SOURCE_PATH}" CACHE PATH + "FormatValidation source tree; empty fetches the pinned tooling") +endif() +if(FORMAT_VALIDATION_SOURCE_PATH) + get_filename_component(_format_validation_source "${FORMAT_VALIDATION_SOURCE_PATH}" + ABSOLUTE BASE_DIR "${CMAKE_CURRENT_LIST_DIR}/..") +else() + include(FetchContent) + FetchContent_Declare(resourcereplacer_format_validation + GIT_REPOSITORY https://github.com/MetaHookSv/FormatValidation.git + GIT_TAG 13c9fabe058e1f887ad1b03bb6884de911192c6a # v1.0.0; retained immutable tooling commit + GIT_SUBMODULES "" + # Populate the tooling without configuring its own test project. + SOURCE_SUBDIR cmake) + FetchContent_MakeAvailable(resourcereplacer_format_validation) + set(_format_validation_source "${resourcereplacer_format_validation_SOURCE_DIR}") +endif() +foreach(_format_validation_file .clang-format clang-format-validate.py cmake/FormatValidation.cmake) + if(NOT EXISTS "${_format_validation_source}/${_format_validation_file}") + message(FATAL_ERROR "FORMAT_VALIDATION_SOURCE_PATH is missing ${_format_validation_file}: ${_format_validation_source}") + endif() +endforeach() +include("${_format_validation_source}/cmake/FormatValidation.cmake") +format_validation_add_component(ResourceReplacer "${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/src/ResourceReplacer.cpp b/src/ResourceReplacer.cpp index 8c14181..be088b3 100644 --- a/src/ResourceReplacer.cpp +++ b/src/ResourceReplacer.cpp @@ -11,124 +11,117 @@ class IResourceReplaceEntry { public: - virtual ~IResourceReplaceEntry() - { + virtual ~IResourceReplaceEntry() + { + } - } - - /* + /* Purpose: Fill ReplacedFileName with replaced file name if szSourceFileName matched. */ - virtual bool GetReplacedFileName(const char* szSourceFileName, std::string &ReplacedFileName) = 0; + virtual bool GetReplacedFileName(const char* szSourceFileName, std::string& ReplacedFileName) = 0; }; class CPlainResourceReplaceEntry : public IResourceReplaceEntry { public: - CPlainResourceReplaceEntry(const char *src, const char* replace) : m_SourceFileName (src), m_ReplacedFileName(replace) - { - - } - CPlainResourceReplaceEntry(const std::string & src, const std::string& replace) : m_SourceFileName(src), m_ReplacedFileName(replace) - { - - } - ~CPlainResourceReplaceEntry() - { - - } - - bool GetReplacedFileName(const char* szSourceFileName, std::string &ReplacedFileName) override - { - if (!stricmp(m_SourceFileName.c_str(), szSourceFileName)) - { - auto SourceExtension = V_GetFileExtension(m_SourceFileName.c_str()); - auto ReplaceExtension = V_GetFileExtension(m_ReplacedFileName.c_str()); - - if (!stricmp(SourceExtension, ReplaceExtension)) - { - ReplacedFileName = m_ReplacedFileName; - return true; - } - } - - return false; - } + CPlainResourceReplaceEntry(const char* src, const char* replace) : m_SourceFileName(src), m_ReplacedFileName(replace) + { + } + CPlainResourceReplaceEntry(const std::string& src, const std::string& replace) : m_SourceFileName(src), m_ReplacedFileName(replace) + { + } + ~CPlainResourceReplaceEntry() + { + } + + bool GetReplacedFileName(const char* szSourceFileName, std::string& ReplacedFileName) override + { + if (!stricmp(m_SourceFileName.c_str(), szSourceFileName)) + { + auto SourceExtension = V_GetFileExtension(m_SourceFileName.c_str()); + auto ReplaceExtension = V_GetFileExtension(m_ReplacedFileName.c_str()); + + if (!stricmp(SourceExtension, ReplaceExtension)) + { + ReplacedFileName = m_ReplacedFileName; + return true; + } + } + + return false; + } private: - std::string m_SourceFileName; - std::string m_ReplacedFileName; + std::string m_SourceFileName; + std::string m_ReplacedFileName; }; class CRegexResourceReplaceEntry : public IResourceReplaceEntry { public: - CRegexResourceReplaceEntry(const std::string& pattern, const std::string& replace) - : m_Pattern(pattern), m_Replacement(replace), m_Regex(pattern, std::regex::ECMAScript) - { - - } - - bool GetReplacedFileName(const char* szSourceFileName, std::string& ReplacedFileName) override - { - std::cmatch match; - if (std::regex_match(szSourceFileName, match, m_Regex)) - { - std::string NewReplacedFileName = std::regex_replace(szSourceFileName, m_Regex, m_Replacement); - - auto SourceExtension = V_GetFileExtension(szSourceFileName); - auto ReplaceExtension = V_GetFileExtension(NewReplacedFileName.c_str()); - - if (!stricmp(SourceExtension, ReplaceExtension)) - { - ReplacedFileName = NewReplacedFileName; - return true; - } - } - return false; - } + CRegexResourceReplaceEntry(const std::string& pattern, const std::string& replace) : m_Pattern(pattern), m_Replacement(replace), m_Regex(pattern, std::regex::ECMAScript) + { + } + + bool GetReplacedFileName(const char* szSourceFileName, std::string& ReplacedFileName) override + { + std::cmatch match; + if (std::regex_match(szSourceFileName, match, m_Regex)) + { + std::string NewReplacedFileName = std::regex_replace(szSourceFileName, m_Regex, m_Replacement); + + auto SourceExtension = V_GetFileExtension(szSourceFileName); + auto ReplaceExtension = V_GetFileExtension(NewReplacedFileName.c_str()); + + if (!stricmp(SourceExtension, ReplaceExtension)) + { + ReplacedFileName = NewReplacedFileName; + return true; + } + } + return false; + } private: - std::string m_Pattern; - std::string m_Replacement; - std::regex m_Regex; + std::string m_Pattern; + std::string m_Replacement; + std::regex m_Regex; }; class CResourceReplacer : public IResourceReplacer { private: - std::vector m_GlobalEntries; - std::vector m_MapEntries; + std::vector m_GlobalEntries; + std::vector m_MapEntries; public: - - void FreeMapEntries() override - { - for (auto entry : m_MapEntries) - { - delete entry; - } - - m_MapEntries.clear(); - } - - void FreeGlobalEntries() override - { - for (auto entry : m_GlobalEntries) - { - delete entry; - } - - m_GlobalEntries.clear(); - } - - void Shutdown() override - { - FreeMapEntries(); - FreeGlobalEntries(); - } - - /* + void FreeMapEntries() override + { + for (auto entry : m_MapEntries) + { + delete entry; + } + + m_MapEntries.clear(); + } + + void FreeGlobalEntries() override + { + for (auto entry : m_GlobalEntries) + { + delete entry; + } + + m_GlobalEntries.clear(); + } + + void Shutdown() override + { + FreeMapEntries(); + FreeGlobalEntries(); + } + + /* Purpose: Parse replace list like, the quota can be omitted. Ignore lines start with ## or // @@ -147,100 +140,100 @@ class CResourceReplacer : public IResourceReplacer */ - void LoadReplaceList(const char* pszFileContent, std::vector &entries) - { - std::istringstream fileStream(pszFileContent); // Use istringstream to read the file content line by line - std::string line; - - while (std::getline(fileStream, line)) - { - // Trim leading and trailing whitespace - line = TrimString(line); - - // Skip empty lines and comments - if (line.empty() || line[0] == '#' || line[0] == '/') - continue; - - // Split the line into two tokens - std::istringstream lineStream(line); - std::string src, replace, token; - lineStream >> std::quoted(src) >> std::quoted(replace); // std::quoted to handle optional quotes around file names - - // Check if both file names were read successfully - if (!src.empty() && !replace.empty()) - { - if (lineStream >> token && token == "regex") - { - // If the token "regex" is found, use the regex-based replacement entry - CRegexResourceReplaceEntry* entry = new CRegexResourceReplaceEntry(src, replace); - entries.push_back(entry); - } - else - { - // Otherwise, use the plain replacement entry - CPlainResourceReplaceEntry* entry = new CPlainResourceReplaceEntry(src, replace); - entries.push_back(entry); - } - } - } - } - - void LoadGlobalReplaceList(const char *szFileName) override - { - const char* pszFileContent = (const char*)gEngfuncs.COM_LoadFile(szFileName, 5, NULL); - - if (!pszFileContent) - { - gEngfuncs.Con_DPrintf("LoadGlobalReplaceList: Could not load replace list file \"%s\"\n", szFileName); - return; - } - - LoadReplaceList(pszFileContent, m_GlobalEntries); - - gEngfuncs.COM_FreeFile((void*)pszFileContent); - } - - void LoadMapReplaceList(const char* szFileName) override - { - const char* pszFileContent = (const char*)gEngfuncs.COM_LoadFile(szFileName, 5, NULL); - - if (!pszFileContent) - { - gEngfuncs.Con_DPrintf("LoadMapReplaceList: Could not load replace list file \"%s\"\n", szFileName); - return; - } - - LoadReplaceList(pszFileContent, m_MapEntries); - - gEngfuncs.COM_FreeFile((void*)pszFileContent); - } - - /* + void LoadReplaceList(const char* pszFileContent, std::vector& entries) + { + std::istringstream fileStream(pszFileContent); // Use istringstream to read the file content line by line + std::string line; + + while (std::getline(fileStream, line)) + { + // Trim leading and trailing whitespace + line = TrimString(line); + + // Skip empty lines and comments + if (line.empty() || line[0] == '#' || line[0] == '/') + continue; + + // Split the line into two tokens + std::istringstream lineStream(line); + std::string src, replace, token; + lineStream >> std::quoted(src) >> std::quoted(replace); // std::quoted to handle optional quotes around file names + + // Check if both file names were read successfully + if (!src.empty() && !replace.empty()) + { + if (lineStream >> token && token == "regex") + { + // If the token "regex" is found, use the regex-based replacement entry + CRegexResourceReplaceEntry* entry = new CRegexResourceReplaceEntry(src, replace); + entries.push_back(entry); + } + else + { + // Otherwise, use the plain replacement entry + CPlainResourceReplaceEntry* entry = new CPlainResourceReplaceEntry(src, replace); + entries.push_back(entry); + } + } + } + } + + void LoadGlobalReplaceList(const char* szFileName) override + { + const char* pszFileContent = (const char*)gEngfuncs.COM_LoadFile(szFileName, 5, NULL); + + if (!pszFileContent) + { + gEngfuncs.Con_DPrintf("LoadGlobalReplaceList: Could not load replace list file \"%s\"\n", szFileName); + return; + } + + LoadReplaceList(pszFileContent, m_GlobalEntries); + + gEngfuncs.COM_FreeFile((void*)pszFileContent); + } + + void LoadMapReplaceList(const char* szFileName) override + { + const char* pszFileContent = (const char*)gEngfuncs.COM_LoadFile(szFileName, 5, NULL); + + if (!pszFileContent) + { + gEngfuncs.Con_DPrintf("LoadMapReplaceList: Could not load replace list file \"%s\"\n", szFileName); + return; + } + + LoadReplaceList(pszFileContent, m_MapEntries); + + gEngfuncs.COM_FreeFile((void*)pszFileContent); + } + + /* Purpose: Fill the ReplacedFileName if szSourceFileName matched, by iterating m_Entries. */ - bool ReplaceFileName(const char* szSourceFileName, std::string& ReplacedFileName) override - { - for (auto entry : m_MapEntries) - { - if (entry->GetReplacedFileName(szSourceFileName, ReplacedFileName)) - { - return true; - } - } - - for (auto entry : m_GlobalEntries) - { - if (entry->GetReplacedFileName(szSourceFileName, ReplacedFileName)) - { - return true; - } - } - - return false; - } + bool ReplaceFileName(const char* szSourceFileName, std::string& ReplacedFileName) override + { + for (auto entry : m_MapEntries) + { + if (entry->GetReplacedFileName(szSourceFileName, ReplacedFileName)) + { + return true; + } + } + + for (auto entry : m_GlobalEntries) + { + if (entry->GetReplacedFileName(szSourceFileName, ReplacedFileName)) + { + return true; + } + } + + return false; + } }; static CResourceReplacer s_ModelReplacer; @@ -248,10 +241,10 @@ static CResourceReplacer s_SoundReplacer; IResourceReplacer* ModelReplacer() { - return &s_ModelReplacer; + return &s_ModelReplacer; } IResourceReplacer* SoundReplacer() { - return &s_SoundReplacer; + return &s_SoundReplacer; } \ No newline at end of file diff --git a/src/ResourceReplacer.h b/src/ResourceReplacer.h index d949bde..c2ff475 100644 --- a/src/ResourceReplacer.h +++ b/src/ResourceReplacer.h @@ -6,12 +6,12 @@ class IResourceReplacer : public IBaseInterface { public: - virtual void FreeMapEntries() = 0; - virtual void FreeGlobalEntries() = 0; - virtual void Shutdown() = 0; - virtual void LoadGlobalReplaceList(const char* szFileName) = 0; - virtual void LoadMapReplaceList(const char* szFileName) = 0; - virtual bool ReplaceFileName(const char *szSourceFileName, std::string &ReplacedFileName) = 0; + virtual void FreeMapEntries() = 0; + virtual void FreeGlobalEntries() = 0; + virtual void Shutdown() = 0; + virtual void LoadGlobalReplaceList(const char* szFileName) = 0; + virtual void LoadMapReplaceList(const char* szFileName) = 0; + virtual bool ReplaceFileName(const char* szSourceFileName, std::string& ReplacedFileName) = 0; }; IResourceReplacer* ModelReplacer(); diff --git a/src/enginedef.h b/src/enginedef.h index c52ff53..bc85ae1 100644 --- a/src/enginedef.h +++ b/src/enginedef.h @@ -2,39 +2,39 @@ #include -#define MAX_QPATH 64 // max length of a quake game pathname +#define MAX_QPATH 64 // max length of a quake game pathname typedef struct sfx_s { - char name[MAX_QPATH]; - cache_user_t cache; - int servercount; -}sfx_t; + char name[MAX_QPATH]; + cache_user_t cache; + int servercount; +} sfx_t; typedef struct sfxcache_s { - int length; - int loopstart; - int speed; - int width; - int stereo; - byte data[1]; // variable sized + int length; + int loopstart; + int speed; + int width; + int stereo; + byte data[1]; // variable sized } sfxcache_t; typedef struct { - sfx_t* sfx; // sfx number - int leftvol; // 0-255 volume - int rightvol; // 0-255 volume - int end; // end time in global paintsamples - int pos; // sample position in sfx - int looping; // where to loop, -1 = no looping - int entnum; // to allow overriding a specific sound - int entchannel; // - vec3_t origin; // origin of sound effect - vec_t dist_mult; // distance multiplier (attenuation/clipK) - int master_vol; // 0-255 master volume - int isentence; - int iword; - int pitch; // real-time pitch after any modulation or shift by dynamic data + sfx_t* sfx; // sfx number + int leftvol; // 0-255 volume + int rightvol; // 0-255 volume + int end; // end time in global paintsamples + int pos; // sample position in sfx + int looping; // where to loop, -1 = no looping + int entnum; // to allow overriding a specific sound + int entchannel; // + vec3_t origin; // origin of sound effect + vec_t dist_mult; // distance multiplier (attenuation/clipK) + int master_vol; // 0-255 master volume + int isentence; + int iword; + int pitch; // real-time pitch after any modulation or shift by dynamic data } channel_t; \ No newline at end of file diff --git a/src/exportfuncs.cpp b/src/exportfuncs.cpp index c309b25..887fb1a 100644 --- a/src/exportfuncs.cpp +++ b/src/exportfuncs.cpp @@ -6,31 +6,31 @@ #include "ResourceReplacer.h" -cl_enginefunc_t gEngfuncs = {0}; -engine_studio_api_t IEngineStudio = {0}; -r_studio_interface_t **gpStudioInterface = NULL; -IKeyValuesSystem* g_pKeyValuesSystem = NULL; +cl_enginefunc_t gEngfuncs = {0}; +engine_studio_api_t IEngineStudio = {0}; +r_studio_interface_t** gpStudioInterface = NULL; +IKeyValuesSystem* g_pKeyValuesSystem = NULL; int HUD_VidInit(void) { - ModelReplacer()->FreeMapEntries(); - SoundReplacer()->FreeMapEntries(); + ModelReplacer()->FreeMapEntries(); + SoundReplacer()->FreeMapEntries(); - return gExportfuncs.HUD_VidInit(); + return gExportfuncs.HUD_VidInit(); } void HUD_Init(void) { - ModelReplacer()->LoadGlobalReplaceList("resreplacer/default_global.gmr"); - SoundReplacer()->LoadGlobalReplaceList("resreplacer/default_global.gsr"); + ModelReplacer()->LoadGlobalReplaceList("resreplacer/default_global.gmr"); + SoundReplacer()->LoadGlobalReplaceList("resreplacer/default_global.gsr"); - gExportfuncs.HUD_Init(); + gExportfuncs.HUD_Init(); } void HUD_Shutdown(void) { - ModelReplacer()->Shutdown(); - SoundReplacer()->Shutdown(); + ModelReplacer()->Shutdown(); + SoundReplacer()->Shutdown(); - return gExportfuncs.HUD_Shutdown(); + return gExportfuncs.HUD_Shutdown(); } \ No newline at end of file diff --git a/src/exportfuncs.h b/src/exportfuncs.h index 160244e..d5d2460 100644 --- a/src/exportfuncs.h +++ b/src/exportfuncs.h @@ -3,6 +3,6 @@ #include #include -int HUD_VidInit(void); +int HUD_VidInit(void); void HUD_Init(void); void HUD_Shutdown(void); \ No newline at end of file diff --git a/src/plugins.cpp b/src/plugins.cpp index 26bceba..afe8789 100644 --- a/src/plugins.cpp +++ b/src/plugins.cpp @@ -3,82 +3,81 @@ #include "privatehook.h" #include "ResourceReplacer.h" -cl_exportfuncs_t gExportfuncs = { 0 }; -mh_interface_t* g_pInterface = NULL; -metahook_api_t* g_pMetaHookAPI = NULL; -mh_enginesave_t* g_pMetaSave = NULL; -IFileSystem* g_pFileSystem = NULL; +cl_exportfuncs_t gExportfuncs = {0}; +mh_interface_t* g_pInterface = NULL; +metahook_api_t* g_pMetaHookAPI = NULL; +mh_enginesave_t* g_pMetaSave = NULL; +IFileSystem* g_pFileSystem = NULL; IFileSystem_HL25* g_pFileSystem_HL25 = NULL; -int g_iEngineType = 0; +int g_iEngineType = 0; DWORD g_dwEngineBuildnum = 0; -mh_dll_info_t g_EngineDLLInfo = { 0 }; +mh_dll_info_t g_EngineDLLInfo = {0}; -void IPluginsV4::Init(metahook_api_t *pAPI, mh_interface_t *pInterface, mh_enginesave_t *pSave) +void IPluginsV4::Init(metahook_api_t* pAPI, mh_interface_t* pInterface, mh_enginesave_t* pSave) { - g_pInterface = pInterface; - g_pMetaHookAPI = pAPI; - g_pMetaSave = pSave; + g_pInterface = pInterface; + g_pMetaHookAPI = pAPI; + g_pMetaSave = pSave; } void IPluginsV4::Shutdown(void) { } -void IPluginsV4::LoadEngine(cl_enginefunc_t *pEngfuncs) +void IPluginsV4::LoadEngine(cl_enginefunc_t* pEngfuncs) { - g_pFileSystem = g_pInterface->FileSystem; + g_pFileSystem = g_pInterface->FileSystem; - if (!g_pFileSystem) - { - g_pFileSystem_HL25 = g_pInterface->FileSystem_HL25; - } + if (!g_pFileSystem) + { + g_pFileSystem_HL25 = g_pInterface->FileSystem_HL25; + } - g_iEngineType = g_pMetaHookAPI->GetEngineType(); - g_dwEngineBuildnum = g_pMetaHookAPI->GetEngineBuildnum(); + g_iEngineType = g_pMetaHookAPI->GetEngineType(); + g_dwEngineBuildnum = g_pMetaHookAPI->GetEngineBuildnum(); - g_EngineDLLInfo.ImageBase = g_pMetaHookAPI->GetEngineBase(); + g_EngineDLLInfo.ImageBase = g_pMetaHookAPI->GetEngineBase(); - memcpy(&gEngfuncs, pEngfuncs, sizeof(gEngfuncs)); + memcpy(&gEngfuncs, pEngfuncs, sizeof(gEngfuncs)); - Engine_FillAddress(); - Engine_InstallHooks(); + Engine_FillAddress(); + Engine_InstallHooks(); } -void IPluginsV4::LoadClient(cl_exportfuncs_t *pExportFunc) +void IPluginsV4::LoadClient(cl_exportfuncs_t* pExportFunc) { - memcpy(&gExportfuncs, pExportFunc, sizeof(gExportfuncs)); + memcpy(&gExportfuncs, pExportFunc, sizeof(gExportfuncs)); - pExportFunc->HUD_VidInit = HUD_VidInit; - pExportFunc->HUD_Init = HUD_Init; - pExportFunc->HUD_Shutdown = HUD_Shutdown; + pExportFunc->HUD_VidInit = HUD_VidInit; + pExportFunc->HUD_Init = HUD_Init; + pExportFunc->HUD_Shutdown = HUD_Shutdown; } void IPluginsV4::ExitGame(int iResult) { - Engine_UninstallHooks(); + Engine_UninstallHooks(); } const char completeVersion[] = + { + BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3, + '-', + BUILD_MONTH_CH0, BUILD_MONTH_CH1, + '-', + BUILD_DAY_CH0, BUILD_DAY_CH1, + 'T', + BUILD_HOUR_CH0, BUILD_HOUR_CH1, + ':', + BUILD_MIN_CH0, BUILD_MIN_CH1, + ':', + BUILD_SEC_CH0, BUILD_SEC_CH1, + '\0'}; + +const char* IPluginsV4::GetVersion(void) { - BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3, - '-', - BUILD_MONTH_CH0, BUILD_MONTH_CH1, - '-', - BUILD_DAY_CH0, BUILD_DAY_CH1, - 'T', - BUILD_HOUR_CH0, BUILD_HOUR_CH1, - ':', - BUILD_MIN_CH0, BUILD_MIN_CH1, - ':', - BUILD_SEC_CH0, BUILD_SEC_CH1, - '\0' -}; - -const char *IPluginsV4::GetVersion(void) -{ - return completeVersion; + return completeVersion; } EXPOSE_SINGLE_INTERFACE(IPluginsV4, IPluginsV4, METAHOOK_PLUGIN_API_VERSION_V4); \ No newline at end of file diff --git a/src/plugins.h b/src/plugins.h index a5d6af2..01dab73 100644 --- a/src/plugins.h +++ b/src/plugins.h @@ -5,34 +5,45 @@ class IFileSystem; extern IFileSystem* g_pFileSystem; -extern int g_iEngineType; +extern int g_iEngineType; extern DWORD g_dwEngineBuildnum; extern mh_dll_info_t g_EngineDLLInfo; -#define MHPluginName "ResourceReplacer" -#define Sys_Error(msg, ...) g_pMetaHookAPI->SysError("[" MHPluginName "] " msg, __VA_ARGS__); -#define Sig_NotFound(name) Sys_Error("Could not found: %s\nEngine buildnum: %d", #name, g_dwEngineBuildnum); -#define Sig_VarNotFound(name) if(!name) Sig_NotFound(name) -#define Sig_AddrNotFound(name) if(!addr) Sig_NotFound(name) -#define Sig_FuncNotFound(name) if(!gPrivateFuncs.name) Sig_NotFound(name) - -#define Sig_Length(a) (sizeof(a)-1) -#define Search_Pattern(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) -#define Search_Pattern_Data(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) -#define Search_Pattern_Rdata(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.RdataBase, dllinfo.RdataSize, sig, Sig_Length(sig)) -#define Search_Pattern_From_Size(fn, size, sig) g_pMetaHookAPI->SearchPattern((void *)(fn), size, sig, Sig_Length(sig)) -#define Search_Pattern_From(fn, sig, dllinfo) g_pMetaHookAPI->SearchPattern((void *)(fn), ((PUCHAR)dllinfo.TextBase + dllinfo.TextSize) - (PUCHAR)(fn), sig, Sig_Length(sig)) - -#define Search_Pattern_NoWildCard(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) -#define Search_Pattern_NoWildCard_Data(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) +#define MHPluginName "ResourceReplacer" +#define Sys_Error(msg, ...) g_pMetaHookAPI->SysError("[" MHPluginName "] " msg, __VA_ARGS__); +#define Sig_NotFound(name) Sys_Error("Could not found: %s\nEngine buildnum: %d", #name, g_dwEngineBuildnum); +#define Sig_VarNotFound(name) \ + if (!name) Sig_NotFound(name) +#define Sig_AddrNotFound(name) \ + if (!addr) Sig_NotFound(name) +#define Sig_FuncNotFound(name) \ + if (!gPrivateFuncs.name) Sig_NotFound(name) + +#define Sig_Length(a) (sizeof(a) - 1) +#define Search_Pattern(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) +#define Search_Pattern_Data(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) +#define Search_Pattern_Rdata(sig, dllinfo) g_pMetaHookAPI->SearchPattern(dllinfo.RdataBase, dllinfo.RdataSize, sig, Sig_Length(sig)) +#define Search_Pattern_From_Size(fn, size, sig) g_pMetaHookAPI->SearchPattern((void*)(fn), size, sig, Sig_Length(sig)) +#define Search_Pattern_From(fn, sig, dllinfo) g_pMetaHookAPI->SearchPattern((void*)(fn), ((PUCHAR)dllinfo.TextBase + dllinfo.TextSize) - (PUCHAR)(fn), sig, Sig_Length(sig)) + +#define Search_Pattern_NoWildCard(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.TextBase, dllinfo.TextSize, sig, Sig_Length(sig)) +#define Search_Pattern_NoWildCard_Data(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.DataBase, dllinfo.DataSize, sig, Sig_Length(sig)) #define Search_Pattern_NoWildCard_Rdata(sig, dllinfo) g_pMetaHookAPI->SearchPatternNoWildCard(dllinfo.RdataBase, dllinfo.RdataSize, sig, Sig_Length(sig)) -#define Install_InlineHook(fn) if(!g_phook_##fn) { g_phook_##fn = g_pMetaHookAPI->InlineHook((void *)gPrivateFuncs.fn, fn, (void **)&gPrivateFuncs.fn); } -#define Uninstall_Hook(fn) if(g_phook_##fn){g_pMetaHookAPI->UnHook(g_phook_##fn);g_phook_##fn = NULL;} +#define Install_InlineHook(fn) \ + if (!g_phook_##fn) { g_phook_##fn = g_pMetaHookAPI->InlineHook((void*)gPrivateFuncs.fn, fn, (void**)&gPrivateFuncs.fn); } +#define Uninstall_Hook(fn) \ + if (g_phook_##fn) \ + { \ + g_pMetaHookAPI->UnHook(g_phook_##fn); \ + g_phook_##fn = NULL; \ + } #define GetCallAddress(addr) g_pMetaHookAPI->GetNextCallAddr((PUCHAR)addr, 1) #define RVA_from_VA(name, dllinfo) (ULONG)((ULONG_PTR)name##_VA - (ULONG_PTR)dllinfo.ImageBase) #define VA_from_RVA(name, dllinfo) ((ULONG_PTR)dllinfo.ImageBase + (ULONG_PTR)name##_RVA) -#define Convert_VA_to_RVA(name, dllinfo) if(name##_VA) name##_RVA = ((ULONG_PTR)name##_VA - (ULONG_PTR)dllinfo.ImageBase) -#define Convert_RVA_to_VA(name, dllinfo) if(name##_RVA) name##_VA = (decltype(name##_VA))VA_from_RVA(name, dllinfo) +#define Convert_VA_to_RVA(name, dllinfo) \ + if (name##_VA) name##_RVA = ((ULONG_PTR)name##_VA - (ULONG_PTR)dllinfo.ImageBase) +#define Convert_RVA_to_VA(name, dllinfo) \ + if (name##_RVA) name##_VA = (decltype(name##_VA))VA_from_RVA(name, dllinfo) diff --git a/src/privatehook.cpp b/src/privatehook.cpp index b9fa6c7..acff960 100644 --- a/src/privatehook.cpp +++ b/src/privatehook.cpp @@ -10,14 +10,14 @@ static_assert(METAHOOK_API_VERSION >= 110, "ResourceReplacer consumes gamedata PATCH symbols through IsGameSymbolAvailable and requires MetaHook API 110"); -private_funcs_t gPrivateFuncs = { }; +private_funcs_t gPrivateFuncs = {}; static hook_t* g_phook_CL_PrecacheResources = NULL; struct CallSite_t { - std::string symbolName; - PVOID address; + std::string symbolName; + PVOID address; }; static std::vector g_S_LoadSound_FS_OpenCallSites; @@ -26,66 +26,66 @@ static std::vector g_Mod_LoadModel_FS_OpenCallSites; // On gamedata failure, print diagnostics (symbol / buildnum / CRC64 / status string) and abort via Sys_Error. static void ReportSymbolFailure(const char* moduleName, const char* symbolName, mh_gamesymbol_status_t status) { - uint64_t crc64 = 0; - mh_gamesymbol_status_t crcSt = g_pMetaHookAPI->GetModuleCRC64(g_EngineDLLInfo.ImageBase, &crc64); - - if (crcSt == MH_GAMESYMBOL_OK) - { - Sys_Error("Failed to resolve \"%s\" (module %s)\nEngine buildnum: %d\nCRC64: %016llx\nReason: %s", - symbolName, moduleName, g_dwEngineBuildnum, (unsigned long long)crc64, g_pMetaHookAPI->GetGameSymbolStatusString(status)); - } - else - { - Sys_Error("Failed to resolve \"%s\" (module %s)\nEngine buildnum: %d\nReason: %s", - symbolName, moduleName, g_dwEngineBuildnum, g_pMetaHookAPI->GetGameSymbolStatusString(status)); - } + uint64_t crc64 = 0; + mh_gamesymbol_status_t crcSt = g_pMetaHookAPI->GetModuleCRC64(g_EngineDLLInfo.ImageBase, &crc64); + + if (crcSt == MH_GAMESYMBOL_OK) + { + Sys_Error("Failed to resolve \"%s\" (module %s)\nEngine buildnum: %d\nCRC64: %016llx\nReason: %s", + symbolName, moduleName, g_dwEngineBuildnum, (unsigned long long)crc64, g_pMetaHookAPI->GetGameSymbolStatusString(status)); + } + else + { + Sys_Error("Failed to resolve \"%s\" (module %s)\nEngine buildnum: %d\nReason: %s", + symbolName, moduleName, g_dwEngineBuildnum, g_pMetaHookAPI->GetGameSymbolStatusString(status)); + } } // The return value is the real-image VA of the gamedata record. static PVOID ResolveGameSymbolOrError(const char* moduleName, const char* symbolName, mh_gamesymbol_kind_t expectedKind) { - PVOID va = NULL; - mh_gamesymbol_status_t st = g_pMetaHookAPI->ResolveGameSymbol(g_EngineDLLInfo.ImageBase, symbolName, expectedKind, &va); + PVOID va = NULL; + mh_gamesymbol_status_t st = g_pMetaHookAPI->ResolveGameSymbol(g_EngineDLLInfo.ImageBase, symbolName, expectedKind, &va); - if (st == MH_GAMESYMBOL_OK) - return va; + if (st == MH_GAMESYMBOL_OK) + return va; - ReportSymbolFailure(moduleName, symbolName, st); - return NULL; + ReportSymbolFailure(moduleName, symbolName, st); + return NULL; } // The call-site set is numbered contiguously from 0; trust the upstream numbering // and stop at the first missing index. Every set is required, so index 0 must exist. static void CollectFSOpenCallSites(const char* symbolPrefix, std::vector& outCallSites) { - for (int index = 0;; ++index) - { - char symbolName[96]; - snprintf(symbolName, sizeof(symbolName), "%s_%d", symbolPrefix, index); + for (int index = 0;; ++index) + { + char symbolName[96]; + snprintf(symbolName, sizeof(symbolName), "%s_%d", symbolPrefix, index); - mh_gamesymbol_status_t st = g_pMetaHookAPI->IsGameSymbolAvailable(g_EngineDLLInfo.ImageBase, symbolName); + mh_gamesymbol_status_t st = g_pMetaHookAPI->IsGameSymbolAvailable(g_EngineDLLInfo.ImageBase, symbolName); - if (st == MH_GAMESYMBOL_SYMBOL_NOT_FOUND) - { - if (index == 0) - ReportSymbolFailure("engine", symbolName, st); + if (st == MH_GAMESYMBOL_SYMBOL_NOT_FOUND) + { + if (index == 0) + ReportSymbolFailure("engine", symbolName, st); - return; - } + return; + } - if (st != MH_GAMESYMBOL_OK) - { - ReportSymbolFailure("engine", symbolName, st); - return; - } + if (st != MH_GAMESYMBOL_OK) + { + ReportSymbolFailure("engine", symbolName, st); + return; + } - PVOID callSiteAddress = ResolveGameSymbolOrError("engine", symbolName, MH_GAMESYMBOL_KIND_PATCH); + PVOID callSiteAddress = ResolveGameSymbolOrError("engine", symbolName, MH_GAMESYMBOL_KIND_PATCH); - if (!callSiteAddress) - return; + if (!callSiteAddress) + return; - outCallSites.push_back({ symbolName, callSiteAddress }); - } + outCallSites.push_back({symbolName, callSiteAddress}); + } } // Only a five-byte E8 rel32 / E9 rel32 is accepted, so a site that other code @@ -93,106 +93,106 @@ static void CollectFSOpenCallSites(const char* symbolPrefix, std::vectorInlinePatchRedirectBranch(callSite.address, newFunc, NULL)) - { - Sys_Error("Failed to redirect \"%s\" at 0x%p", - callSite.symbolName.c_str(), callSite.address); - return false; - } - - return true; + PUCHAR opcode = (PUCHAR)callSite.address; + + if (opcode[0] != 0xE8 && opcode[0] != 0xE9) + { + Sys_Error("\"%s\" at 0x%p is not a five-byte E8/E9 branch (opcode 0x%02X)", + callSite.symbolName.c_str(), callSite.address, opcode[0]); + return false; + } + + if (!g_pMetaHookAPI->InlinePatchRedirectBranch(callSite.address, newFunc, NULL)) + { + Sys_Error("Failed to redirect \"%s\" at 0x%p", + callSite.symbolName.c_str(), callSite.address); + return false; + } + + return true; } qboolean CL_PrecacheResources() { - if (1) - { - std::string name = gEngfuncs.pfnGetLevelName(); + if (1) + { + std::string name = gEngfuncs.pfnGetLevelName(); - RemoveFileExtension(name); + RemoveFileExtension(name); - name += ".gmr"; + name += ".gmr"; - ModelReplacer()->LoadMapReplaceList(name.c_str()); - } + ModelReplacer()->LoadMapReplaceList(name.c_str()); + } - if (1) - { - std::string name = gEngfuncs.pfnGetLevelName(); + if (1) + { + std::string name = gEngfuncs.pfnGetLevelName(); - RemoveFileExtension(name); + RemoveFileExtension(name); - name += ".gsr"; + name += ".gsr"; - SoundReplacer()->LoadMapReplaceList(name.c_str()); - } + SoundReplacer()->LoadMapReplaceList(name.c_str()); + } - return gPrivateFuncs.CL_PrecacheResources(); + return gPrivateFuncs.CL_PrecacheResources(); } FileHandle_t Mod_LoadModel_FS_Open(const char* pFileName, const char* pOptions) { - if (!strcmp(pOptions, "rb")) - { - std::string ReplacedFileName; - if (ModelReplacer()->ReplaceFileName(pFileName, ReplacedFileName)) - { - return gPrivateFuncs.FS_Open(ReplacedFileName.c_str(), pOptions); - } - } - return gPrivateFuncs.FS_Open(pFileName, pOptions); + if (!strcmp(pOptions, "rb")) + { + std::string ReplacedFileName; + if (ModelReplacer()->ReplaceFileName(pFileName, ReplacedFileName)) + { + return gPrivateFuncs.FS_Open(ReplacedFileName.c_str(), pOptions); + } + } + return gPrivateFuncs.FS_Open(pFileName, pOptions); } FileHandle_t S_LoadSound_FS_Open(const char* pFileName, const char* pOptions) { - if (!strcmp(pOptions, "rb")) - { - std::string ReplacedFileName; - if (SoundReplacer()->ReplaceFileName(pFileName, ReplacedFileName)) - { - return gPrivateFuncs.FS_Open(ReplacedFileName.c_str(), pOptions); - } - } - - return gPrivateFuncs.FS_Open(pFileName, pOptions); + if (!strcmp(pOptions, "rb")) + { + std::string ReplacedFileName; + if (SoundReplacer()->ReplaceFileName(pFileName, ReplacedFileName)) + { + return gPrivateFuncs.FS_Open(ReplacedFileName.c_str(), pOptions); + } + } + + return gPrivateFuncs.FS_Open(pFileName, pOptions); } void Engine_FillAddress(void) { - gPrivateFuncs.FS_Open = (decltype(gPrivateFuncs.FS_Open))ResolveGameSymbolOrError("engine", "FS_Open", MH_GAMESYMBOL_KIND_FUNCTION); - gPrivateFuncs.CL_PrecacheResources = (decltype(gPrivateFuncs.CL_PrecacheResources))ResolveGameSymbolOrError("engine", "CL_PrecacheResources", MH_GAMESYMBOL_KIND_FUNCTION); + gPrivateFuncs.FS_Open = (decltype(gPrivateFuncs.FS_Open))ResolveGameSymbolOrError("engine", "FS_Open", MH_GAMESYMBOL_KIND_FUNCTION); + gPrivateFuncs.CL_PrecacheResources = (decltype(gPrivateFuncs.CL_PrecacheResources))ResolveGameSymbolOrError("engine", "CL_PrecacheResources", MH_GAMESYMBOL_KIND_FUNCTION); - CollectFSOpenCallSites("S_LoadSound_to_FS_Open_callsite", g_S_LoadSound_FS_OpenCallSites); - CollectFSOpenCallSites("Mod_LoadModel_to_FS_Open_callsite", g_Mod_LoadModel_FS_OpenCallSites); + CollectFSOpenCallSites("S_LoadSound_to_FS_Open_callsite", g_S_LoadSound_FS_OpenCallSites); + CollectFSOpenCallSites("Mod_LoadModel_to_FS_Open_callsite", g_Mod_LoadModel_FS_OpenCallSites); } void Engine_InstallHooks() { - for (const auto& callSite : g_S_LoadSound_FS_OpenCallSites) - { - if (!RedirectCallSite(callSite, S_LoadSound_FS_Open)) - return; - } - - for (const auto& callSite : g_Mod_LoadModel_FS_OpenCallSites) - { - if (!RedirectCallSite(callSite, Mod_LoadModel_FS_Open)) - return; - } - - Install_InlineHook(CL_PrecacheResources); + for (const auto& callSite : g_S_LoadSound_FS_OpenCallSites) + { + if (!RedirectCallSite(callSite, S_LoadSound_FS_Open)) + return; + } + + for (const auto& callSite : g_Mod_LoadModel_FS_OpenCallSites) + { + if (!RedirectCallSite(callSite, Mod_LoadModel_FS_Open)) + return; + } + + Install_InlineHook(CL_PrecacheResources); } void Engine_UninstallHooks() { - Uninstall_Hook(CL_PrecacheResources); + Uninstall_Hook(CL_PrecacheResources); } diff --git a/src/privatehook.h b/src/privatehook.h index 5aedd10..f83129b 100644 --- a/src/privatehook.h +++ b/src/privatehook.h @@ -4,9 +4,9 @@ typedef struct { - FileHandle_t (*FS_Open)(const char* pFileName, const char* pOptions); - qboolean(*CL_PrecacheResources)(); -}private_funcs_t; + FileHandle_t (*FS_Open)(const char* pFileName, const char* pOptions); + qboolean (*CL_PrecacheResources)(); +} private_funcs_t; void Engine_FillAddress(void); void Engine_InstallHooks(); diff --git a/src/util.cpp b/src/util.cpp index 57ba92b..b366a45 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -2,48 +2,52 @@ std::string TrimString(const std::string& str) { - size_t first = str.find_first_not_of(" \t\n\r\f\v"); - size_t last = str.find_last_not_of(" \t\n\r\f\v"); + size_t first = str.find_first_not_of(" \t\n\r\f\v"); + size_t last = str.find_last_not_of(" \t\n\r\f\v"); - if (first == std::string::npos || last == std::string::npos) - return ""; + if (first == std::string::npos || last == std::string::npos) + return ""; - return str.substr(first, (last - first + 1)); + return str.substr(first, (last - first + 1)); } void RemoveFileExtension(std::string& filePath) { - // Find the last occurrence of '.' - size_t lastDotPosition = filePath.find_last_of("."); - - // Check if the dot is part of a directory component rather than an extension - size_t lastPathSeparator = filePath.find_last_of("/\\"); - - if (lastDotPosition != std::string::npos) { - // Ensure the dot is after the last path separator - if (lastPathSeparator != std::string::npos && lastDotPosition < lastPathSeparator) { - return; // Dot is part of a directory name, not an extension - } - // Return the substring from the beginning to the dot - filePath = filePath.substr(0, lastDotPosition); - } - - // No extension found, return the original path + // Find the last occurrence of '.' + size_t lastDotPosition = filePath.find_last_of("."); + + // Check if the dot is part of a directory component rather than an extension + size_t lastPathSeparator = filePath.find_last_of("/\\"); + + if (lastDotPosition != std::string::npos) + { + // Ensure the dot is after the last path separator + if (lastPathSeparator != std::string::npos && lastDotPosition < lastPathSeparator) + { + return; // Dot is part of a directory name, not an extension + } + // Return the substring from the beginning to the dot + filePath = filePath.substr(0, lastDotPosition); + } + + // No extension found, return the original path } void COM_FixSlashes(char* pname) { #ifdef _WIN32 - while (*pname) { - if (*pname == '/') - *pname = '\\'; - pname++; - } + while (*pname) + { + if (*pname == '/') + *pname = '\\'; + pname++; + } #else - while (*pname) { - if (*pname == '\\') - *pname = '/'; - pname++; - } + while (*pname) + { + if (*pname == '\\') + *pname = '/'; + pname++; + } #endif } \ No newline at end of file diff --git a/src/util.h b/src/util.h index e811c12..e75cef4 100644 --- a/src/util.h +++ b/src/util.h @@ -4,5 +4,5 @@ #include std::string TrimString(const std::string& str); -void RemoveFileExtension(std::string& filePath); -void COM_FixSlashes(char* pname); +void RemoveFileExtension(std::string& filePath); +void COM_FixSlashes(char* pname);