diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 75b1adf0..349668e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,8 @@ jobs: python-version: "3.12" - name: Line endings run: python tools/ci/check_line_endings.py + - name: Vendored model entry order (OptiScaler WrongGPU edition) + run: python tools/ci/check_vendored_model_entries.py - name: Licence (REUSE) run: | $PSNativeCommandUseErrorActionPreference = $true diff --git a/clean/fsr/CMakeLists.txt b/clean/fsr/CMakeLists.txt index 0f5af475..5af83945 100644 --- a/clean/fsr/CMakeLists.txt +++ b/clean/fsr/CMakeLists.txt @@ -132,7 +132,15 @@ add_test(NAME fsr30_hook_${WG_OTHER_K_NAME}_unit COMMAND test_fsr30_${WG_OTHER_K # WrongGPU OptiScaler ASI plugin: thunk logic (any OS) and the offline anchor scan of an OptiScaler binary # (any OS; skips when WRONGGPU_OPTISCALER_BIN is not set). Header-only resolver/thunk, no extra libraries. add_executable(test_asi_thunk tests/test_asi_thunk.cpp) +target_compile_definitions(test_asi_thunk PRIVATE WRONGGPU_MODEL_L=${WG_MODEL_L_VALUE}) add_test(NAME fsr_asi_thunk_unit COMMAND test_asi_thunk) +# The plugin's menu and saved choice with Model L (and Model K), whatever this build's switches: the 0.6.5 shape. +add_executable(test_asi_thunk_kl tests/test_asi_thunk.cpp) +target_compile_definitions(test_asi_thunk_kl PRIVATE WRONGGPU_MODEL_K_OVERRIDE=1 WRONGGPU_MODEL_L=1) +add_test(NAME fsr_asi_thunk_kl_unit COMMAND test_asi_thunk_kl) +# The game's model choice record (src/model_choice_record.h) on real files in the temporary folder. +add_executable(test_model_choice_record tests/test_model_choice_record.cpp) +add_test(NAME fsr_model_choice_record_unit COMMAND test_model_choice_record) add_executable(test_asi_patch tests/test_asi_patch.cpp) add_test(NAME fsr_asi_patch_unit COMMAND test_asi_patch) add_executable(test_asi_lifetime tests/test_asi_lifetime.cpp) @@ -141,7 +149,7 @@ add_executable(test_asi_scan tests/test_asi_scan.cpp) add_test(NAME fsr_asi_scan_unit COMMAND test_asi_scan) set_tests_properties(fsr_asi_scan_unit PROPERTIES SKIP_RETURN_CODE 77) if(MSVC) - set_property(TARGET test_asi_thunk test_asi_scan test_asi_patch test_asi_lifetime PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + set_property(TARGET test_asi_thunk test_asi_thunk_kl test_model_choice_record test_asi_scan test_asi_patch test_asi_lifetime PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() if(WIN32) @@ -166,6 +174,8 @@ if(WIN32) target_link_options(test_fsr30_${WG_OTHER_K_NAME} PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_fsr30 PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_thunk PRIVATE ${WG_STATIC_RUNTIME}) + target_link_options(test_asi_thunk_kl PRIVATE ${WG_STATIC_RUNTIME}) + target_link_options(test_model_choice_record PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_scan PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_patch PRIVATE ${WG_STATIC_RUNTIME}) target_link_options(test_asi_lifetime PRIVATE ${WG_STATIC_RUNTIME}) @@ -280,7 +290,7 @@ if(WIN32) set_target_properties(wronggpu_asi PROPERTIES PREFIX "" OUTPUT_NAME WrongGPU SUFFIX ".asi" MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") target_include_directories(wronggpu_asi PRIVATE src) - target_compile_definitions(wronggpu_asi PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX) + target_compile_definitions(wronggpu_asi PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX WRONGGPU_MODEL_L=${WG_MODEL_L_VALUE}) if(MSVC) target_compile_options(wronggpu_asi PRIVATE /W4 /wd4100 /Zi) target_link_options(wronggpu_asi PRIVATE /DEBUG:FULL /INCREMENTAL:NO) diff --git a/clean/fsr/asi/README.md b/clean/fsr/asi/README.md index 6a511070..a38cfac7 100644 --- a/clean/fsr/asi/README.md +++ b/clean/fsr/asi/README.md @@ -21,6 +21,25 @@ What the front end does with the plugin's entry (`src/frontend.cpp`, `TestAsiPlu whatever the FFX box names; "FSR 3.X(/4)" runs AMD: the AMD version the FFX box names, else AMD's newest listed version. The FFX box's list is the same with and without the plugin (WrongGPU first). +Which model runs (0.6.5, `src/model_choice_record.h`, `TestAsiChoiceRecord`, `tests/test_model_choice_record.cpp`): the +plugin's entry says WrongGPU or AMD; which WrongGPU model is the game's **model choice record**, `model-choice.ini` in the +game's WrongGPU state folder (`wronggpu-setup`, beside `settings.ini`; `clean/wgshared/include/wg_state.h`). It holds +`model=`, `seq=` and `source=` (launcher, ffx or plugin) and is written only for a choice the player made, each time with +the record's seq + 1, so the highest seq is the most recent choice: by the launcher when the player applies a model (Apply, +or `set model=`; always, also the same model again; then OptiScaler's `UpscalerIndex` is set to that model's entry, +for display); by the front end when the WrongGPU edition of OptiScaler reports that the player selected one of WrongGPU's +entries (`WrongGpuHostSelectedV1`, `include/wronggpu_host_event.h`); and by this plugin when the player clicks one of its +model entries. The index OptiScaler stores is never a choice, and wronggpu.ini's model item is the install's default, which +only seeds the record of a game that has none (read under the lock). Every read and write holds the game's state lock (one +named mutex per game folder, from its volume and file identity, shared with every WrongGPU program); writes are atomic. +A click that cannot be saved in time changes nothing: its entry says "not saved, try again" and nothing is kept for later. +When the record cannot be read, is corrupt or busy at a create, the front end runs the last choice it read this session, +else wronggpu.ini's model item, else Model M. Without a record (no launcher state folder) the launcher's Model K / L item +decides, else the plugin's saved entry, else Model M. The front end logs the model and which +choice decided and tells the plugin which model runs (`WrongGpuAsiShowModelV1`), so the menu marks that entry. Model L's +own entry ("WrongGPU Model L") is in the menu of a build with `WG_MODEL_L`; a model the front end was built without runs +as Model M, with a note in the log. + ## How it works 1. OptiScaler loads the plugin and calls its exported `InitializeASI()`. `opti_module.h` finds OptiScaler's module @@ -41,7 +60,8 @@ The FFX box's list is the same with and without the plugin (WrongGPU first). none of OptiScaler's data. 4. WrongGPU's front end (`amd_fidelityfx_dx12.dll`) finds the plugin by module and asks it (`WrongGpuAsiQuery`, `asi_abi.h`) which model is selected. The FFX list always starts with WrongGPU entries followed by AMD entries; - when hooked, the front end creates Model M / Model K / AMD according to the plugin selection. + when hooked, the front end creates Model M / K / L or AMD from the plugin's selection weighed against the launcher's + model choice (the model choice record; see "Which model runs" above). If a required anchor is missing or ambiguous, or a stub cannot be placed, nothing is patched and the plugin reports "not hooked". Call sites are prepared and revalidated before publication. A failed write rolls back sites whose diff --git a/clean/fsr/asi/asi_abi.h b/clean/fsr/asi/asi_abi.h index 157a480f..443b7cef 100644 --- a/clean/fsr/asi/asi_abi.h +++ b/clean/fsr/asi/asi_abi.h @@ -4,6 +4,7 @@ // entry the player selected in OptiScaler's menu. The front end finds the plugin by module (GetModuleHandle of the // plugin file name) and resolves this one export by name, so load order does not matter and neither DLL links the // other. Defined once, shared by the plugin (which exports it) and the front-end bridge (which calls it). +#include #include #define WRONGGPU_ASI_MODULE L"WrongGPU.asi" @@ -12,8 +13,9 @@ // Query result. `hooked` is 1 after the prepared menu call-patch transaction commits; it does not promise // complete menu adaptation. The FFX list still contains WrongGPU and AMD entries. Zero means inactive: the -// front end then behaves as if no plugin were present. `model` is 0 (OptiScaler's own FSR 3.X / AMD), 'M' or 'K'. -// Returns the ABI version (>= 1), or 0 on error. Signature: int WrongGpuAsiQuery(int* hooked, char* model). +// front end then behaves as if no plugin were present. `model` is 0 (OptiScaler's own FSR 3.X / AMD), 'M' or 'K' +// (a saved Model L reads as 'M' here, for an older front end; which WrongGPU model runs is the model choice +// record's, src/model_choice_record.h). Returns the ABI version (>= 1), or 0 on error. Signature: int WrongGpuAsiQuery(int* hooked, char* model). typedef int (*PfnWrongGpuAsiQuery)(int* hooked, char* model); // Additive WrongGPU-owned diagnostic API; this is NOT a host plugin or RR frame ABI. @@ -56,7 +58,7 @@ typedef int (*PfnWrongGpuAsiQuery)(int* hooked, char* model); // Before any host write, the plugin pins its own module until process termination. Pin failure // leaves host call sites untouched. Query-only loads do not pin. Neither query promises host // lifetime, executing-thread atomicity, or safe live unhook/unload. -// Selection is 0 (AMD), 'M', or 'K'; it is NOT evidence of the effective rendering backend. +// Selection is 0 (AMD), 'M', 'K' or 'L' (the saved choice); it is NOT evidence of the effective rendering backend. // Fields are independent observations during initialization/selection changes, not a transactional snapshot. // rr_ready is always zero in this implementation; rr_blockers is a bitmask of the reasons above. typedef struct WrongGpuAsiStatusV1 { @@ -75,3 +77,14 @@ typedef struct WrongGpuAsiStatusV1 { } WrongGpuAsiStatusV1; typedef int (*PfnWrongGpuAsiQueryStatusV1)(WrongGpuAsiStatusV1* status, uint32_t caller_size); + +// The front end tells the plugin where the game's model choice record is (wronggpu-setup\model-choice.ini next to +// its wronggpu.ini; src/model_choice_record.h). A click on one of the plugin's model entries is written there (seq + 1, +// source=plugin). Without this call the plugin uses wronggpu-setup\model-choice.ini in its own data folder. +#define WRONGGPU_ASI_SET_CHOICE_RECORD "WrongGpuAsiSetChoiceRecordV1" +typedef void (*PfnWrongGpuAsiSetChoiceRecordV1)(const wchar_t* path); + +// The front end reports which model it runs (0 AMD, 'M', 'K', 'L'), so the plugin's menu marks that entry; 1 returns +// to marking the saved choice. Display only: nothing is saved. +#define WRONGGPU_ASI_SHOW_MODEL "WrongGpuAsiShowModelV1" +typedef void (*PfnWrongGpuAsiShowModelV1)(char model); diff --git a/clean/fsr/asi/asi_thunk.h b/clean/fsr/asi/asi_thunk.h index 312d5174..2b6710f1 100644 --- a/clean/fsr/asi/asi_thunk.h +++ b/clean/fsr/asi/asi_thunk.h @@ -6,8 +6,10 @@ // // It writes none of OptiScaler's data. When the player clicks a WrongGPU item, the Selectable thunk returns "clicked" // for OptiScaler's own "FSR 3.X" entry, so OptiScaler's unchanged code sets its backend to FSR 3.X (which loads -// WrongGPU's FidelityFX DLL); the plugin only remembers which entry the player chose, and the front end reads that -// back. The WrongGPU labels are plain UI text. +// WrongGPU's FidelityFX DLL). The plugin remembers whether WrongGPU or AMD was chosen (wronggpu-asi.ini); a click on a +// WrongGPU model is also written to the game's model choice record (clean/fsr/src/model_choice_record.h), which decides +// the model with the launcher's and OptiScaler's list's choices. The front end reports the model it runs, so the menu +// marks that one. The WrongGPU labels are plain UI text. #include #include #include @@ -16,21 +18,30 @@ #ifndef WRONGGPU_MODEL_K #define WRONGGPU_MODEL_K 1 #endif +#ifndef WRONGGPU_MODEL_L +#define WRONGGPU_MODEL_L 0 +#endif namespace wgasi { constexpr char kModelAmd = 0; // no WrongGPU model: OptiScaler's own FSR 3.X (AMD) is selected constexpr char kModelM = 'M'; constexpr char kModelK = 'K'; +constexpr char kModelL = 'L'; constexpr char kDefaultModel = kModelM; // WrongGPU is the default entry wherever the plugin hooks +constexpr char kShowSaved = 1; // PluginState::shown: no model reported by the front end, mark the saved one -// The entries the plugin adds in front of OptiScaler's FSR 3.X entry. A build without Model K has one, "WrongGPU". +// The entries the plugin adds in front of OptiScaler's FSR 3.X entry. A build with only Model M has one, "WrongGPU". struct Entry { char model; const char* label; }; -#if WRONGGPU_MODEL_K +#if WRONGGPU_MODEL_K && WRONGGPU_MODEL_L +constexpr Entry kEntries[] = {{kModelM, "WrongGPU Model M"}, {kModelK, "WrongGPU Model K"}, {kModelL, "WrongGPU Model L"}}; +#elif WRONGGPU_MODEL_K constexpr Entry kEntries[] = {{kModelM, "WrongGPU Model M"}, {kModelK, "WrongGPU Model K"}}; +#elif WRONGGPU_MODEL_L +constexpr Entry kEntries[] = {{kModelM, "WrongGPU Model M"}, {kModelL, "WrongGPU Model L"}}; #else constexpr Entry kEntries[] = {{kModelM, "WrongGPU"}}; #endif @@ -42,46 +53,95 @@ inline const char* LabelOf(char model) { return nullptr; } -// Shared plugin state. `hooked` is read by the front end through the exported query; `model` is the player's current -// choice within OptiScaler's FSR 3.X entry. +// Shared plugin state. `hooked` is read by the front end through the exported query; `model` is the player's choice +// within OptiScaler's FSR 3.X entry (0: AMD). `shown` is the model the front end reported as running (kShowSaved until +// it reports one): the menu marks that one, so the model the choice record decided is what the player sees checked. +// `unsaved`: the model of the last click the plugin could not write to the model choice record (0: none). That click +// changed nothing (nothing is kept for later); its entry says "(not saved, try again)", or with `refused` "(not saved: +// the choice record is full, ...)", until the next click. struct PluginState { std::atomic hooked{false}; std::atomic model{kDefaultModel}; + std::atomic shown{kShowSaved}; + std::atomic unsaved{0}; + std::atomic refused{false}; }; +constexpr const char* kUnsavedSuffix = " (not saved, try again)"; +constexpr const char* kRefusedSuffix = " (not saved: the choice record is full, see the plugin's log)"; + +// The label drawn for entry `e`: its name, with the not-saved note when its last click could not be saved. +inline std::string EntryLabel(const Entry& e, const PluginState& st) { + if (st.unsaved.load() != e.model) return e.label; + return std::string(e.label) + (st.refused.load() ? kRefusedSuffix : kUnsavedSuffix); +} + +inline char ShownModel(const PluginState& st) { + const char s = st.shown.load(); + return s == kShowSaved ? st.model.load() : s; +} + inline bool IsFsr3xLabel(const char* label) { return label && (std::strcmp(label, "FSR 3.X") == 0 || std::strcmp(label, "FSR 3.X/4") == 0); } +// The result of saving a model click (SaveFn): saved; not saved (busy, unreadable, a failed write); refused (the +// record's sequence numbers are at their end). +enum class Save { Saved, NotSaved, Refused }; + // The Selectable thunk. `sel` is the real ImGui::Selectable(label, selected, flags, size). For OptiScaler's FSR 3.X // entry it draws the WrongGPU items first, then the original entry, records any click as the selected model, and // returns true (click) to OptiScaler when any of them was clicked so OptiScaler switches to its FSR 3.X backend. -// `selected` (OptiScaler's backend is FSR 3.X) marks the WrongGPU item or the FSR 3.X item, whichever is chosen. -// Every other entry passes through unchanged. -template -bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st) { +// `selected` (OptiScaler's backend is FSR 3.X) marks the item of the model shown (ShownModel). Every other entry passes +// through unchanged. A click on a WrongGPU model is first written to the model choice record (`save(model)`); when that +// fails NOTHING changes (the selection, the mark, OptiScaler: no click is passed on) and the entry says it was not +// saved. *clickedOut (when given) is set to true on a click that took effect (the caller saves the selection). +template +bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st, + SaveFn&& save, bool* clickedOut = nullptr) { + if (clickedOut) *clickedOut = false; if (!IsFsr3xLabel(label)) return sel(label, selected, flags, size); - const char model = st.model.load(); + const char model = ShownModel(st); char clicked = 1; // 1: nothing clicked for (const Entry& e : kEntries) - if (sel(e.label, selected && model == e.model, flags, size) && clicked == 1) clicked = e.model; + if (sel(EntryLabel(e, st).c_str(), selected && model == e.model, flags, size) && clicked == 1) clicked = e.model; if (sel(label, selected && model == kModelAmd, flags, size) && clicked == 1) clicked = kModelAmd; if (clicked == 1) return false; + if (clicked != kModelAmd) { + const Save r = save(clicked); + if (r != Save::Saved) { + st.refused.store(r == Save::Refused); + st.unsaved.store(clicked); + return false; + } + } + st.unsaved.store(0); + st.refused.store(false); st.model.store(clicked); + st.shown.store(kShowSaved); // the player's click is the newest choice: it runs and is marked + if (clickedOut) *clickedOut = true; return true; } -// The BeginCombo thunk: when a WrongGPU model is selected and OptiScaler would show its FSR 3.X name as the closed +// The same without a model choice record to write (every click is saved). +template +bool SelectableThunkLogic(SelFn&& sel, const char* label, bool selected, int flags, const void* size, PluginState& st, + bool* clickedOut = nullptr) { + return SelectableThunkLogic(sel, label, selected, flags, size, st, [](char) { return Save::Saved; }, clickedOut); +} + +// The BeginCombo thunk: when a WrongGPU model is shown and OptiScaler would show its FSR 3.X name as the closed // combo's preview, show the WrongGPU entry's name instead. `bc` is the real ImGui::BeginCombo(label, preview, flags). template bool BeginComboThunkLogic(BcFn&& bc, const char* label, const char* preview, int flags, PluginState& st) { if (IsFsr3xLabel(preview)) - if (const char* own = LabelOf(st.model.load())) preview = own; + if (const char* own = LabelOf(ShownModel(st))) preview = own; return bc(label, preview, flags); } -// The remembered choice (wronggpu-asi.ini next to the plugin): "selection=wronggpu", "wronggpu-k" or "amd". Anything -// else, or no file, is the default (WrongGPU). Model K in a build without it reads as WrongGPU. +// The remembered entry (wronggpu-asi.ini next to the plugin): "selection=wronggpu" (Model M), "wronggpu-k", "wronggpu-l" +// or "amd". Anything else, or no file, is the default (WrongGPU). A model this build lacks reads as WrongGPU (Model M). +// Which WrongGPU model runs is the model choice record's (model_choice_record.h); this file says WrongGPU or AMD. inline char ParseSelection(const std::string& text) { size_t at = 0; while (at < text.size()) { @@ -95,15 +155,42 @@ inline char ParseSelection(const std::string& text) { const std::string v = line.substr(10); if (v == "amd") return kModelAmd; if (v == "wronggpu-k") return LabelOf(kModelK) ? kModelK : kModelM; + if (v == "wronggpu-l") return LabelOf(kModelL) ? kModelL : kModelM; return kDefaultModel; } return kDefaultModel; } +inline const char* SelectionValue(char model) { + return model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : model == kModelL ? "wronggpu-l" : "wronggpu"; +} + inline std::string FormatSelection(char model) { - const char* v = model == kModelAmd ? "amd" : model == kModelK ? "wronggpu-k" : "wronggpu"; return std::string("; WrongGPU OptiScaler plugin: the entry last selected in OptiScaler's upscaler list\r\n") + - "; (wronggpu or amd). Deleting this file selects WrongGPU.\r\nselection=" + v + "\r\n"; + "; (wronggpu, wronggpu-k, wronggpu-l or amd). Deleting this file selects WrongGPU.\r\nselection=" + SelectionValue(model) + "\r\n"; +} + +// `text` with its selection set to `model`, every other byte kept: the line ParseSelection reads (the first one that is +// "selection=..." once spaces are ignored) becomes "selection=" and keeps its own line end; a file without one gets +// the line at its end (with the file's first line end, CRLF when it has none; a last line without a line end gets one). +inline std::string WithSelection(const std::string& text, char model) { + const std::string want = std::string("selection=") + SelectionValue(model); + size_t at = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + const size_t next = end == std::string::npos ? text.size() : end + 1; + if (end == std::string::npos) end = text.size(); + size_t stop = end; + if (stop > at && text[stop - 1] == '\r') --stop; // the line end ("\r\n" or "\n") stays + std::string line; + for (size_t i = at; i < stop; ++i) + if (!std::isspace(static_cast(text[i]))) line += char(std::tolower(static_cast(text[i]))); + if (line.rfind("selection=", 0) == 0) return text.substr(0, at) + want + text.substr(stop); + at = next; + } + const size_t lf = text.find('\n'); + const std::string eol = lf != std::string::npos && lf > 0 && text[lf - 1] == '\r' ? "\r\n" : lf != std::string::npos ? "\n" : "\r\n"; + return text + (text.empty() || text.back() == '\n' ? "" : eol) + want + eol; } } // namespace wgasi diff --git a/clean/fsr/asi/exports_asi.def b/clean/fsr/asi/exports_asi.def index 52127332..fbd2a940 100644 --- a/clean/fsr/asi/exports_asi.def +++ b/clean/fsr/asi/exports_asi.def @@ -4,3 +4,5 @@ EXPORTS InitializeASI WrongGpuAsiQuery WrongGpuAsiQueryStatusV1 + WrongGpuAsiSetChoiceRecordV1 + WrongGpuAsiShowModelV1 diff --git a/clean/fsr/asi/wronggpu_asi.cpp b/clean/fsr/asi/wronggpu_asi.cpp index 9adb88e2..cf6bfe8c 100644 --- a/clean/fsr/asi/wronggpu_asi.cpp +++ b/clean/fsr/asi/wronggpu_asi.cpp @@ -1,8 +1,10 @@ // SPDX-License-Identifier: MIT // WrongGPU.asi: an OptiScaler plugin (its own DLL, our own code only) that makes WrongGPU appear as its own entry -// ("WrongGPU"; with Model K: "WrongGPU Model M", "WrongGPU Model K") in OptiScaler's MAIN DX12 upscaler dropdown, -// leaving OptiScaler's "FSR 3.X(/4)" entry to mean AMD's upscaler again. WrongGPU is the default entry; the player's -// choice is remembered in wronggpu-asi.ini next to the plugin. +// ("WrongGPU"; with Model K and/or L: "WrongGPU Model M", "WrongGPU Model K", "WrongGPU Model L") in OptiScaler's MAIN +// DX12 upscaler dropdown, leaving OptiScaler's "FSR 3.X(/4)" entry to mean AMD's upscaler again. WrongGPU is the default +// entry; WrongGPU or AMD is remembered in wronggpu-asi.ini next to the plugin, and a click on a model entry is written to +// the game's model choice record (src/model_choice_record.h, under its cross-process lock), which decides the model. The front end reports back the +// model it runs. // // How: OptiScaler calls our exported InitializeASI() after loading us (see its LoadAsiPlugins). The module that // called us is OptiScaler itself (its image holds the menu code), so we identify it by InitializeASI's return @@ -29,6 +31,7 @@ #include "asi_patch.h" #include "asi_status.h" #include "asi_thunk.h" +#include "model_choice_record.h" #include "opti_module.h" #include "opti_resolver.h" @@ -70,8 +73,8 @@ std::wstring SelectionPath() { return wgasi::PluginDataDir() + L"wronggpu-asi.in char LoadSelection() { std::string text; - HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (h != INVALID_HANDLE_VALUE) { char buf[512]; DWORD got = 0; @@ -81,23 +84,60 @@ char LoadSelection() { return wgasi::ParseSelection(text); } +// The plugin's own file, replaced atomically (a temporary file next to it, flushed, moved over it). void SaveSelection(char model) { const std::string text = wgasi::FormatSelection(model); - HANDLE h = CreateFileW(SelectionPath().c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) return; - DWORD written = 0; - WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr); - CloseHandle(h); + const std::wstring path = SelectionPath(), tmp = path + L"." + std::to_wstring(GetCurrentProcessId()) + L".tmp"; + HANDLE h = CreateFileW(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + bool ok = false; + if (h != INVALID_HANDLE_VALUE) { + DWORD written = 0; + ok = WriteFile(h, text.data(), DWORD(text.size()), &written, nullptr) && written == text.size() && FlushFileBuffers(h); + CloseHandle(h); + ok = ok && MoveFileExW(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); + if (!ok) DeleteFileW(tmp.c_str()); + } + if (!ok) AsiLog::Get().Write("wronggpu-asi.ini could not be written (Windows error " + std::to_string(GetLastError()) + ")"); +} + +// The game's model choice record (model_choice_record.h): where the front end said it is (WrongGpuAsiSetChoiceRecordV1), +// else wronggpu-setup\model-choice.ini in PluginDataDir() (the game folder in the launcher's layouts). +std::mutex g_recordMutex; +std::wstring g_recordPath; +std::wstring RecordPath() { + std::lock_guard lock(g_recordMutex); + return g_recordPath.empty() ? wgchoice::RecordPathIn(wgasi::PluginDataDir()).wstring() : g_recordPath; +} + +// A click on one of the plugin's model entries: the record gets this model with the next seq (source=plugin), under the +// game's state lock (model_choice_record.h; waited for 1 second at most, on the menu thread). A click that cannot be +// written is NOT kept: nothing changes, the menu says "not saved, try again" (SelectableThunkLogic) and the log says why. +// At the end of the sequence numbers the click is refused, logged and said in the menu. +wgasi::Save RecordModelChoice(char model) { + const std::wstring path = RecordPath(); + wgchoice::Record after; + std::string why; + const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Plugin, &after, &why, nullptr, 1000); + if (o == wgchoice::Outcome::Written) { + AsiLog::Get().Writef("model choice record: Model %c (seq %llu, source=plugin)%s", model, static_cast(after.seq), + why.empty() ? "" : ("; " + why).c_str()); + return wgasi::Save::Saved; + } + AsiLog::Get().Write(std::string("ERROR: model choice record ") + wgasi::Utf8(path) + ": Model " + model + " not saved (" + + wgchoice::OutcomeWords(o) + (why.empty() ? "" : ": " + why) + "); nothing changed" + + (o == wgchoice::Outcome::SeqExhausted ? ". Delete the record or apply the model in the launcher." + : o == wgchoice::Outcome::Corrupt ? "" // (OutcomeWords says to fix or delete the file) + : ", try again")); + return o == wgchoice::Outcome::SeqExhausted || o == wgchoice::Outcome::Corrupt ? wgasi::Save::Refused : wgasi::Save::NotSaved; } extern "C" bool WgSelectableThunk(const char* label, bool selected, int flags, const void* size) { - const char before = g_state.model.load(); + bool ours = false; const bool clicked = wgasi::SelectableThunkLogic( [](const char* l, bool s, int f, const void* z) { return g_realSelectable(l, s, f, z); }, - label, selected, flags, size, g_state); - const char after = g_state.model.load(); - if (after != before) { // a click on another entry of the FSR 3.X group: remember it (rare; on the menu thread) + label, selected, flags, size, g_state, [](char model) { return RecordModelChoice(model); }, &ours); + if (ours) { // a click that took effect on an entry of the FSR 3.X group (rare; on the menu thread) + const char after = g_state.model.load(); SaveSelection(after); AsiLog::Get().Writef("selected: %s", after == wgasi::kModelAmd ? label : wgasi::LabelOf(after)); } @@ -290,12 +330,27 @@ extern "C" __declspec(dllexport) __declspec(noinline) void InitializeASI() { }); } +// The earlier query (ABI 1): an older front end knows 0, 'M' and 'K' only, so Model L reads as Model M there. extern "C" __declspec(dllexport) int WrongGpuAsiQuery(int* hooked, char* model) { if (hooked) *hooked = g_state.hooked.load() ? 1 : 0; - if (model) *model = g_state.model.load(); + if (model) { + const char m = g_state.model.load(); + *model = m == wgasi::kModelL ? wgasi::kModelM : m; + } return int(WRONGGPU_ASI_ABI); } +// The front end tells the plugin where the game's model choice record is (next to its wronggpu.ini). +extern "C" __declspec(dllexport) void WrongGpuAsiSetChoiceRecordV1(const wchar_t* path) { + std::lock_guard lock(g_recordMutex); + g_recordPath = path ? path : L""; +} + +// The front end reports the model it runs (0 AMD, 'M', 'K', 'L'), so the menu marks that one; 1 = the saved choice. +extern "C" __declspec(dllexport) void WrongGpuAsiShowModelV1(char model) { + if (model == wgasi::kShowSaved || model == wgasi::kModelAmd || wgasi::LabelOf(model)) g_state.shown.store(model); +} + extern "C" __declspec(dllexport) int WrongGpuAsiQueryStatusV1(WrongGpuAsiStatusV1* status, uint32_t caller_size) { return g_diagnostics.Query(status, caller_size, g_state.hooked.load(), g_state.model.load()); } diff --git a/clean/fsr/include/wronggpu_host_event.h b/clean/fsr/include/wronggpu_host_event.h new file mode 100644 index 00000000..ab693739 --- /dev/null +++ b/clean/fsr/include/wronggpu_host_event.h @@ -0,0 +1,35 @@ +/* SPDX-License-Identifier: MIT */ +#pragma once +/* The event a host (the WrongGPU edition of OptiScaler) sends WrongGPU's front end (amd_fidelityfx_dx12.dll in the + * custom WrongGPU slot or next to the game) when the PLAYER selects one of the listed upscaler versions in its menu. The + * host resolves this one export by name in the front-end DLL it loaded (GetProcAddress) and calls it with the selected + * entry's version id (from the list the front end returned to FFX_API_QUERY_DESC_TYPE_GET_VERSIONS), BEFORE it recreates + * the upscaler. Only a player's selection is an event: a host never sends one for an index it read from its ini or applied + * at start. The export is an in-process call with no caller check: any code in the game's process could call it, as it + * could write the record itself; the record only ever holds a model choice, and the next create applies it. + * + * A selection of one of WrongGPU's model entries is written to the game's model choice record + * (clean/fsr/src/model_choice_record.h, source=ffx) and decides the model from then on, until a newer choice (the + * launcher's, the WrongGPU menu plugin's, or another selection). An AMD version or a Ray Reconstruction mode entry is no + * model choice. Re-selecting the entry that is already selected is a choice too (it wins over a newer choice made + * elsewhere). + * + * Signature: int32_t WrongGpuHostSelectedV1(uint64_t versionId). Callable from any thread; it takes the game's state lock + * for a few milliseconds (3 s at most when another WrongGPU program holds it). Nothing is ever kept for later: a choice + * that is not saved changes nothing. */ +#include + +#define WRONGGPU_HOST_SELECTED_EXPORT "WrongGpuHostSelectedV1" + +#define WG_HOST_SELECTED_RECORDED 1 /* recorded, and this model runs from now on instead of another: recreate the + upscaler (also when the entry was already selected) */ +#define WG_HOST_SELECTED_NOTHING_CHANGED 0 /* nothing changes in what runs: an AMD version or an RR mode entry, a model + that already ran (recorded again), or a game without a record (no launcher + state folder: the host's entry decides, as before) */ +#define WG_HOST_SELECTED_NOT_SAVED -1 /* not saved (the record busy or unreadable, or a failed write): nothing changes + and nothing is kept; the host says "not saved, try again" and does not + recreate the upscaler */ +#define WG_HOST_SELECTED_REFUSED -2 /* the record's sequence number is at its end: refused (logged); as NOT_SAVED */ +#define WG_HOST_SELECTED_NOT_READY -3 /* the front end is not hosted or not initialised; as NOT_SAVED */ + +typedef int32_t (*PfnWrongGpuHostSelectedV1)(uint64_t versionId); diff --git a/clean/fsr/src/asi_bridge.cpp b/clean/fsr/src/asi_bridge.cpp index 736a533a..84c86eb2 100644 --- a/clean/fsr/src/asi_bridge.cpp +++ b/clean/fsr/src/asi_bridge.cpp @@ -24,4 +24,18 @@ bool QueryAsiPlugin(char* model) { return hooked != 0; } +void ShowAsiModel(char model) { + HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); + if (!m) return; + if (auto show = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_SHOW_MODEL)))) + show(model); +} + +void SetAsiChoiceRecord(const std::wstring& path) { + HMODULE m = GetModuleHandleW(WRONGGPU_ASI_MODULE); + if (!m) return; + if (auto set = reinterpret_cast(reinterpret_cast(GetProcAddress(m, WRONGGPU_ASI_SET_CHOICE_RECORD)))) + set(path.c_str()); +} + } // namespace wgwin diff --git a/clean/fsr/src/asi_bridge.h b/clean/fsr/src/asi_bridge.h index a1e1dbff..739d3312 100644 --- a/clean/fsr/src/asi_bridge.h +++ b/clean/fsr/src/asi_bridge.h @@ -2,10 +2,18 @@ #pragma once // Front-end side of the WrongGPU ASI plugin interface (clean/fsr/asi/asi_abi.h): find WrongGPU.asi if it is loaded // in the process and ask it which upscaler entry the player selected in OptiScaler's menu. No link to the plugin. +#include + namespace wgwin { -// Sets *model to 0 (AMD FSR), 'M' or 'K'. Returns true only when the plugin is present and has hooked the host's -// menu (so the front end should list AMD-only versions and let the plugin choose the model). False otherwise. +// Sets *model to 0 (AMD FSR) or a WrongGPU model ('M', 'K'; which WrongGPU model runs is the model choice record's). +// Returns true only when the plugin is present and has hooked the host's menu. False otherwise. bool QueryAsiPlugin(char* model); +// Tells the plugin which model runs (its menu marks that entry). Nothing happens without the plugin or the export. +void ShowAsiModel(char model); + +// Tells the plugin where the game's model choice record is (src/model_choice_record.h). Nothing without the plugin. +void SetAsiChoiceRecord(const std::wstring& path); + } // namespace wgwin diff --git a/clean/fsr/src/dllmain.cpp b/clean/fsr/src/dllmain.cpp index 5afd77c1..9dcb7790 100644 --- a/clean/fsr/src/dllmain.cpp +++ b/clean/fsr/src/dllmain.cpp @@ -13,6 +13,7 @@ #include #include +#include "../include/wronggpu_host_event.h" #include "ffx_headers.h" #include "frontend.h" #include "version.h" @@ -53,6 +54,18 @@ HMODULE g_self = nullptr; std::once_flag g_initOnce; FrontEnd* g_frontEnd = nullptr; bool g_hosted = false; // loaded under another name by an upscaler mod (OptiScaler) as its FidelityFX upscaler +// wronggpu.ini as it is on disk now (FrontEnd::Platform::readWronggpuIni). A named class, not a lambda that captures the +// path by copy: with MSVC's /Zc:lambda (on with /permissive-, as in CI) a lambda whose capture copy throws terminates the +// process instead of unwinding; the same copy in a class constructor unwinds normally (async_create.h DeviceRelease). +struct WronggpuIniReader { + std::wstring path; + explicit WronggpuIniReader(const std::wstring& p) : path(p) {} + std::string operator()() const { + std::string text; + wgstate::ReadBytes(path, &text); + return text; + } +}; std::once_flag g_originalOnce; OriginalApi g_original; @@ -138,6 +151,48 @@ bool StartTimer(uint32_t ms, std::function fn) { return true; } +// The callables Get() gives the front end that keep a string of the configuration. Named classes, not lambdas that +// capture the string by copy: with MSVC's /Zc:lambda (on with /permissive-, as in CI) a lambda whose capture copy throws +// (std::bad_alloc) terminates the process instead of unwinding; the same copy in a class constructor unwinds normally +// (async_create.h DeviceRelease). +// +// Where the converted model is looked for (config.h ModelPlace): wronggpu.ini [fsr] model_dir, the game's data folder, +// then the runtime's own default. +struct ModelPlacesOf { + std::string modelDir; + explicit ModelPlacesOf(const std::string& d) : modelDir(d) {} + std::vector operator()() const { + std::vector places; + const std::wstring data = Place().dataDir; + if (!modelDir.empty()) { + std::wstring dir = Widen(modelDir); + const bool absolute = dir.size() > 1 && (dir[1] == L':' || (dir[0] == L'\\' && dir[1] == L'\\')); + if (!absolute) dir = data + L"\\" + dir; + places.push_back({Narrow(dir), "wronggpu.ini model_dir", false}); + } + wchar_t exe[MAX_PATH] = {}; + const DWORD n = GetModuleFileNameW(nullptr, exe, MAX_PATH); + std::wstring exeDir(exe, n); + exeDir = exeDir.substr(0, exeDir.find_last_of(L"\\/") == std::wstring::npos ? 0 : exeDir.find_last_of(L"\\/")); + const std::wstring gameData = exeDir + L"\\WrongGPU"; + places.push_back({Narrow(gameData + L"\\model"), "the game's data folder", false}); + if (_wcsicmp(data.c_str(), gameData.c_str()) != 0) places.push_back({Narrow(data + L"\\model"), "the data folder (WG_DATA_DIR)", false}); + wchar_t local[MAX_PATH] = {}; + const DWORD m = GetEnvironmentVariableW(L"LOCALAPPDATA", local, MAX_PATH); + if (m > 0 && m < MAX_PATH) places.push_back({Narrow(std::wstring(local, m) + L"\\WrongGPU\\model"), "%LOCALAPPDATA%", true}); + return places; + } +}; +// AMD's upscaler for fallbacks and the version list: the DLL next to this one, else the comparison DLL. +struct OriginalOrCompare { + std::string dll; + explicit OriginalOrCompare(const std::string& d) : dll(d) {} + const OriginalApi* operator()() const { + if (const OriginalApi* o = LoadOriginal()) return o; + return CompareApi(dll); + } +}; + FrontEnd& Get() { std::call_once(g_initOnce, [] { // Shared settings first (clean/wgshared): data folder, wronggpu.ini, the shared block (this DLL writes it when @@ -189,27 +244,7 @@ FrontEnd& Get() { // Where the converted model is looked for (config.h ModelPlace): wronggpu.ini [fsr] model_dir, the game's data // folder, then the runtime's own default. Files a game reads must be in places the game's process sees: the // installer's %LOCALAPPDATA% copy can be private to another app's container. - p.modelPlaces = [modelDir = config.modelDir] { - std::vector places; - const std::wstring data = Place().dataDir; - if (!modelDir.empty()) { - std::wstring dir = Widen(modelDir); - const bool absolute = dir.size() > 1 && (dir[1] == L':' || (dir[0] == L'\\' && dir[1] == L'\\')); - if (!absolute) dir = data + L"\\" + dir; - places.push_back({Narrow(dir), "wronggpu.ini model_dir", false}); - } - wchar_t exe[MAX_PATH] = {}; - const DWORD n = GetModuleFileNameW(nullptr, exe, MAX_PATH); - std::wstring exeDir(exe, n); - exeDir = exeDir.substr(0, exeDir.find_last_of(L"\\/") == std::wstring::npos ? 0 : exeDir.find_last_of(L"\\/")); - const std::wstring gameData = exeDir + L"\\WrongGPU"; - places.push_back({Narrow(gameData + L"\\model"), "the game's data folder", false}); - if (_wcsicmp(data.c_str(), gameData.c_str()) != 0) places.push_back({Narrow(data + L"\\model"), "the data folder (WG_DATA_DIR)", false}); - wchar_t local[MAX_PATH] = {}; - const DWORD m = GetEnvironmentVariableW(L"LOCALAPPDATA", local, MAX_PATH); - if (m > 0 && m < MAX_PATH) places.push_back({Narrow(std::wstring(local, m) + L"\\WrongGPU\\model"), "%LOCALAPPDATA%", true}); - return places; - }; + p.modelPlaces = ModelPlacesOf(config.modelDir); p.fileExists = [](const std::string& path) { const DWORD a = GetFileAttributesW(Widen(path).c_str()); return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); @@ -231,14 +266,29 @@ FrontEnd& Get() { // host's way in and would route the call back to this DLL (config.h Config::customSlot). p.original = []() -> const OriginalApi* { return LoadOriginal(); }; } else { - p.original = [dll]() -> const OriginalApi* { - if (const OriginalApi* o = LoadOriginal()) return o; - return CompareApi(dll); - }; + p.original = OriginalOrCompare(dll); } - // If WrongGPU.asi has hooked OptiScaler's menu, it (not an FFX version override) chooses the model, and - // WrongGPU's own versions are left out of the FFX sub-box. Absent or not hooked: hosted mode as before. + // If WrongGPU.asi has hooked OptiScaler's menu, its entry says WrongGPU or AMD, and the game's model choice + // record (model_choice_record.h, next to wronggpu.ini) says which WrongGPU model. Absent or not hooked: hosted + // mode as before. p.asiPlugin = [](char* model) { return QueryAsiPlugin(model); }; + p.asiShowModel = [](char model) { ShowAsiModel(model); }; + } + // The game's model choice record (model_choice_record.h, in the game's WrongGPU state folder wronggpu-setup next to + // wronggpu.ini) decides the WrongGPU model on every route; the plugin writes its menu's model clicks there too. + // Always set: without the state folder the front end runs the session's last choice, wronggpu.ini's model item or + // Model M, never the host's stored index (FrontEnd::ChooseModel). + { + const std::wstring ini = Place().ini; + const size_t slash = ini.find_last_of(L"\\/"); + const std::filesystem::path record = + wgchoice::RecordPathIn(slash == std::wstring::npos ? std::wstring(L".") : ini.substr(0, slash)); + p.choiceRecord = record; + p.readWronggpuIni = WronggpuIniReader(ini); // the upgrade migration reads wronggpu.ini's model item under the state lock + if (g_hosted) { + SetAsiChoiceRecord(record.wstring()); + SetHostIniPollModels(false); // the host's stored index is no model choice (the record decides) + } } p.menu = Menu(); g_frontEnd = new FrontEnd(p, config); @@ -289,6 +339,18 @@ FFX_API_ENTRY ffxReturnCode_t ffxDispatch(ffxContext* context, const ffxDispatch return Guard("ffxDispatch", [&] { return Get().Dispatch(context, desc); }); } +// The WrongGPU edition of OptiScaler: the player selected the listed version `versionId` in its upscaler list +// (include/wronggpu_host_event.h). Not hosted or not initialised: WG_HOST_SELECTED_NOT_READY. +__declspec(dllexport) int32_t WrongGpuHostSelectedV1(uint64_t versionId) { + int32_t rc = WG_HOST_SELECTED_NOT_READY; + Guard("WrongGpuHostSelectedV1", [&] { + FrontEnd& fe = Get(); + if (fe.GetConfig().hosted) rc = fe.HostSelected(versionId); + return FFX_API_RETURN_OK; + }); + return rc; +} + } // extern "C" BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) { diff --git a/clean/fsr/src/exports.def b/clean/fsr/src/exports.def index fe3e4936..a1ed40ee 100644 --- a/clean/fsr/src/exports.def +++ b/clean/fsr/src/exports.def @@ -6,3 +6,4 @@ EXPORTS ffxDestroyContext ffxDispatch ffxQuery + WrongGpuHostSelectedV1 diff --git a/clean/fsr/src/frontend.cpp b/clean/fsr/src/frontend.cpp index 0d83165d..79c2df9a 100644 --- a/clean/fsr/src/frontend.cpp +++ b/clean/fsr/src/frontend.cpp @@ -2,12 +2,14 @@ #include "frontend.h" #include +#include #include #include #include #include #include +#include "../include/wronggpu_host_event.h" #include "ffx_describe.h" #include "diagnostics.h" #include "wg_settings_io.h" // pure part: describe() (the registry's log words) @@ -565,28 +567,40 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes } } - // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, its entry decides. - // "WrongGPU" -> WrongGPU, whatever the FFX sub-box names. "FSR 3.X(/4)" -> AMD: the version the FFX sub-box names - // when that is one of AMD's, else AMD's newest listed version (FSR 4 when the AMD provider has it). + // OptiScaler ASI plugin (clean/fsr/asi): when it has hooked the host's MAIN upscaler list, its entry says WrongGPU or + // AMD ("FSR 3.X(/4)"), and the game's model choice record (model_choice_record.h) says which WrongGPU model: the + // launcher, a player's selection in OptiScaler's list (an event the WrongGPU edition of OptiScaler sends, + // HostSelected) and the plugin's own model entries write it, the highest seq is the most recent choice. The entry the + // FFX box stores is never a choice. A WrongGPU model -> WrongGPU, whatever version the FFX box names. AMD -> AMD: the + // version the FFX sub-box names when that is one of AMD's, else AMD's newest listed version (FSR 4 when the AMD + // provider has it). char asiModel = 0; const bool asiHooked = config_.hosted && platform_.asiPlugin && platform_.asiPlugin(&asiModel); bool forceAmd = false; if (asiHooked) { - if (asiModel == 'M' || asiModel == 'K') { -#if WRONGGPU_MODEL_K - const char model = asiModel; -#else - const char model = 'M'; // a plugin built with Model K, with a front end without it: Model M -#endif - u->selectedModel = model; - u->modelProviderId = model == 'K' ? kWrongGpuKProviderVersionId : kWrongGpuProviderVersionId; - u->modelProviderName = model == 'K' ? "WrongGPU Model K" : "WrongGPU Model M"; + std::string why; + char model = asiModel != 0 ? ChooseModel(tag, &why) : 0; + if (asiModel != 0) { + const int32_t m = ModelOfName(std::string(1, model)); + const WgEntryDef* sr = m >= 0 ? SrEntryOfModel(m) : nullptr; + if (!sr) { // a model this build of the front end lacks (CMake WG_MODEL_K / WG_MODEL_L): Model M, said once + LogOnce(tag, std::string("note: model choice: Model ") + model + " is not part of this build of the front end; Model M is used"); + model = 'M'; + sr = SrEntryOfModel(ModelOfName("M")); + } + u->selectedModel = model; // passed on as model= (CreateUpscale, below) + u->modelProviderId = sr ? sr->id : kWrongGpuProviderVersionId; + u->modelProviderName = sr ? EntryProviderName(*sr) : kWrongGpuVersionName; u->hasOverride = false; // an AMD version in the FFX sub-box must not route this context to AMD - Log(tag + " OptiScaler plugin: " + u->modelProviderName + " selected in the host's upscaler list"); + // "selected in the host's upscaler list" (the launcher's log reader looks for it): the plugin's menu marks the + // model that runs (asiShowModel) + Log(tag + " OptiScaler plugin: " + u->modelProviderName + " selected in the host's upscaler list (" + why + ")"); } else { forceAmd = true; + model = 0; Log(tag + " OptiScaler plugin: AMD FSR selected in the host's upscaler list"); } + if (platform_.asiShowModel) platform_.asiShowModel(model); } // One folder per choice (registry option entry_source = folders): this DLL's folder IS the choice; the host's @@ -631,6 +645,7 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes const std::string name = "amd:upscale#" + std::to_string(nextId_++); std::lock_guard lock(mutex_); forwarded_[*context] = Forwarded{name, 0, api, status, true}; + runningModel_.store(0); // AMD's upscaler runs } Log(tag + " -> " + RcName(rc) + " (the host chose AMD's upscaler version " + Hex(chosen) + "; forwarded) context=" + Name(context)); @@ -641,8 +656,31 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes } u->hasOverride = false; // WrongGPU's own id means nothing to AMD's DLL (fallback, comparison) } - // No entry chose the model (direct route, no override, an id WrongGPU did not list): sr_model when it is set in - // the shared block, the environment or wronggpu.ini; otherwise runtime_options / the runtime's default as before. + // No entry named a model (no override, an id WrongGPU did not list, or the direct route): hosted, or with a model choice + // record path (the DLL always sets one), the model choice route (ChooseModel); else (tests of the direct route) sr_model + // when it is set in the shared block, the environment or wronggpu.ini; otherwise runtime_options / the runtime's + // default as before. + if (!forceAmd && !u->selectedModel && !u->modelOption && (config_.hosted || !platform_.choiceRecord.empty())) { + std::string why; + const int32_t model = ModelOfName(std::string(1, ChooseModel(tag, &why))); + if (const WgEntryDef* sr = model >= 0 ? SrEntryOfModel(model) : nullptr) { + u->selectedModel = kWgModelRows[model].name[0]; + u->modelOption = kWgModelRows[model].runtime_option; + u->modelProviderId = sr->id; + u->modelProviderName = EntryProviderName(*sr); + Log(tag + " model choice: Model " + u->selectedModel + " (" + why + ")"); + } else { + // a model this build lacks (CMake WG_MODEL_K / WG_MODEL_L): Model M, as in ApplyEntry; never the configured + // sr_model, which the menu persists and an earlier session may have left on another model + const int32_t mm = ModelOfName("M"); + const WgEntryDef* srM = SrEntryOfModel(mm); + u->selectedModel = 'M'; + u->modelOption = kWgModelRows[mm].runtime_option; + u->modelProviderId = srM->id; + u->modelProviderName = EntryProviderName(*srM); + LogOnce(tag, "note: model choice: that model is not part of this build of the front end; Model M is used"); + } + } if (!forceAmd && !u->selectedModel && !u->modelOption) { int32_t model = -1; std::string described; @@ -894,6 +932,8 @@ ffxReturnCode_t FrontEnd::CreateUpscale(ffxContext* context, ffxCreateContextDes std::lock_guard lock(mutex_); own_[u] = true; } + // the model the active context runs (HostSelected compares a selection with it): none while it runs AMD's upscaler + runningModel_.store(u->mode == UpscaleContext::Mode::Amd && !u->pending ? char(0) : u->selectedModel); *context = u; Log(tag + " -> OK context=" + Name(context) + (u->mode == UpscaleContext::Mode::Amd ? " amd=" + Pointer(u->amd) : "")); return FFX_API_RETURN_OK; @@ -1412,11 +1452,168 @@ bool FrontEnd::ConfiguredModel(int32_t* model, std::string* described) { return true; } +char FrontEnd::LauncherModel() const { + // The last model item of wronggpu.ini's runtime_options (the launcher writes model= there; a build without + // Model K / L has already dropped those items, IgnoreModelK / IgnoreModelL). + bool found = false; + const std::string v = OptionValue(config_.runtimeOptions, "model", &found); + if (!found || v.size() != 1) return 0; + const char m = char(std::toupper(static_cast(v[0]))); + return wgchoice::IsModel(m) ? m : 0; +} + +void FrontEnd::LogOnce(const std::string& tag, const std::string& line) { + { + std::lock_guard lock(mutex_); + if (modelLogged_.count(line)) return; + modelLogged_[line] = true; + } + Log(tag + " " + line); +} + +char FrontEnd::WronggpuIniModel() const { + if (!platform_.readWronggpuIni) return LauncherModel(); + std::string warnings; + const Config c = ParseConfig(platform_.readWronggpuIni(), &warnings); + bool found = false; + const std::string v = OptionValue(c.runtimeOptions, "model", &found); + if (!found || v.size() != 1) return 0; + const char m = char(std::toupper(static_cast(v[0]))); + return wgchoice::IsModel(m) ? m : 0; +} + +char FrontEnd::ChooseModel(const std::string& tag, std::string* why) { + std::lock_guard lock(choiceMutex_); + // the record cannot be used now (no state folder, unreadable, corrupt, busy): the last record this session read or + // wrote, else wronggpu.ini's model item, else Model M; never the host's stored entry + auto fallback = [&](const std::string& reason) { + if (wgchoice::IsModel(lastChoice_)) { + *why = reason + "; the last model choice read this session"; + return lastChoice_; + } + const char ini = LauncherModel(); + *why = ini ? reason + "; wronggpu.ini model=" + ini : reason + "; the default"; + return ini ? ini : 'M'; + }; + const std::filesystem::path& path = platform_.choiceRecord; + DWORD dirErr = 0; + const wgstate::PathState dir = path.empty() ? wgstate::PathState::Missing : wgstate::DirectoryState(path.parent_path().wstring(), &dirErr); + if (dir != wgstate::PathState::Present) { + LogOnce(tag, dir == wgstate::PathState::Missing + ? std::string("model choice: no WrongGPU state folder (wronggpu-setup) for this game: no model choice record") + : "model choice: the WrongGPU state folder (wronggpu-setup) cannot be checked (error " + std::to_string(dirErr) + ")"); + return fallback(dir == wgstate::PathState::Missing ? "no WrongGPU state folder" : "the WrongGPU state folder cannot be checked"); + } + wgchoice::Record rec; + bool migrated = false; + std::string err; + const wgchoice::LoadResult lr = + wgchoice::LoadOrMigrateRecord(path, [this] { return WronggpuIniModel(); }, &rec, &migrated, &err); + switch (lr) { + case wgchoice::LoadResult::Ok: break; + case wgchoice::LoadResult::Corrupt: + LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) is corrupt (" + err + "): not used until the next choice replaces it"); + return fallback("the model choice record is corrupt"); + case wgchoice::LoadResult::Unreadable: + // (never written over: a record held open for a moment must not be replaced by a guess) + LogOnce(tag, "model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (" + err + ")"); + return fallback("the model choice record cannot be read"); + case wgchoice::LoadResult::NoLock: + Log(tag + " model choice: the record was not read (" + err + ")"); + return fallback("the model choice record was busy"); + case wgchoice::LoadResult::Missing: + LogOnce(tag, "ERROR: model choice: no record yet, and it could not be written (" + err + ")"); + return fallback("no model choice record (not written)"); + } + lastChoice_ = rec.model; + if (migrated) + Log(tag + " model choice: no record yet (an install from before 0.6.5): Model " + rec.model + + " from wronggpu.ini's model item (or the default) recorded (seq 1, source=launcher)"); + *why = std::string("the model choice record: ") + wgchoice::SourceWords(rec.source) + ", seq " + std::to_string(rec.seq); + const char launcher = LauncherModel(); + if (launcher && launcher != rec.model) + LogOnce(tag, std::string("model choice: wronggpu.ini's model item (the install's default) says Model ") + launcher + + "; the model choice record says Model " + rec.model + " (" + wgchoice::SourceWords(rec.source) + ", seq " + + std::to_string(rec.seq) + "), which runs"); + return rec.model; +} + +int32_t FrontEnd::HostSelected(uint64_t versionId) { + const std::string tag = "host event:"; + const WgEntryDef* e = OwnEntryOfId(versionId); + if (!e || e->slot != WG_OPT_SR_MODEL || e->value < 0 || e->value >= WG_SR_MODEL_COUNT) { + Log(tag + " the player selected " + (e ? std::string(EntryProviderName(*e)) : "version " + Hex(versionId)) + + " in OptiScaler's upscaler list: no WrongGPU model choice"); + return WG_HOST_SELECTED_NOTHING_CHANGED; + } + const char model = kWgModelRows[e->value].name[0]; + const char running = runningModel_.load(); + const std::filesystem::path& path = platform_.choiceRecord; + DWORD dirErr = 0; + if (path.empty() || wgstate::DirectoryState(path.parent_path().wstring(), &dirErr) != wgstate::PathState::Present) { + // no record to write: not saved, nothing changes (the host's index is never a choice) + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but it was not saved: no WrongGPU " + "state folder (wronggpu-setup) for this game" + (dirErr ? " (error " + std::to_string(dirErr) + ")" : std::string()) + + ". Nothing changes; apply the model in the WrongGPU launcher."); + return WG_HOST_SELECTED_NOT_SAVED; + } + std::lock_guard lock(choiceMutex_); + wgchoice::Record after; + std::string err; + const wgchoice::Outcome o = wgchoice::RecordChoice(path, model, wgchoice::Source::Ffx, &after, &err); + if (o == wgchoice::Outcome::Written) { + lastChoice_ = model; + // 1 when the selected model is not what the active context runs (also when the record changed underneath, a + // launcher Apply while the game is open): the host recreates the upscaler, which then runs the record's model + Log(tag + " the player selected Model " + model + " in OptiScaler's upscaler list: recorded (seq " + std::to_string(after.seq) + + ", source=ffx)" + (err.empty() ? "" : "; " + err) + + (running == model ? "; it already runs" : std::string("; it runs after the upscaler is recreated (now running: ") + + (wgchoice::IsModel(running) ? std::string("Model ") + running : std::string("no WrongGPU model")) + ")")); + return running == model ? WG_HOST_SELECTED_NOTHING_CHANGED : WG_HOST_SELECTED_RECORDED; + } + if (o == wgchoice::Outcome::SeqExhausted) { + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list: " + wgchoice::OutcomeWords(o) + + ". Delete wronggpu-setup\\model-choice.ini or apply the model in the launcher."); + return WG_HOST_SELECTED_REFUSED; + } + if (o == wgchoice::Outcome::Corrupt) { // never replaced: the model that runs stays + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list: " + wgchoice::OutcomeWords(o) + + (err.empty() ? "" : " (" + err + ")") + ". Nothing changes."); + return WG_HOST_SELECTED_REFUSED; + } + Log(tag + " ERROR: the player selected Model " + model + " in OptiScaler's upscaler list, but it was not saved: " + + wgchoice::OutcomeWords(o) + (err.empty() ? "" : " (" + err + ")") + ". Nothing changes; select it again."); + return WG_HOST_SELECTED_NOT_SAVED; +} + void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::string& tag, const char* source) { int32_t model = e.slot == WG_OPT_SR_MODEL ? e.value : -1; std::string described; if (model < 0 && ConfiguredModel(&model, &described)) Log(tag + " settings: " + described + " (the SR context's model)"); + // The entry the host passes at a create is the index its ini stores, never a choice: the model choice record decides + // the SR context's model (ChooseModel: the record, or when it cannot be used the session's last choice, wronggpu.ini's + // model item, Model M; a player's selection in the host's list reaches the record as an event, HostSelected). One + // folder per choice keeps its folder's model. + const WgEntryDef* shown = &e; // the entry written to the shared settings and logged + if (config_.hosted && std::strcmp(source, "folder") != 0) { + std::string why; + const char entry = model >= 0 && model < WG_SR_MODEL_COUNT ? kWgModelRows[model].name[0] : 0; + char chosen = ChooseModel(tag, &why); + int32_t m = ModelOfName(std::string(1, chosen)); + if (m < 0 || !SrEntryOfModel(m)) { + LogOnce(tag, std::string("note: model choice: Model ") + chosen + " is not part of this build of the front end; Model M is used"); + chosen = 'M'; + m = ModelOfName("M"); + } + if (m != model) + Log(tag + " model choice: the host's entry names " + (entry ? std::string("Model ") + entry : std::string("no model")) + + "; Model " + chosen + " runs (" + why + "; an entry the host stores is not a choice)"); + else + Log(tag + " model choice: Model " + chosen + " (" + why + ")"); + model = m; + if (e.slot == WG_OPT_SR_MODEL) shown = SrEntryOfModel(m); + } if (const WgEntryDef* sr = model >= 0 ? SrEntryOfModel(model) : nullptr) { u.selectedModel = kWgModelRows[model].name[0]; u.modelOption = kWgModelRows[model].runtime_option; @@ -1428,9 +1625,9 @@ void FrontEnd::ApplyEntry(const WgEntryDef& e, UpscaleContext& u, const std::str if (OwnEntry(i)->slot == WG_OPT_SR_MODEL && std::strcmp(EntryProviderName(*OwnEntry(i)), u.modelProviderName) == 0) u.modelProviderId = OwnEntry(i)->id; } - const bool written = platform_.menu.set && platform_.menu.set(e.slot, e.value, source); + const bool written = platform_.menu.set && platform_.menu.set(shown->slot, shown->value, source); wg::Source word = std::strcmp(source, "folder") == 0 ? wg::Source::Sidecar : wg::Source::Menu; - Log(tag + " the host chose " + EntryProviderName(e) + " (" + Hex(e.id) + "): settings: " + wg::describe(e.slot, e.value, word) + + Log(tag + " the host chose " + EntryProviderName(e) + " (" + Hex(e.id) + "): settings: " + wg::describe(shown->slot, shown->value, word) + (written ? std::string() : platform_.menu.set ? " (not written: another module writes the shared settings)" : std::string()) + (e.slot == WG_OPT_SR_MODEL ? std::string() : std::string("; the SR context runs ") + u.modelProviderName)); } diff --git a/clean/fsr/src/frontend.h b/clean/fsr/src/frontend.h index 48d587d3..952c9e20 100644 --- a/clean/fsr/src/frontend.h +++ b/clean/fsr/src/frontend.h @@ -16,6 +16,7 @@ #include "amd_compare.h" #include "async_create.h" #include "config.h" +#include "model_choice_record.h" #include "status.h" #include "ffx_headers.h" #include "param_map.h" @@ -94,9 +95,17 @@ struct Platform { std::function releaseDevice; // OptiScaler ASI plugin bridge (clean/fsr/asi): when WrongGPU.asi is loaded and has hooked OptiScaler's menu, // WrongGPU is its own entry in the host's MAIN upscaler list, not a version in the FFX sub-box. Returns true when - // hooked (then the version query lists AMD only and this plugin, not an FFX override, chooses the model) and sets - // *model to 0 (AMD FSR), 'M' or 'K'. Null or returns false: no plugin / unknown host build; hosted mode as before. + // hooked and sets *model to 0 (AMD FSR chosen there) or a WrongGPU model (then the model choice record decides which, + // choiceRecord below). Null or returns false: no plugin / unknown host build; hosted mode as before. std::function asiPlugin; + // Tells the plugin which model the context runs (0 AMD, 'M', 'K', 'L'), so its menu marks that entry. May be empty. + std::function asiShowModel; + // The game's model choice record (model_choice_record.h: wronggpu-setup\model-choice.ini next to wronggpu.ini), read + // and written with real files. Empty: no record (the launcher's model item decides, as before). + std::filesystem::path choiceRecord; + // wronggpu.ini's text as it is on disk now (the record's upgrade migration reads its model item while it holds the + // game's state lock). Empty: the model item of the configuration read at start. + std::function readWronggpuIni; // Registry options and the menu's choices (shared settings block). Empty members: defaults, nothing written. MenuSettings menu; }; @@ -161,6 +170,13 @@ class FrontEnd { size_t OwnContextCount(); // for tests bool HasParked(); // for tests + // The host tells the front end that the PLAYER selected the listed version `versionId` in its upscaler list (the + // WrongGPU edition of OptiScaler calls the exported WrongGpuHostSelectedV1, before it would recreate the upscaler). + // One of WrongGPU's SR model entries is a model choice: written to the model choice record (source=ffx). Returns + // WG_HOST_SELECTED_* (include/wronggpu_host_event.h): 1 this model runs from now on (recreate), 0 nothing changed, + // negative not saved (nothing changes, the host says "not saved, try again"). + int32_t HostSelected(uint64_t versionId); + struct UpscaleContext; private: @@ -208,6 +224,18 @@ class FrontEnd { // The configured SR model (sr_model: block > environment > ini) for a context no entry chose; false: not set // anywhere (the model then comes from runtime_options / the runtime's default, as before the registry). bool ConfiguredModel(int32_t* model, std::string* described); + // The model the launcher's wronggpu.ini names (the last model item of runtime_options: 'M', 'K', 'L'), else 0. + char LauncherModel() const; + // The WrongGPU model a create runs: the model choice record's (model_choice_record.h; a game without one gets one from + // wronggpu.ini's model item, read under the game's state lock, else Model M: LoadOrMigrateRecord). When the record + // cannot be used (no state folder or one that cannot be checked, unreadable, corrupt, its lock not taken in time): the + // last record this session read or wrote (lastChoice_), else wronggpu.ini's model item, else Model M. NEVER the host's + // stored entry, NEVER the plugin's saved entry. *why: which choice decided, for the log. + char ChooseModel(const std::string& tag, std::string* why); + // wronggpu.ini's model item as it is on disk now (readWronggpuIni), else as read at start ('M', 'K', 'L' or 0). + char WronggpuIniModel() const; + // `line` logged once per session (after `tag`). + void LogOnce(const std::string& tag, const std::string& line); // AMD's DLL behind a forwarded context (the one that created it), else AMD's original. const OriginalApi* ApiOf(void* context); // `u` runs on AMD while its upscaler's create runs (u.pending): takes the upscaler over when the create has finished. @@ -270,6 +298,9 @@ class FrontEnd { uint32_t inputRefusedRun_ = 0; // refusals in a row with that key (mutex_) std::atomic inputRefusedAny_{false}; // inputRefusedRun_ > 0 (the taken-frame path's cheap check) std::map modelLogged_; // ApplyModelDir: each distinct choice logged once (mutex_) + std::mutex choiceMutex_; // ChooseModel / HostSelected: lastChoice_ + char lastChoice_ = 0; // the model of the last record read or written this session + std::atomic runningModel_{0}; // the model the last created context runs (0: none / AMD's upscaler) std::atomic reentered_{0}; // calls refused because they re-entered this front end on one thread std::mutex parkMutex_; // guards the three below; held while a parked context is destroyed UpscaleContext* parked_ = nullptr; diff --git a/clean/fsr/src/model_choice_record.h b/clean/fsr/src/model_choice_record.h new file mode 100644 index 00000000..a3ad5ed4 --- /dev/null +++ b/clean/fsr/src/model_choice_record.h @@ -0,0 +1,307 @@ +// SPDX-License-Identifier: MIT +#pragma once +// The model choice record (0.6.5): ONE small file per game, model-choice.ini in the game's WrongGPU state folder +// (clean/wgshared/include/wg_state.h: \wronggpu-setup, beside settings.ini; always WrongGPU's: an uninstall +// removes it, a repair, update or reinstall keeps it; without that folder there is no record). It decides which WrongGPU +// model runs, on every route; wronggpu.ini's model item is the install's default, which no WrongGPU program rewrites +// after the install and which only seeds the record of a game that has none (the upgrade below). Three places write the +// record, each only for an EVENT, a choice the player made: +// - the launcher, when the player applies a model (the launcher's Apply, or `WrongGPU.exe set model=`: always, +// also the same model again); it then sets OptiScaler's UpscalerIndex to that model's entry, for display only (and it +// seeds the record of a game without one from its profile); +// - the front end, when OptiScaler tells it that the player selected one of WrongGPU's entries in its upscaler list +// (the WrongGPU edition of OptiScaler calls WrongGpuHostSelectedV1 in the front-end DLL); the stored index OptiScaler +// passes at a create is never taken for a choice; +// - the WrongGPU menu plugin (clean/fsr/asi), when the player clicks one of its model entries. +// "Most recent" is the highest sequence number. Every read-modify-write (read, seq + 1, write) runs under the game's +// state lock (wgstate::StateLock, one named mutex per game folder, shared by every WrongGPU program and by settings.ini's +// writers), so no update is lost and seq never goes back. No clock is involved. +// +// The file, strictly (anything else is CORRUPT: logged and treated as "no choice", never as a partial one): +// ; comment lines and blank lines +// model= +// seq=<1..18446744073709551615> (decimal digits only, overflow refused) +// source= +// each key exactly once, no other key, no spaces around '='; the last line is WrongGPU's stamp (a comment, +// wg_state.h Stamped) when the file is WrongGPU's and unedited and the install has an id. Writes: in place through +// wgstate::UpdateStateFile (only the three keys' lines change; a corrupt record is never replaced; an edited or +// player-made record stays the player's, unstamped; RecordChoiceUnlocked), a temporary file in the same +// folder, written and flushed, then MoveFileExW(REPLACE_EXISTING | WRITE_THROUGH), every step checked), tried up to 3 +// times. Readers take the lock too, so a reader never sees part of a record. A temporary file a crash left behind is +// never read. +// +// Upgrade: a game without a record gets one from the launcher's existing choice (wronggpu.ini's model item, else Model M): +// seq 1, source=launcher, read and written under the lock (LoadOrMigrateRecord). The model is never taken from OptiScaler's +// stored index. A choice that cannot be saved (the lock not taken in time, an unreadable record, a failed write) is not +// kept for later: its writer says "not saved, try again" and the model that runs does not change. +#include +#include +#include +#include + +#include "../../wgshared/include/wg_state.h" // the state folder, its lock, atomic writes (shared with settings.ini) + +namespace wgchoice { + +constexpr const wchar_t* kStateFolder = wgstate::kStateFolder; // wronggpu-setup +constexpr const wchar_t* kRecordFile = wgstate::kModelChoiceFile; +// The record of the game whose WrongGPU files (wronggpu.ini, the state folder) are in `gameDir`. +inline std::filesystem::path RecordPathIn(const std::filesystem::path& gameDir) { return gameDir / kStateFolder / kRecordFile; } +// The game folder of a record (the folder holding its state folder): the game's state lock is taken on it. +inline std::filesystem::path GameDirOf(const std::filesystem::path& record) { return record.parent_path().parent_path(); } + +enum class Source { Launcher, Ffx, Plugin }; + +struct Record { + char model = 'M'; // 'M', 'K', 'L' + uint64_t seq = 0; // >= 1 in a valid record + Source source = Source::Launcher; +}; + +inline const char* SourceName(Source s) { return s == Source::Launcher ? "launcher" : s == Source::Ffx ? "ffx" : "plugin"; } +inline const char* SourceWords(Source s) { + return s == Source::Launcher ? "the launcher" : s == Source::Ffx ? "OptiScaler's upscaler list" : "the WrongGPU menu plugin"; +} +inline bool IsModel(char c) { return c == 'M' || c == 'K' || c == 'L'; } + +// Decimal digits only, 1..20 of them, no overflow, not zero. +inline bool ParseSeq(const std::string& v, uint64_t* out) { + if (v.empty() || v.size() > 20) return false; + uint64_t n = 0; + for (char c : v) { + if (c < '0' || c > '9') return false; + const uint64_t d = uint64_t(c - '0'); + if (n > (UINT64_MAX - d) / 10) return false; // n * 10 + d would overflow + n = n * 10 + d; + } + if (n == 0) return false; + *out = n; + return true; +} + +// false (with *why) for anything but one valid record. +inline bool ParseRecord(const std::string& text, Record* out, std::string* why) { + Record r; + bool hasModel = false, hasSeq = false, hasSource = false; + auto fail = [&](const std::string& w) { + if (why) *why = w; + return false; + }; + size_t at = 0; + int lineNo = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + std::string line = text.substr(at, end - at); + at = end + 1; + ++lineNo; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty() || line[0] == ';' || line[0] == '#') continue; + const size_t eq = line.find('='); + if (eq == std::string::npos) return fail("line " + std::to_string(lineNo) + " is not key=value"); + const std::string k = line.substr(0, eq), v = line.substr(eq + 1); + if (k == "model") { + if (hasModel) return fail("model given twice"); + if (v.size() != 1 || !IsModel(v[0])) return fail("model is not M, K or L"); + r.model = v[0]; + hasModel = true; + } else if (k == "seq") { + if (hasSeq) return fail("seq given twice"); + if (!ParseSeq(v, &r.seq)) return fail("seq is not a number from 1 to 18446744073709551615"); + hasSeq = true; + } else if (k == "source") { + if (hasSource) return fail("source given twice"); + if (v == "launcher") r.source = Source::Launcher; + else if (v == "ffx") r.source = Source::Ffx; + else if (v == "plugin") r.source = Source::Plugin; + else return fail("source is not launcher, ffx or plugin"); + hasSource = true; + } else { + return fail("unknown key \"" + k + "\""); + } + } + if (!hasModel || !hasSeq || !hasSource) return fail("model, seq and source are all needed"); + *out = r; + return true; +} + +// The comment a new record starts with. +constexpr const char* kRecordHeader = + "; WrongGPU: the model chosen last for this game, by the launcher, OptiScaler's upscaler list (ffx) or the\r\n" + "; WrongGPU menu plugin. The highest seq is the most recent choice. Written by WrongGPU; do not edit.\r\n"; + +inline std::string FormatRecord(const Record& r) { + return std::string(kRecordHeader) + "model=" + r.model + "\r\nseq=" + std::to_string(r.seq) + "\r\nsource=" + SourceName(r.source) + "\r\n"; +} + +// ---- the lock ------------------------------------------------------------------------------------------------------- + +// Holds the game's state lock (wgstate::StateLock on the record's game folder) for its lifetime. ok(): taken within +// `timeoutMs`. An abandoned lock (a holder that died) is taken over: the files are whole either way (atomic replacement). +class Lock { +public: + explicit Lock(const std::filesystem::path& record, unsigned timeoutMs = 3000) : lock_(GameDirOf(record).wstring(), timeoutMs) {} + bool ok() const { return lock_.held(); } + Lock(const Lock&) = delete; + Lock& operator=(const Lock&) = delete; + +private: + wgstate::StateLock lock_; +}; + +// ---- files ---------------------------------------------------------------------------------------------------------- + +enum class ReadResult { Missing, Ok, Corrupt, Unreadable }; + +// Reads the record (call it under the record's Lock). +inline ReadResult ReadRecordFile(const std::filesystem::path& path, Record* out, std::string* why) { + std::string text; + HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD e = GetLastError(); + if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) return ReadResult::Missing; + if (why) *why = "cannot open (Windows error " + std::to_string(e) + ")"; + return ReadResult::Unreadable; + } + char buf[2048]; + DWORD got = 0; + const BOOL ok = ReadFile(h, buf, sizeof buf, &got, nullptr); + CloseHandle(h); + if (!ok) { + if (why) *why = "cannot read"; + return ReadResult::Unreadable; + } + if (got == sizeof buf) { + if (why) *why = "larger than a record"; + return ReadResult::Corrupt; + } + text.assign(buf, got); + return ParseRecord(text, out, why) ? ReadResult::Ok : ReadResult::Corrupt; +} + +// ---- the operations, each one read-modify-write under the lock ------------------------------------------------------ + +enum class Outcome { Written, NoLock, Unreadable, SeqExhausted, WriteFailed, Corrupt }; + +inline const char* OutcomeWords(Outcome o) { + switch (o) { + case Outcome::Written: return "written"; + case Outcome::NoLock: return "the game's state lock could not be taken in time"; + case Outcome::Unreadable: return "the record cannot be read (not written over)"; + case Outcome::SeqExhausted: return "the record's sequence number is at its end (18446744073709551615): choice refused"; + case Outcome::WriteFailed: return "the record could not be written"; + case Outcome::Corrupt: + return "the record (wronggpu-setup\\model-choice.ini) is not a valid record, so it is left as it is and the choice is " + "refused (fix the file or delete it)"; + } + return "?"; +} + +// A choice of `model` by `source`: the record's model, seq + 1 (seq 1 without a record) and source, written IN PLACE through +// wgstate::UpdateStateFile (#224's rule for the game's state files): the file is held from the read to the replace, only +// the three keys' lines change, every other line (the player's comments, blank lines) and every line end stay, and the +// stamp is put back only when the file was WrongGPU's and unedited (its valid stamp) or new; an edited or player-made +// record stays unstamped, the player's, and an uninstall keeps it. A record that is not a valid record (corrupt, or text +// WrongGPU cannot keep) is never replaced: Corrupt (*why says what is wrong), and the caller keeps the model that runs. +// *after: the record written; *before: the record it replaced (model 0 when there was none). Any failure leaves the file +// as it was and nothing is kept for later: the caller says "not saved". A failed write is tried up to 3 times. Call it +// holding the game's state lock (RecordChoice takes it; the lock is recursive on one thread). +inline Outcome RecordChoiceUnlocked(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, + Record* before = nullptr) { + if (before) *before = Record{0, 0, Source::Launcher}; + Outcome result = Outcome::Written; + Record next{model, 1, source}; + std::string err; + wgstate::SetOutcome o; + for (int attempt = 0; attempt < 3; ++attempt) { + result = Outcome::Written; + err.clear(); + o = wgstate::UpdateStateFile( + GameDirOf(path).wstring(), kRecordFile, + [&](const wgstate::Settings& now, std::vector>* changes) { + Record cur; + bool had = false; + if (now.present) { // (the strict record rules on the file as read, its valid stamp already off) + if (!ParseRecord(wgstate::RenderSettings(now), &cur, &err)) { result = Outcome::Corrupt; return; } + had = true; + if (before) *before = cur; + if (cur.seq == UINT64_MAX) { result = Outcome::SeqExhausted; return; } + } + next = Record{model, had ? cur.seq + 1 : 1, source}; + changes->push_back({"model", std::string(1, model)}); + changes->push_back({"seq", std::to_string(next.seq)}); + changes->push_back({"source", SourceName(source)}); + }, + 1000, kRecordHeader); + const bool writeFailed = o.result == wgstate::SetResult::WriteFailed || (o.result == wgstate::SetResult::AccessDenied && o.write.error); + if (!writeFailed || result != Outcome::Written) break; + Sleep(20); + } + switch (o.result) { + case wgstate::SetResult::Ok: + if (result != Outcome::Written) { + if (why && !err.empty()) *why = err; + return result; + } + if (after) *after = next; + return Outcome::Written; + case wgstate::SetResult::Unparseable: + if (why) *why = o.why; + return Outcome::Corrupt; + case wgstate::SetResult::Busy: + case wgstate::SetResult::LockDenied: + if (why) *why = o.words(); + return Outcome::NoLock; + case wgstate::SetResult::AccessDenied: + if (why) *why = o.words(); + return o.write.error ? Outcome::WriteFailed : Outcome::Unreadable; // (denied at the replace: a write that failed) + case wgstate::SetResult::Unreadable: + case wgstate::SetResult::NoStateFolder: + case wgstate::SetResult::StateFolderUnknown: + if (why) *why = o.words(); + return Outcome::Unreadable; + default: + if (why) *why = o.words(); + return Outcome::WriteFailed; + } +} + +inline Outcome RecordChoice(const std::filesystem::path& path, char model, Source source, Record* after, std::string* why, + Record* before = nullptr, unsigned lockMs = 3000) { + Lock lock(path, lockMs); + if (!lock.ok()) return Outcome::NoLock; + return RecordChoiceUnlocked(path, model, source, after, why, before); +} + +// The record as it is now, read under the game's state lock. A game without one (an install from before 0.6.5) gets one +// from the launcher's existing choice, read WHILE the lock is held (`launcherModel()`: wronggpu.ini's model item, 'M' / +// 'K' / 'L', or 0 for none: Model M), seq 1, source=launcher; so a launcher apply, which holds the same lock, is either +// wholly before or wholly after it. Returns Ok (also after the migration; *out set, *migrated true then), Corrupt or +// Unreadable (*why; nothing written), Missing when the migration's write failed (*why), or NoLock (the lock was not +// taken in `lockMs`; *why). +enum class LoadResult { Ok, Corrupt, Unreadable, Missing, NoLock }; +template +inline LoadResult LoadOrMigrateRecord(const std::filesystem::path& path, LauncherModelFn&& launcherModel, Record* out, bool* migrated, + std::string* why, unsigned lockMs = 3000) { + if (migrated) *migrated = false; + Lock lock(path, lockMs); + if (!lock.ok()) { + if (why) *why = OutcomeWords(Outcome::NoLock); + return LoadResult::NoLock; + } + const ReadResult rr = ReadRecordFile(path, out, why); + if (rr == ReadResult::Ok) return LoadResult::Ok; + if (rr == ReadResult::Corrupt) return LoadResult::Corrupt; + if (rr == ReadResult::Unreadable) return LoadResult::Unreadable; + const char m = launcherModel(); + Record first; + const Outcome wo = RecordChoiceUnlocked(path, IsModel(m) ? m : 'M', Source::Launcher, &first, why); + if (wo == Outcome::Corrupt) return LoadResult::Corrupt; // (a file that appeared meanwhile is the player's: left as it is) + if (wo != Outcome::Written) return LoadResult::Missing; + *out = first; + if (migrated) *migrated = true; + return LoadResult::Ok; +} + +} // namespace wgchoice diff --git a/clean/fsr/src/settings_bridge.cpp b/clean/fsr/src/settings_bridge.cpp index 2dce4b3b..8d6dff16 100644 --- a/clean/fsr/src/settings_bridge.cpp +++ b/clean/fsr/src/settings_bridge.cpp @@ -6,6 +6,7 @@ #define WG_SETTINGS_IO_IMPLEMENTATION #include "wg_settings_io.h" +#include #include #include "settings_bridge.h" @@ -180,6 +181,9 @@ wgfsr::MenuSettings Menu() { return m; } +std::atomic g_pollModels{true}; +void SetHostIniPollModels(bool apply) { g_pollModels.store(apply); } + bool HostIniPollActive() { State& s = S(); return s.initialised && s.poll.configured() && s.block.is_writer(); @@ -198,6 +202,11 @@ bool PollHostIni() { " is not one of WrongGPU's entries (one of AMD's versions); nothing to apply"); return true; } + if (e->slot == WG_OPT_SR_MODEL && !g_pollModels.load()) { + L().WriteLine("settings: " + N(s.poll.path()) + " [" + s.poll.section() + "] UpscalerIndex=" + std::to_string(index) + " = " + + wgfsr::EntryProviderName(*e) + ": not applied (a stored index is no model choice; the model choice record decides)"); + return true; + } L().WriteLine("settings: " + N(s.poll.path()) + " [" + s.poll.section() + "] UpscalerIndex=" + std::to_string(index) + " = " + wgfsr::EntryProviderName(*e)); WriteChoice(e->slot, e->value, "optiscaler.ini"); diff --git a/clean/fsr/src/settings_bridge.h b/clean/fsr/src/settings_bridge.h index dc812bfc..12058270 100644 --- a/clean/fsr/src/settings_bridge.h +++ b/clean/fsr/src/settings_bridge.h @@ -46,6 +46,9 @@ int32_t Setting(uint32_t slot, std::string* described = nullptr, bool* isDefault // The OptiScaler.ini [] UpscalerIndex poll (mtime at most once per second); applies a changed index as if it // had been chosen in the menu (writer only). True while there is something to poll (custom slot and writer). bool PollHostIni(); +// false: the poll leaves WrongGPU's SR model entries alone (a launcher install: the model choice record decides the +// model, and the index the host's ini stores is no choice); RR mode entries are applied as before. Default true. +void SetHostIniPollModels(bool apply); bool HostIniPollActive(); // For tests and logs. diff --git a/clean/fsr/src/win_util.h b/clean/fsr/src/win_util.h index 7f5f64fa..d7d42cea 100644 --- a/clean/fsr/src/win_util.h +++ b/clean/fsr/src/win_util.h @@ -71,6 +71,13 @@ const WgUpscalerBackend* StandInForFallback(const wgfsr::Config& config); // and checked (CheckProviderModule). Logs the choice, or "FSR 4 / AMD versions not available: ..." when none is usable // (null then). const wgfsr::OriginalApi* CompareApi(const std::string& path); +// CompareApi of a path kept by copy: a named class, not a lambda capturing the string (MSVC /Zc:lambda: a throwing capture +// copy terminates instead of unwinding; async_create.h DeviceRelease). +struct CompareApiOf { + std::string path; + explicit CompareApiOf(const std::string& p) : path(p) {} + const wgfsr::OriginalApi* operator()() const { return CompareApi(path); } +}; // Whether `m`, got from LoadLibrary of `requested`, is that AMD FidelityFX API DLL: not WrongGPU's own module or a copy // of it, the file that was asked for (a host's LoadLibrary hook can hand out OptiScaler's or WrongGPU's module for an // AMD file name), the FidelityFX API exports, none of which jumps into a module that is not AMD's (a host's hook). @@ -105,7 +112,7 @@ void AddSplitServices(PlatformT& p, const wgfsr::Config& config) { }; p.gpuTimer = &OverlayGpuTimer; p.compareAmd = &OverlayCompareAmd; - p.compareApi = [dll = config.compareDll] { return CompareApi(dll); }; + p.compareApi = CompareApiOf(config.compareDll); // (a named class: no lambda copies the path, as in dllmain.cpp) p.services = &SplitServices; p.noteDispatch = &NoteDispatch; p.standIn = &StandInForFallback; diff --git a/clean/fsr/tests/test_asi_status.cpp b/clean/fsr/tests/test_asi_status.cpp index 7bdc000a..58453618 100644 --- a/clean/fsr/tests/test_asi_status.cpp +++ b/clean/fsr/tests/test_asi_status.cpp @@ -117,6 +117,21 @@ int main(int argc, char** argv) { CHECK(s.selected_model == 'M' && s.rr_ready == 0); } } + // 0.6.5: the front end's report of the model that runs (display only) and of where the game's model choice record is + // (the plugin writes its menu's model clicks there). Neither is saved, neither hooks anything. + auto show = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_SHOW_MODEL)); + auto setRecord = reinterpret_cast(GetProcAddress(module, WRONGGPU_ASI_SET_CHOICE_RECORD)); + CHECK(show != nullptr && setRecord != nullptr); + if (show && setRecord && legacy) { + show('L'); + show('Z'); // not an entry: ignored + show(1); + setRecord(L"X:\\nowhere\\wronggpu-setup\\model-choice.ini"); + setRecord(nullptr); + int hooked = -1; char model = '?'; + CHECK(legacy(&hooked, &model) == 1 && hooked == 0 && model == 'M'); // the saved entry is unchanged + } + CHECK(GetProcAddress(module, "WrongGpuAsiPendingChoiceV1") == nullptr); // no queued choice exists any more CHECK(FreeLibrary(module) != 0); // No initialization or patches ever occurred. CHECK(GetModuleHandleA(argv[1]) == nullptr); // Query-only loading did not permanently pin it. } diff --git a/clean/fsr/tests/test_asi_thunk.cpp b/clean/fsr/tests/test_asi_thunk.cpp index fdf5551f..2cb6ff97 100644 --- a/clean/fsr/tests/test_asi_thunk.cpp +++ b/clean/fsr/tests/test_asi_thunk.cpp @@ -6,6 +6,10 @@ #include #include +#ifdef WRONGGPU_MODEL_K_OVERRIDE // test_asi_thunk_kl: Model K on, whatever the build's WG_MODEL_K says +#undef WRONGGPU_MODEL_K +#define WRONGGPU_MODEL_K 1 +#endif #include "../asi/asi_thunk.h" using namespace wgasi; @@ -63,8 +67,13 @@ void TestDefaultIsWrongGpu() { CHECK(sel.calls.size() == kEntryCount + 1); CHECK(sel.calls[0].label == kEntries[0].label && sel.calls[0].selected); CHECK(sel.calls.back().label == "FSR 3.X" && !sel.calls.back().selected); -#if WRONGGPU_MODEL_K +#if WRONGGPU_MODEL_K && WRONGGPU_MODEL_L + CHECK(kEntryCount == 3 && sel.calls[0].label == "WrongGPU Model M" && sel.calls[1].label == "WrongGPU Model K" && + sel.calls[2].label == "WrongGPU Model L"); +#elif WRONGGPU_MODEL_K CHECK(kEntryCount == 2 && sel.calls[0].label == "WrongGPU Model M" && sel.calls[1].label == "WrongGPU Model K"); +#elif WRONGGPU_MODEL_L + CHECK(kEntryCount == 2 && sel.calls[0].label == "WrongGPU Model M" && sel.calls[1].label == "WrongGPU Model L"); #else CHECK(kEntryCount == 1 && sel.calls[0].label == "WrongGPU"); #endif @@ -150,6 +159,99 @@ void TestSelectionFile() { CHECK(ParseSelection(FormatSelection(kModelAmd)) == kModelAmd); CHECK(ParseSelection(FormatSelection(kModelM)) == kModelM); CHECK(FormatSelection(kModelM).find("selection=wronggpu\r\n") != std::string::npos); + CHECK(ParseSelection("selection=wronggpu-l") == (WRONGGPU_MODEL_L ? kModelL : kModelM)); + // WithSelection: only the selection line ParseSelection reads changes; every other byte stays (the player's comments, + // a later selection line ParseSelection never reads, line ends, a last line without one) + const std::string mine = "# my notes: AMD for screenshots\r\n\r\n Selection = AMD \r\n; keep\nselection=wronggpu-k\n# end"; + CHECK(WithSelection(mine, kModelM) == "# my notes: AMD for screenshots\r\n\r\nselection=wronggpu\r\n; keep\nselection=wronggpu-k\n# end"); + CHECK(ParseSelection(WithSelection(mine, kModelM)) == kModelM); + CHECK(WithSelection("selection=amd", kModelM) == "selection=wronggpu"); // no line end: none added + CHECK(WithSelection("; only a comment\n", kModelM) == "; only a comment\nselection=wronggpu\n"); // none there: appended + CHECK(WithSelection("; no line end", kModelAmd) == "; no line end\r\nselection=amd\r\n"); + CHECK(WithSelection("", kModelM) == "selection=wronggpu\r\n"); + CHECK(WithSelection(FormatSelection(kModelAmd), kModelM) == FormatSelection(kModelM)); // WrongGPU's own file +} + +// A click records the model and reports it; the menu marks the model the front end reported (ShownModel) until the +// next click. (The click's entry in the game's model choice record is the live plugin's: wronggpu_asi.cpp.) +void TestClickAndShownModel() { + PluginState st; + FakeSelectable none; + bool clicked = true; + const int size = 0; + SelectableThunkLogic(none, "FSR 3.X", true, 0, &size, st, &clicked); + CHECK(!clicked && st.model.load() == kModelM); // drawing alone records nothing + // the front end reports that another model runs (the model choice record decided) + st.shown.store(kEntries[kEntryCount - 1].model); + FakeSelectable marks; + SelectableThunkLogic(marks, "FSR 3.X", true, 0, &size, st); + for (size_t i = 0; i < kEntryCount; ++i) CHECK(marks.calls[i].selected == (i == kEntryCount - 1)); + FakeBeginCombo bc; + BeginComboThunkLogic(bc, "", "FSR 3.X", 0, st); + CHECK(bc.preview == kEntries[kEntryCount - 1].label); + // the player clicks the first entry: recorded, marked again + FakeSelectable click; + click.clickLabel = kEntries[0].label; + CHECK(SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, &clicked)); + CHECK(clicked && st.model.load() == kModelM && st.shown.load() == kShowSaved && ShownModel(st) == kModelM); +#if WRONGGPU_MODEL_L + FakeSelectable l; + l.clickLabel = "WrongGPU Model L"; + CHECK(SelectableThunkLogic(l, "FSR 3.X", true, 0, &size, st, &clicked) && clicked && st.model.load() == kModelL); + CHECK(ParseSelection(FormatSelection(kModelL)) == kModelL); +#endif +#if WRONGGPU_MODEL_K + FakeSelectable k; + k.clickLabel = "WrongGPU Model K"; + CHECK(SelectableThunkLogic(k, "FSR 3.X", true, 0, &size, st, &clicked) && clicked && st.model.load() == kModelK); +#endif +} + +// A model click the plugin cannot write to the model choice record (the lock not taken in time, a failed write, the end of +// the sequence numbers): NOTHING changes (the selection, the mark, no click passed on to OptiScaler, nothing kept for +// later) and the entry says "(not saved, try again)" ("not saved: the choice record is full" when refused) until a click +// that is saved. The AMD entry never writes the record. +void TestUnsavedClick() { + PluginState st; + const int size = 0; + const Entry& first = kEntries[0]; + const Entry& last = kEntries[kEntryCount - 1]; + st.model.store(first.model); + st.shown.store(first.model); // the front end runs the first model + int saves = 0; + auto fail = [&](char) { ++saves; return Save::NotSaved; }; + FakeSelectable click; + click.clickLabel = last.label; + bool clicked = true; + CHECK(!SelectableThunkLogic(click, "FSR 3.X", true, 0, &size, st, fail, &clicked) && !clicked && saves == 1); + CHECK(st.model.load() == first.model && st.shown.load() == first.model && st.unsaved.load() == last.model); + FakeSelectable draw; + SelectableThunkLogic(draw, "FSR 3.X", true, 0, &size, st, fail); + CHECK(draw.calls.size() == kEntryCount + 1 && draw.calls[kEntryCount - 1].label == std::string(last.label) + kUnsavedSuffix); + CHECK(draw.calls[0].selected == true || kEntryCount == 1); // the model that runs stays marked + for (size_t i = 0; i + 1 < kEntryCount; ++i) CHECK(draw.calls[i].label == kEntries[i].label); + // refused (the end of the sequence numbers): said so + auto refuse = [&](char) { return Save::Refused; }; + FakeSelectable click2; + click2.clickLabel = std::string(last.label) + kUnsavedSuffix; + CHECK(!SelectableThunkLogic(click2, "FSR 3.X", true, 0, &size, st, refuse, &clicked) && st.model.load() == first.model); + FakeSelectable draw2; + SelectableThunkLogic(draw2, "FSR 3.X", true, 0, &size, st, refuse); + CHECK(draw2.calls[kEntryCount - 1].label == std::string(last.label) + kRefusedSuffix); + // the AMD entry: no record write, takes effect + int amdSaves = 0; + FakeSelectable amd; + amd.clickLabel = "FSR 3.X"; + CHECK(SelectableThunkLogic(amd, "FSR 3.X", true, 0, &size, st, [&](char) { ++amdSaves; return Save::NotSaved; }, &clicked) && + clicked && amdSaves == 0 && st.model.load() == kModelAmd && st.unsaved.load() == 0); + // a click that is saved: takes effect, the note goes + FakeSelectable ok; + ok.clickLabel = last.label; + CHECK(SelectableThunkLogic(ok, "FSR 3.X", true, 0, &size, st, [](char) { return Save::Saved; }, &clicked) && clicked && + st.model.load() == last.model && st.unsaved.load() == 0); + FakeSelectable plain; + SelectableThunkLogic(plain, "FSR 3.X", true, 0, &size, st); + CHECK(plain.calls[kEntryCount - 1].label == last.label); } } // namespace @@ -163,6 +265,8 @@ int main() { TestClickAmd(); TestPreviewRelabel(); TestSelectionFile(); + TestClickAndShownModel(); + TestUnsavedClick(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/clean/fsr/tests/test_frontend.cpp b/clean/fsr/tests/test_frontend.cpp index 64bee896..f15b109f 100644 --- a/clean/fsr/tests/test_frontend.cpp +++ b/clean/fsr/tests/test_frontend.cpp @@ -7,6 +7,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -19,6 +22,8 @@ #include #include +#include "../include/wronggpu_host_event.h" +#include "../../wgshared/include/wg_model_entries.h" #include "../src/config.h" #include "../src/ffx_describe.h" #include "../src/frontend.h" @@ -250,6 +255,9 @@ static std::vector> g_timed; // Platform::gpuTimer static bool g_asiPresent = false; // the plugin bridge is wired at all static bool g_asiHooked = false; // and it reports a successful hook static char g_asiModel = 0; // 0 (AMD), 'M', 'K' +static std::vector g_asiShown; // Platform::asiShowModel calls +static std::filesystem::path g_choiceRecord; // Platform::choiceRecord (a real file; empty: none) +static std::string g_iniOnDisk; // Platform::readWronggpuIni (empty: not wired); not cleared by Reset // Fake shared settings (Platform::menu, settings_bridge.h in the DLL): values set "somewhere" (block / env / ini), // the writes of the menu's choices, whether this module is the writer, the folder sidecar's entry. @@ -296,6 +304,9 @@ static std::unique_ptr MakeFrontEnd(const Config& config) { } if (g_asiPresent) p.asiPlugin = [](char* model) { if (model) *model = g_asiModel; return g_asiHooked; }; + if (g_asiPresent) p.asiShowModel = [](char model) { g_asiShown.push_back(model); }; + if (!g_iniOnDisk.empty()) p.readWronggpuIni = [] { return g_iniOnDisk; }; + p.choiceRecord = g_choiceRecord; p.compareApi = []() -> const OriginalApi* { return g_compareApi; }; p.backend = [](const Config&, std::string&) -> const WgUpscalerBackend* { return g_useBackend; }; p.services = [](const WgUpscalerBackend* b, void* device) -> const WgFrontEndServices* { @@ -394,6 +405,7 @@ static void Reset() { g_asiPresent = false; g_asiHooked = false; g_asiModel = 0; + g_asiShown.clear(); g_createInfo = WgCreateInfo{}; g_compare = false; g_statuses.clear(); @@ -2294,12 +2306,15 @@ static void TestRuntimeProviderName() { g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; Config c; c.hosted = true; - // Deliberately configure the opposite default: the in-game choice must win. - c.runtimeOptions = std::string("model=") + (model[0] == 'M' ? "K" : "M"); + // The host's stored entry deliberately names ANOTHER model: it is no choice (0.6.5 #213); the model choice route + // decides (no state folder here: wronggpu.ini's model item). + c.runtimeOptions = std::string("model=") + model; auto f = MakeFrontEnd(c); UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); - create.version.versionId = model[0] == 'K' ? kWrongGpuKProviderVersionId - : model[0] == 'L' ? kWrongGpuLProviderVersionId : kWrongGpuProviderVersionId; + create.version.versionId = model[0] == 'M' ? (WRONGGPU_MODEL_L ? kWrongGpuLProviderVersionId : WRONGGPU_MODEL_K ? kWrongGpuKProviderVersionId + : kWrongGpuProviderVersionId) + : kWrongGpuProviderVersionId; + const uint64_t modelId = model[0] == 'K' ? kWrongGpuKProviderVersionId : model[0] == 'L' ? kWrongGpuLProviderVersionId : kWrongGpuProviderVersionId; ffxContext ctx = nullptr; CHECK(f->CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK); auto frame = MakeDispatch(); @@ -2309,7 +2324,7 @@ static void TestRuntimeProviderName() { CHECK(f->Query(&ctx, &q.header) == FFX_API_RETURN_OK); const std::string expected = std::string("WrongGPU Model ") + model; CHECK(q.versionName && expected == q.versionName); - CHECK(q.versionId == create.version.versionId); + CHECK(q.versionId == modelId); CHECK(std::string(g_createInfo.options).rfind(std::string("model=") + model) == std::string(g_createInfo.options).size() - 7); CHECK(!g_statuses.empty() && g_statuses.back().upscaler.find(expected) != std::string::npos); // After a frame failure, version queries must report the actual AMD fallback. @@ -2666,17 +2681,18 @@ static void TestHostVersionHandling() { CHECK(std::strcmp(names[0], "WrongGPU Model M##3.1.0") == 0); CHECK(WRONGGPU_MODEL_K == 0 || std::strcmp(names[1], "WrongGPU Model K##3.1.0") == 0); CHECK(WRONGGPU_MODEL_L == 0 || std::strcmp(names[kOwn - 1], "WrongGPU Model L##3.1.0") == 0); - // The selection still works by id, and a context's own provider name stays the label alone (the last SR model). + // A context's own provider name stays the label alone. The host's stored entry (the last SR model) is no choice: with no + // record and no model item, Model M runs. const uint64_t lastModel = WRONGGPU_MODEL_L ? kWrongGpuLProviderVersionId : WRONGGPU_MODEL_K ? kWrongGpuKProviderVersionId : kWrongGpuProviderVersionId; - const char* const lastName = WRONGGPU_MODEL_L ? "WrongGPU Model L" : WRONGGPU_MODEL_K ? "WrongGPU Model K" : "WrongGPU Model M"; + const char* const lastName = "WrongGPU Model M"; UpscaleCreate own(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, /*withOverride=*/true); own.version.versionId = lastModel; ffxContext ctx = nullptr; CHECK(fe->CreateContext(&ctx, &own.upscale.header, kMemCb) == FFX_API_RETURN_OK && fe->OwnContextCount() == 1); ffxQueryGetProviderVersion provider{}; provider.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; - CHECK(fe->Query(&ctx, &provider.header) == FFX_API_RETURN_OK && provider.versionId == lastModel && provider.versionName && + CHECK(fe->Query(&ctx, &provider.header) == FFX_API_RETURN_OK && provider.versionId == kWrongGpuProviderVersionId && provider.versionName && std::strcmp(provider.versionName, lastName) == 0); CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); @@ -2889,12 +2905,10 @@ static void TestAsiPluginHooked() { ownRun(kWrongGpuProviderVersionId, "WrongGPU Model M", kWrongGpuProviderVersionId); ownRun(g_versionIds[0], "WrongGPU Model M", kWrongGpuProviderVersionId); ownRun(0, "WrongGPU Model M", kWrongGpuProviderVersionId); + // The plugin's saved WrongGPU model is no model choice (0.6.5 #213: the model choice record decides; none here, no model + // item: Model M). g_asiModel = 'K'; -#if WRONGGPU_MODEL_K - ownRun(kWrongGpuProviderVersionId, "WrongGPU Model K", kWrongGpuKProviderVersionId); -#else - ownRun(kWrongGpuProviderVersionId, "WrongGPU Model M", kWrongGpuProviderVersionId); // no Model K in this build -#endif + ownRun(kWrongGpuProviderVersionId, "WrongGPU Model M", kWrongGpuProviderVersionId); // The host's FSR 3.X(/4) entry: AMD upscales. g_asiModel = 0; @@ -2953,8 +2967,9 @@ static void TestAsiPluginNotHooked() { // The installer's Preset K with the plugin hooked (0.5.0): wronggpu.ini says runtime_options = model=K, OptiScaler.ini // UpscalerIndex=1, and the installer seeds the plugin's wronggpu-asi.ini with selection=wronggpu-k, so the plugin -// reports 'K' and the context runs Model K. The plugin's entry decides over the ini: without that seed its default -// entry (Model M) would run, and a later choice of Model M in OptiScaler's list runs Model M. +// reports 'K' and the context runs Model K. Since 0.6.5 the game's model choice record decides (TestAsiChoiceRecord); +// without one, the launcher's K item decides over the plugin's saved entry (the 0.6.5 audit: the plugin's default hid the +// launcher's choice), so both cases run Model K here. static void TestAsiPluginPresetK() { #if WRONGGPU_MODEL_K const bool present = g_asiPresent, hooked = g_asiHooked; @@ -2980,11 +2995,12 @@ static void TestAsiPluginPresetK() { ffxQueryGetProviderVersion q{}; q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; CHECK(fe->Query(&ctx, &q.header) == FFX_API_RETURN_OK); - const std::string expected = std::string("WrongGPU Model ") + plugin; + const char runs = 'K'; // (no record: the launcher's K item) + const std::string expected = std::string("WrongGPU Model ") + runs; CHECK(q.versionName && expected == q.versionName); - CHECK(q.versionId == (plugin == 'K' ? kWrongGpuKProviderVersionId : kWrongGpuProviderVersionId)); + CHECK(q.versionId == kWrongGpuKProviderVersionId); const std::string options = g_createInfo.options ? g_createInfo.options : ""; - CHECK(options.size() >= 7 && options.compare(options.size() - 7, 7, std::string("model=") + plugin) == 0); + CHECK(options.size() >= 7 && options.compare(options.size() - 7, 7, std::string("model=") + runs) == 0); CHECK(CountLog((std::string("OptiScaler plugin: ") + expected + " selected").c_str()) == 1); CHECK(fe->DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); } @@ -2994,6 +3010,323 @@ static void TestAsiPluginPresetK() { #endif } +// 0.6.5 (#213): the game's model choice record (model_choice_record.h) decides the WrongGPU model of a create, on REAL +// files in a fresh folder under the temporary folder, through the front end: the upgrade migration (wronggpu.ini's model +// item as it is on disk, read under the state lock; never the stored index); the index OptiScaler stores is never a +// choice (hooked route, custom slot, and when the record fails); a player's selection in OptiScaler's list arrives as an +// event (HostSelected): 1 when the model that runs changes (also re-selecting the same entry after a plugin choice), 0 +// when it does not, negative when it is not saved (busy, failed write, end of seq), which changes nothing; each source +// winning in turn; AMD; corrupt and unreadable records (the last choice of the session, else wronggpu.ini's item); the +// direct route; a game without a record. Plus the audit's case without any record (the launcher's model item). +struct RecordFolder { + std::filesystem::path dir; + RecordFolder() { + dir = std::filesystem::temp_directory_path() / "wg-frontend-choice-test"; + std::error_code ec; + std::filesystem::create_directories(dir / wgchoice::kStateFolder, ec); + std::filesystem::remove(record(), ec); + } + std::filesystem::path record() const { return wgchoice::RecordPathIn(dir); } + ~RecordFolder() { + std::error_code ec; + for (auto& e : std::filesystem::directory_iterator(dir / wgchoice::kStateFolder, ec)) std::filesystem::remove(e.path(), ec); + std::filesystem::remove(dir / wgchoice::kStateFolder, ec); + std::filesystem::remove(dir, ec); + } +}; + +static wgchoice::Record ReadRec(const std::filesystem::path& p, wgchoice::ReadResult* rr = nullptr) { + wgchoice::Record r; + std::string why; + const wgchoice::ReadResult res = wgchoice::ReadRecordFile(p, &r, &why); + if (rr) *rr = res; + if (res != wgchoice::ReadResult::Ok) r = wgchoice::Record{0, 0, wgchoice::Source::Launcher}; + return r; +} + +static void WriteRec(const std::filesystem::path& p, const std::string& text) { + std::ofstream o(p, std::ios::binary | std::ios::trunc); + o << text; +} + +// A front end for hosted creates: hooked (the plugin hooked, its entry `plugin`: 0 AMD or a WrongGPU model) or not (the +// custom slot / FFX route without the plugin). hosted false: the direct route. +static std::unique_ptr ChoiceFrontEnd(const char* ini, char plugin, bool hooked, bool hosted = true) { + Reset(); + g_resources[kOutput] = {dxgi::R16G16B16A16_FLOAT, 2560, 1440}; + std::string warnings; + Config c = ParseConfig(ini, &warnings); + CHECK(warnings.empty()); + c.hosted = hosted; + c.upscaler = UpscalerChoice::Network; + c.contextParkMs = 0; + g_asiPresent = hooked; + g_asiHooked = hooked; + g_asiModel = plugin; + return MakeFrontEnd(c); +} + +// One create on `fe`, the host's list naming `overrideId` (0: none); the provider the context runs ("" for AMD). +static std::string ChoiceCreate(FrontEnd& fe, uint64_t overrideId) { + const size_t amd = g_amd.size(); + UpscaleCreate create(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, overrideId != 0); + create.version.versionId = overrideId; + ffxContext ctx = nullptr; + CHECK(fe.CreateContext(&ctx, &create.upscale.header, kMemCb) == FFX_API_RETURN_OK && ctx); + std::string provider; + if (g_amd.size() == amd) { + ffxQueryGetProviderVersion q{}; + q.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION; + if (fe.Query(&ctx, &q.header) == FFX_API_RETURN_OK && q.versionName) provider = q.versionName; + } + CHECK(fe.DestroyContext(&ctx, kMemCb) == FFX_API_RETURN_OK); + return provider; +} + +static std::string HostedCreate(const char* ini, char plugin, uint64_t overrideId, bool hooked = true, + const std::function& before = {}) { + auto fe = ChoiceFrontEnd(ini, plugin, hooked); + if (before) before(*fe); + return ChoiceCreate(*fe, overrideId); +} + +static void TestAsiChoiceRecord() { + const bool present = g_asiPresent, hooked = g_asiHooked; + const char saved = g_asiModel; + const bool hasL = ModelOfName("L") >= 0, hasK = ModelOfName("K") >= 0; + auto idOf = [](char m) { return SrEntryOfModel(ModelOfName(std::string(1, m)))->id; }; + auto name = [](char m) { return std::string("WrongGPU Model ") + m; }; + auto lines = [](const std::string& s) { return CountLog(s.c_str()); }; + // A second model to choose (L, else K); a build with neither checks the record with Model M only (below). + const char b = hasL ? 'L' : hasK ? 'K' : 0; + const char c3 = hasL && hasK ? 'K' : 0; // a third model, in a build with both + RecordFolder f; + const std::filesystem::path& rec = f.record(); + std::string why; + // No state folder (a hand install, or one that cannot be found): the record route all the same: the session's last + // choice, else wronggpu.ini's model item (the audit's case: L / K over the plugin's saved default entry, Model M), else + // Model M; NEVER the host's entry (the box names M, on the hooked route and on the custom slot). A selection there is + // not saved (-1) and changes nothing. + if (b) { + const std::string ini = std::string("runtime_options = model=") + b + "\n"; + CHECK(HostedCreate(ini.c_str(), 'M', kWrongGpuProviderVersionId) == name(b)); + CHECK(CountLog("model choice: no WrongGPU state folder (wronggpu-setup) for this game") == 1); + CHECK(CountLog((std::string("(no WrongGPU state folder; wronggpu.ini model=") + b + ")").c_str()) == 1); + CHECK(HostedCreate(ini.c_str(), 0, idOf('M'), false) == name(b)); // the custom slot: the stored M is no choice + int32_t rc = 9; + CHECK(HostedCreate(ini.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); + CHECK(rc == WG_HOST_SELECTED_NOT_SAVED); + CHECK(CountLog("but it was not saved: no WrongGPU state folder (wronggpu-setup) for this game") == 1); + CHECK(HostedCreate("runtime_options = timing_log=1\n", 'M', idOf(b), false) == name('M')); // no model item: Model M + } + g_choiceRecord = rec; + if (b) { + const std::string iniB = std::string("runtime_options = model=") + b + "\n"; + const char* iniM = "runtime_options = model=M\n"; + // (1) upgrade: no record; wronggpu.ini ON DISK says b (the configuration read at start said M), OptiScaler's box + // names Model M: the record is migrated from the file as it is now (b, seq 1, source=launcher), never from the box + g_iniOnDisk = iniB; + CHECK(HostedCreate(iniM, 'M', idOf('M')) == name(b)); + g_iniOnDisk.clear(); + wgchoice::Record r = ReadRec(rec); + CHECK(r.model == b && r.seq == 1 && r.source == wgchoice::Source::Launcher); + CHECK(lines(std::string("model choice: no record yet (an install from before 0.6.5): Model ") + b) == 1); + CHECK(lines("selected in the host's upscaler list (the model choice record: the launcher, seq 1)") == 1); + // (2) the stored index is never a choice: the box names M at every create, the record stays b, seq 1 + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + CHECK(ReadRec(rec).seq == 1 && g_asiShown.size() == 1 && g_asiShown[0] == b); + // (3) the player selects Model M in OptiScaler's list: recorded (seq 2, source=ffx), 1 (M runs now instead of b) + int32_t rc = 9; + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + r = ReadRec(rec); + CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == 'M' && r.seq == 2 && r.source == wgchoice::Source::Ffx); + CHECK(lines("the player selected Model M in OptiScaler's upscaler list: recorded (seq 2, source=ffx)") == 1); + CHECK(lines(std::string("model choice: wronggpu.ini's model item (the install's default) says Model ") + b) == 1); + // (4) the player clicks b in the plugin's menu (the plugin writes seq 3, source=plugin); the box still names M: b runs + wgchoice::Record after; + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Plugin, &after, &why) == wgchoice::Outcome::Written); + CHECK(HostedCreate(iniB.c_str(), b, idOf('M')) == name(b)); + // (5) the player selects the SAME entry (M) again after the plugin's choice: it wins (seq 4) and returns 1, so the + // host recreates the upscaler although its index did not change + { + auto fe = ChoiceFrontEnd(iniB.c_str(), b, true); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // the session runs b + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_RECORDED); + CHECK(ChoiceCreate(*fe, idOf('M')) == name('M')); + // ... and once more: recorded again (seq 5), but nothing changes in what runs: 0 + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOTHING_CHANGED); + r = ReadRec(rec); + CHECK(r.model == 'M' && r.seq == 5 && r.source == wgchoice::Source::Ffx); + } + // (5b) the record changed underneath (a launcher Apply while the game is open): the session runs b, the launcher + // records M, the player selects M (the box already shows it): 1, so the host recreates, and M runs + { + wgchoice::Record after0; + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after0, &why) == wgchoice::Outcome::Written); + auto fe = ChoiceFrontEnd(iniB.c_str(), 0, false); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // runs b (the box names M) + CHECK(wgchoice::RecordChoice(rec, 'M', wgchoice::Source::Launcher, &after0, &why) == wgchoice::Outcome::Written); + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_RECORDED); + CHECK(CountLog((std::string("it runs after the upscaler is recreated (now running: Model ") + b + ")").c_str()) == 1); + CHECK(ChoiceCreate(*fe, idOf('M')) == name('M')); + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOTHING_CHANGED); // M runs now: nothing to recreate + } + // (6) the launcher applies b: b runs + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M')) == name(b)); + // (7) a third model selected in the list (a build with K and L) + if (c3) { + CHECK(HostedCreate(iniM, b, idOf(b), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf(c3)); }) == name(c3)); + CHECK(rc == WG_HOST_SELECTED_RECORDED && ReadRec(rec).model == c3 && ReadRec(rec).source == wgchoice::Source::Ffx); + } + // (8) an AMD version selected in the list is no model choice (0); the plugin's AMD entry runs AMD; record untouched + const uint64_t s0 = ReadRec(rec).seq; + CHECK(HostedCreate(iniM, 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(g_versionIds[0]); }) != ""); + CHECK(rc == WG_HOST_SELECTED_NOTHING_CHANGED && ReadRec(rec).seq == s0); + CHECK(HostedCreate(iniM, 0, idOf('M')).empty()); + CHECK(ReadRec(rec).seq == s0 && CountLog("OptiScaler plugin: AMD FSR selected in the host's upscaler list") == 1); + // (9) the custom slot / FFX route without the plugin: the host's entry names M, the record says b: b runs + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + CHECK(HostedCreate(iniM, 0, idOf('M'), false) == name(b)); + CHECK(lines(std::string("model choice: the host's entry names Model M; Model ") + b + " runs") == 1); + // ... and a selection event there is recorded and runs + CHECK(HostedCreate(iniM, 0, idOf(b), false, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name('M')); + CHECK(rc == WG_HOST_SELECTED_RECORDED && ReadRec(rec).model == 'M'); + // (10) the direct route (not hosted, no entry): the record's model too + CHECK(wgchoice::RecordChoice(rec, b, wgchoice::Source::Launcher, &after, &why) == wgchoice::Outcome::Written); + { + auto fe = ChoiceFrontEnd(iniM, 0, false, /*hosted=*/false); + CHECK(ChoiceCreate(*fe, 0) == name(b)); + } +#ifdef _WIN32 + // (11) the game's state lock held by another WrongGPU program for longer than the event waits: the selection is + // NOT saved (-1), nothing changes and nothing is kept; a create meanwhile runs the session's last choice (b), never + // the host's entry (M) + { + auto fe = ChoiceFrontEnd(iniM, 0, false); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // the session read b + const std::string kept = [&] { std::ifstream i(rec, std::ios::binary); return std::string(std::istreambuf_iterator(i), {}); }(); + std::atomic held{false}, release{false}; + std::thread holder([&] { + wgstate::StateLock l(f.dir.wstring()); + held.store(l.held()); + while (!release.load()) Sleep(1); + }); + while (!held.load()) Sleep(1); + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOT_SAVED); + CHECK(CountLog("but it was not saved: the game's state lock could not be taken in time") == 1); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); + CHECK(CountLog("the model choice record was busy; the last model choice read this session") == 1); + release.store(true); + holder.join(); + const std::string now = [&] { std::ifstream i(rec, std::ios::binary); return std::string(std::istreambuf_iterator(i), {}); }(); + CHECK(now == kept); + CHECK(ChoiceCreate(*fe, idOf('M')) == name(b)); // still b: the unsaved selection was not kept for later + } + // (12) a selection whose write fails (the record held open without delete sharing): not saved, nothing changes + { + auto fe = ChoiceFrontEnd(iniM, 0, false); + HANDLE hold = CreateFileW(rec.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(hold != INVALID_HANDLE_VALUE); + const uint64_t s1 = ReadRec(rec).seq; + CHECK(fe->HostSelected(idOf('M')) == WG_HOST_SELECTED_NOT_SAVED); + CloseHandle(hold); + CHECK(ReadRec(rec).seq == s1 && ChoiceCreate(*fe, idOf('M')) == name(b)); + } + // (13) a record another program holds open without sharing: not read, NEVER written over. A fresh session uses + // wronggpu.ini's item (b), never the host's entry (M or the third model) + HANDLE hold = CreateFileW(rec.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(hold != INVALID_HANDLE_VALUE); + CHECK(HostedCreate(iniB.c_str(), 0, idOf('M'), false) == name(b)); + CHECK(CountLog("model choice: the record (wronggpu-setup\\model-choice.ini) cannot be read (") == 1); + CHECK(CountLog("(the model choice record cannot be read; wronggpu.ini model=") == 1); + CloseHandle(hold); + CHECK(ReadRec(rec).model == b); +#endif + // (14) a corrupt record (seq overflow): said once, not used (a fresh session: wronggpu.ini's item, never the host's + // entry), not written over by a create; NOR by a choice: the selection is refused (-2) with one log line, the file + // keeps its bytes (the player's to fix or delete) and the model that runs stays (b) + const std::string corrupt = "model=L\nseq=18446744073709551616\nsource=launcher\n"; + WriteRec(rec, corrupt); + CHECK(HostedCreate(iniB.c_str(), 0, idOf('M'), false) == name(b)); + CHECK(CountLog("is corrupt (seq is not a number") == 1); + wgchoice::ReadResult rr; + ReadRec(rec, &rr); + CHECK(rr == wgchoice::ReadResult::Corrupt); + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); + CHECK(rc == WG_HOST_SELECTED_REFUSED); + CHECK(CountLog("in OptiScaler's upscaler list: the record (wronggpu-setup\\model-choice.ini) is not a valid record") == 1); + { + std::ifstream i(rec, std::ios::binary); + CHECK(std::string(std::istreambuf_iterator(i), {}) == corrupt); + } + WriteRec(rec, "model=M\nseq=1\nsource=ffx\n"); // the player fixes the file: the next choice is saved again + CHECK(HostedCreate(iniB.c_str(), 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf(b)); }) == name(b)); + r = ReadRec(rec); + CHECK(rc == WG_HOST_SELECTED_RECORDED && r.model == b && r.seq == 2 && r.source == wgchoice::Source::Ffx); + // (15) the end of the sequence numbers: the selection is refused loudly (-2), the record unchanged + WriteRec(rec, std::string("model=") + b + "\nseq=18446744073709551615\nsource=plugin\n"); + CHECK(HostedCreate(iniM, 'M', idOf('M'), true, [&](FrontEnd& fe) { rc = fe.HostSelected(idOf('M')); }) == name(b)); + r = ReadRec(rec); + CHECK(rc == WG_HOST_SELECTED_REFUSED && r.model == b && r.seq == UINT64_MAX); + CHECK(CountLog("ERROR: the player selected Model M in OptiScaler's upscaler list: the record's sequence number is at its end") == 1); + // (16) the record names a model this build lacks, and sr_model (which the menu persists) still names this build's + // other model from an earlier session: a create that no entry names runs Model M, never the stale sr_model + if (hasK != hasL) { + const char missing = hasK ? 'L' : 'K'; + WriteRec(rec, std::string("model=") + missing + "\nseq=5\nsource=launcher\n"); + auto fe = ChoiceFrontEnd(iniB.c_str(), 0, false); // (Reset clears the menu's values: sr_model set after it) + g_menuValues[WG_OPT_SR_MODEL] = ModelOfName(std::string(1, b)); + CHECK(ChoiceCreate(*fe, 0) == name('M')); + CHECK(CountLog("model choice: that model is not part of this build of the front end; Model M is used") == 1); + g_menuValues.erase(WG_OPT_SR_MODEL); + } + } else { + // Model M only: the record is migrated (M, seq 1, launcher) and says what runs + CHECK(HostedCreate("runtime_options = model=M\n", 'M', idOf('M')) == name('M')); + CHECK(ReadRec(rec).model == 'M' && ReadRec(rec).seq == 1 && ReadRec(rec).source == wgchoice::Source::Launcher); + } + g_choiceRecord.clear(); + g_asiPresent = present; + g_asiHooked = hooked; + g_asiModel = saved; +} + +// The order of WrongGPU's model entries in the list the front end gives a host (ListVersions) is the one shared +// definition (wgshared wg_model_entries.h) the launcher writes OptiScaler's UpscalerIndex from: M, then K, then L, for this +// build's K / L flags. +static void TestModelEntryOrder() { + Reset(); + Config config; + config.hosted = true; + auto fe = MakeFrontEnd(config); + uint64_t count = 0; + ffxQueryDescGetVersions versions{}; + versions.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS; + versions.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE; + versions.device = kDevice; + versions.outputCount = &count; + CHECK(fe->Query(nullptr, &versions.header) == FFX_API_RETURN_OK && count > 0); + std::vector ids(count); + std::vector names(count); + versions.versionIds = ids.data(); + versions.versionNames = names.data(); + CHECK(fe->Query(nullptr, &versions.header) == FFX_API_RETURN_OK); + const bool withK = ModelOfName("K") >= 0, withL = ModelOfName("L") >= 0; + int listed = 0; + for (char m : {'M', 'K', 'L'}) { + const int want = wgentries::ModelEntryIndex(m, withK, withL); + const int32_t row = ModelOfName(std::string(1, m)); + const WgEntryDef* sr = row >= 0 ? SrEntryOfModel(row) : nullptr; + CHECK((want < 0) == (sr == nullptr)); + if (!sr) continue; + ++listed; + CHECK(want < int(count) && ids[size_t(want)] == sr->id); + } + CHECK(listed == 1 + (withK ? 1 : 0) + (withL ? 1 : 0)); +} + // i15: WrongGPU's version-list entries come from the registry (clean/wgshared). i20 (owner 2026-10-31): only the SR // models; the RR modes are a box of their own in the RR plugin's menu tab. An entry sets the context's model and // writes sr_model; one folder per choice lists its one entry and applies it without an override; a module that is not @@ -3056,20 +3389,21 @@ static void TestRegistryEntries() { std::get<1>(g_menuWrites[0]) == WG_SR_MODEL_M && std::get<2>(g_menuWrites[0]) == "menu"); CHECK(CountLog("the host chose WrongGPU Model M (0x5747000000000001): settings: sr_model=M (menu)") == 1); #if WRONGGPU_MODEL_K - // Model K chosen: sr_model=K written, the context runs Model K. - CHECK(run(kWrongGpuKProviderVersionId, true) == "WrongGPU Model K"); - CHECK(g_menuWrites.size() == 2 && std::get<0>(g_menuWrites[1]) == WG_OPT_SR_MODEL && std::get<1>(g_menuWrites[1]) == WG_SR_MODEL_K); - CHECK(g_createOptions.size() >= 8 && g_createOptions.compare(g_createOptions.size() - 8, 8, ";model=K") == 0); - CHECK(g_menuValues[WG_OPT_SR_MODEL] == WG_SR_MODEL_K); - // No override at all (the host passes none): sr_model as configured (K), nothing written. - CHECK(run(0, false) == "WrongGPU Model K" && g_menuWrites.size() == 2); - CHECK(CountLog("settings: sr_model=K (ini)") >= 1); + // Model K's entry: the host's stored entry is no choice (0.6.5 #213): the model choice route decides (no state folder + // and no model item here: Model M); sr_model=M written, the context runs Model M, the log names both. + CHECK(run(kWrongGpuKProviderVersionId, true) == "WrongGPU Model M"); + CHECK(g_menuWrites.size() == 2 && std::get<0>(g_menuWrites[1]) == WG_OPT_SR_MODEL && std::get<1>(g_menuWrites[1]) == WG_SR_MODEL_M); + CHECK(g_createOptions.size() >= 8 && g_createOptions.compare(g_createOptions.size() - 8, 8, ";model=M") == 0); + CHECK(CountLog("model choice: the host's entry names Model K; Model M runs") == 1); + // No override at all (the host passes none): the same route, nothing written. + CHECK(run(0, false) == "WrongGPU Model M" && g_menuWrites.size() == 2); #endif - // Every entry the registry has: its option = its value, and nothing writes rr_mode (the RR plugin's box owns it). + // Every entry the registry has: the model choice route's model (here Model M) is written, whatever the entry names, + // and nothing writes rr_mode (the RR plugin's box owns it). for (int i = 0; i < kOwn; ++i) { const WgEntryDef* e = OwnEntry(i); - CHECK(!run(e->id, true).empty()); - CHECK(!g_menuWrites.empty() && std::get<0>(g_menuWrites.back()) == e->slot && std::get<1>(g_menuWrites.back()) == e->value); + CHECK(run(e->id, true) == "WrongGPU Model M"); + CHECK(!g_menuWrites.empty() && std::get<0>(g_menuWrites.back()) == WG_OPT_SR_MODEL && std::get<1>(g_menuWrites.back()) == WG_SR_MODEL_M); CHECK(CountLog((std::string("the host chose ") + EntryProviderName(*e) + " (").c_str()) >= 1); } for (const auto& w : g_menuWrites) CHECK(std::get<0>(w) != WG_OPT_RR_MODE); @@ -3272,15 +3606,15 @@ static void TestCustomSlotFailedCreate() { CHECK(CountLog("this failure is remembered for the session") == 1); CHECK(CountLog("no context, the host's own upscaler takes over") == 1); CHECK(CountLog("custom slot: create ") == 4 && CountLog("custom slot: create 10 since the failure") == 1); - // Another model is something new: one attempt of its own. + // Another entry (Model K's) is no other model (0.6.5 #213: the stored entry is no choice): the same upscaler with the + // same options, so the remembered failure stands and nothing is tried again. #if WRONGGPU_MODEL_K { UpscaleCreate k(FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE, true); k.version.versionId = kWrongGpuKProviderVersionId; ffxContext ctx = nullptr; CHECK(fe->CreateContext(&ctx, &k.upscale.header, nullptr) == FFX_API_RETURN_ERROR_RUNTIME_ERROR && !ctx); - CHECK(g_createCalls == 2 && CountLog("this failure is remembered for the session") == 2); - CHECK(fe->CreateContext(&ctx, &k.upscale.header, nullptr) == FFX_API_RETURN_ERROR_RUNTIME_ERROR && g_createCalls == 2); + CHECK(g_createCalls == 1); } #endif // A working upscaler (the model was there) in a fresh session: created, hooks after the create. @@ -3866,6 +4200,8 @@ int main() { TestAsiPluginHooked(); TestAsiPluginNotHooked(); TestAsiPluginPresetK(); + TestAsiChoiceRecord(); + TestModelEntryOrder(); { Config profile; const auto original = profile.BackendOptions(); diff --git a/clean/fsr/tests/test_model_choice_record.cpp b/clean/fsr/tests/test_model_choice_record.cpp new file mode 100644 index 00000000..a904c667 --- /dev/null +++ b/clean/fsr/tests/test_model_choice_record.cpp @@ -0,0 +1,575 @@ +// SPDX-License-Identifier: MIT +// Unit tests of the game's model choice record (clean/fsr/src/model_choice_record.h) on REAL files in a fresh folder under +// the system temporary folder, and with REAL processes (this program started again as a writer, a reader, a launcher +// apply, a lock holder, or a lock holder that dies): the strict three-key format, seq order with each source winning in +// turn, the game's state lock (wg_state.h: concurrent writers lose no update, seq never goes back; an abandoned lock is +// taken over; two path aliases of one folder are one lock), the upgrade migration (under the lock, against a launcher +// apply in another process), corrupt and overflowing records, the end of the sequence numbers, failures that change +// nothing (no queue), a stale temporary file. +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../src/model_choice_record.h" + +using namespace wgchoice; +namespace fs = std::filesystem; + +static int g_failures = 0, g_checks = 0; +#define CHECK(cond) \ + do { \ + ++g_checks; \ + if (!(cond)) { ++g_failures; std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); } \ + } while (0) + +namespace { + +std::string Valid(const char* model = "L", const char* seq = "7", const char* source = "launcher") { + return std::string("; c\r\n\r\nmodel=") + model + "\r\nseq=" + seq + "\r\nsource=" + source + "\r\n"; +} + +bool Parses(const std::string& text, Record* r = nullptr) { + Record tmp; + std::string why; + return ParseRecord(text, r ? r : &tmp, &why); +} + +void TestStrictFormat() { + Record r; + CHECK(Parses(Valid(), &r) && r.model == 'L' && r.seq == 7 && r.source == Source::Launcher); + CHECK(Parses("model=M\nseq=1\nsource=ffx\n", &r) && r.model == 'M' && r.source == Source::Ffx); + CHECK(Parses("model=K\nseq=18446744073709551615\nsource=plugin", &r) && r.seq == UINT64_MAX && r.source == Source::Plugin); + CHECK(!Parses("")); // no record + CHECK(!Parses("model=L\nseq=7\n")); // a key missing + CHECK(!Parses(Valid() + "model=K\r\n")); // a key twice + CHECK(!Parses(Valid() + "extra=1\r\n")); // an unknown key + CHECK(!Parses(Valid() + "ffx=L\r\n")); // the earlier design's fourth key: corrupt + CHECK(!Parses(Valid("l")) && !Parses(Valid("Q")) && !Parses(Valid("LL"))); // model: M, K or L exactly + CHECK(!Parses(Valid("L", "0")) && !Parses(Valid("L", "-1")) && !Parses(Valid("L", "7x")) && !Parses(Valid("L", ""))); + CHECK(!Parses(Valid("L", "18446744073709551616"))); // 2^64: overflow refused + CHECK(!Parses(Valid("L", "99999999999999999999"))); // 20 digits, overflow refused + CHECK(!Parses(Valid("L", "000000000000000000001"))); // 21 digits refused + CHECK(!Parses(Valid("L", "7", "game")) && !Parses(Valid("L", "7", "Launcher"))); + CHECK(!Parses("model = L\nseq=7\nsource=launcher\n")); // no spaces around '=' + CHECK(!Parses("model=L\nseq=7\nsource=launcher\ngarbage\n")); // a line that is not key=value + CHECK(Parses(FormatRecord(Record{'K', 42, Source::Plugin}), &r) && r.model == 'K' && r.seq == 42 && r.source == Source::Plugin); +} + +struct Folder { + fs::path dir; + explicit Folder(const char* name = "") { + dir = fs::temp_directory_path() / ("wg-choice-test-" + std::to_string( +#ifdef _WIN32 + GetCurrentProcessId() +#else + 0 +#endif + ) + name); + std::error_code ec; + fs::create_directories(dir / kStateFolder, ec); + } + fs::path record() const { return RecordPathIn(dir); } + ~Folder() { // our own files only, one by one + std::error_code ec; + for (auto& e : fs::directory_iterator(dir / kStateFolder, ec)) fs::remove(e.path(), ec); + fs::remove(dir / kStateFolder, ec); + fs::remove(dir, ec); + } +}; + +void WriteRaw(const fs::path& p, const std::string& text) { + std::ofstream f(p, std::ios::binary | std::ios::trunc); + f << text; +} + +std::string ReadRaw(const fs::path& p) { + std::ifstream f(p, std::ios::binary); + return std::string(std::istreambuf_iterator(f), std::istreambuf_iterator()); +} + +Record Rec(const fs::path& p, ReadResult* rr = nullptr) { + Record r; + std::string why; + const ReadResult res = ReadRecordFile(p, &r, &why); + if (rr) *rr = res; + return res == ReadResult::Ok ? r : Record{0, 0, Source::Launcher}; +} + +int TmpFiles(const Folder& f) { + int n = 0; + std::error_code ec; + for (auto& e : fs::directory_iterator(f.dir / kStateFolder, ec)) + if (wgstate::IsTempName(e.path().filename().wstring())) ++n; + return n; +} + +// An install with an id (the install record's install-id line, #224): every write of the record carries WrongGPU's stamp +// for model-choice.ini and that id (wg_state.h WriteStamped), so the launcher's uninstall knows the record as WrongGPU's; +// the stamp is a comment line the parser skips. Another install's id, or the file under another name: not stamped for it. +void TestStampedRecord() { + Folder f("stamp"); + const std::string id = "0123456789abcdef0123456789abcdef"; + { + std::ofstream o(f.dir / kStateFolder / "install.record", std::ios::binary); + o << "WRONGGPU-RECORD 2\r\ninstall-id\t" << id << "\r\n"; + } + Record after; + std::string why; + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); + std::string bytes; + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes)); + CHECK(wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(!wgstate::StampedByWrongGPU(bytes, "model-choice.ini", "fedcba9876543210fedcba9876543210")); + CHECK(!wgstate::StampedByWrongGPU(bytes, "settings.ini", id)); + Record r; + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.model == 'L' && r.seq == 1); + // the next choice: still stamped, the seq grows (the stamp line is not read as part of the record) + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 2); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.model == 'K' && r.seq == 2 && r.source == Source::Ffx); + // without an install id (no install record): nothing is stamped (the earlier stamp line is no longer valid and stays as a + // comment, as #224's updater keeps any line that is not a valid stamp); a new record without an id: no stamp line at all + fs::remove(f.dir / kStateFolder / "install.record"); + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Written); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && !wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.model == 'M' && r.seq == 3); + fs::remove(f.record()); + CHECK(RecordChoice(f.record(), 'K', Source::Launcher, &after, &why) == Outcome::Written && after.seq == 1); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && bytes.find(wgstate::kStampPrefix) == std::string::npos); +} + +void TestChoicesInTurn() { + Folder f; + Record r, after; + std::string why; + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Missing); + // each source winning in turn: launcher L, the player in OptiScaler's list (K, an event), the plugin's menu (M), the + // launcher again (L), the list re-selecting the SAME entry after a plugin choice (it wins): the highest seq is the record + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written && after.seq == 1); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written); + r = Rec(f.record()); + CHECK(r.model == 'K' && r.seq == 2 && r.source == Source::Ffx); + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Written); + r = Rec(f.record()); + CHECK(r.model == 'M' && r.seq == 3 && r.source == Source::Plugin); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written); // K again in the list: wins + r = Rec(f.record()); + CHECK(r.model == 'K' && r.seq == 4 && r.source == Source::Ffx); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 5 && r.source == Source::Launcher); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); // the same choice again: seq grows + CHECK(Rec(f.record()).seq == 6); + // a stale temporary file a crash left next to the record (and garbage in it): never read, writes still work + const fs::path stale = f.record().wstring() + wgstate::kTempMark + L"999-1"; + WriteRaw(stale, "model=K\nseq=999999"); + CHECK(Rec(f.record()).seq == 6); + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why) == Outcome::Written && Rec(f.record()).seq == 7); + std::error_code ec; + fs::remove(stale, ec); + // only a temporary file, no record (a crash before the move): no record + fs::remove(f.record(), ec); + WriteRaw(stale, Valid()); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Missing); + fs::remove(stale, ec); + CHECK(TmpFiles(f) == 0); // no temporary file is left behind by the writes +} + +// #224's rule for the game's state files: a choice changes only the record's three key lines, in place. A record WrongGPU +// wrote and nobody changed keeps WrongGPU's stamp; one the player edited (a comment added to a stamped record) or made +// (no stamp) keeps every other byte (comments, blank lines, line ends) and stays UNSTAMPED, the player's, which the +// launcher's uninstall keeps. +void TestPlayerFiles() { + Folder f("player"); + const std::string id = "00112233445566778899aabbccddeeff"; + { + std::ofstream o(f.dir / kStateFolder / "install.record", std::ios::binary); + o << "WRONGGPU-RECORD 2\r\ninstall-id\t" << id << "\r\n"; + } + Record after, r; + std::string why, bytes; + // WrongGPU's own record: re-stamped + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + // edited: the player adds a comment line to the stamped record; the next choice keeps it, writes K, no stamp + WriteRaw(f.record(), "; my note: keep L for this game\r\n" + bytes); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 2); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes)); + CHECK(bytes.rfind("; my note: keep L for this game\r\n", 0) == 0); + CHECK(bytes.find("model=K\r\nseq=2\r\nsource=ffx\r\n") != std::string::npos); + CHECK(!wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Ok && r.model == 'K' && r.seq == 2); + // and it stays the player's on the choice after that (still no stamp) + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Written && after.seq == 3); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && !wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(bytes.rfind("; my note: keep L for this game\r\n", 0) == 0); + // player-made: LF line ends, a blank line, comments around the keys, keys in another order, no stamp + const std::string mine = "# mine\n\nsource=launcher\n; the model:\nmodel=L\nseq=40\n# end\n"; + WriteRaw(f.record(), mine); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why) == Outcome::Written && after.seq == 41); + CHECK(ReadRaw(f.record()) == "# mine\n\nsource=ffx\n; the model:\nmodel=K\nseq=41\n# end\n"); + CHECK(wgstate::ReadBytes(f.record().wstring(), &bytes) && !wgstate::StampedByWrongGPU(bytes, "model-choice.ini", id)); + CHECK(TmpFiles(f) == 0); +} + +void TestCorruptAndEnd() { + Folder f; + Record r, after; + std::string why; + // corrupt and overflowing records (and text WrongGPU cannot keep: a NUL): Corrupt, never a partial choice, and NEVER + // replaced: a choice is refused with what is wrong, the file keeps its bytes (the player's to fix or delete) + for (const std::string& bad : {Valid("L", "18446744073709551616"), std::string("model=L\nseq=3\n"), std::string(4096, 'x'), + Valid() + "ffx=L\r\n", std::string("model=L\0\nseq=3\nsource=ffx\n", 26)}) { + WriteRaw(f.record(), bad); + CHECK(ReadRecordFile(f.record(), &r, &why) == ReadResult::Corrupt); + why.clear(); + CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why) == Outcome::Corrupt); + CHECK(!why.empty()); + CHECK(ReadRaw(f.record()) == bad); + } + CHECK(std::string(OutcomeWords(Outcome::Corrupt)).find("left as it is") != std::string::npos); + // the end of the sequence numbers: refused loudly (SeqExhausted), the record unchanged, never wrapped to 0 + WriteRaw(f.record(), Valid("K", "18446744073709551615", "plugin")); + const std::string before = ReadRaw(f.record()); + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::SeqExhausted); + CHECK(ReadRaw(f.record()) == before); + CHECK(std::string(OutcomeWords(Outcome::SeqExhausted)).find("refused") != std::string::npos); + CHECK(TmpFiles(f) == 0); +} + +void TestMigration() { + Folder f; + Record r; + bool migrated = false; + std::string why; + auto model = [](char m) { return [m] { return m; }; }; + // an install from before 0.6.5 (no record): wronggpu.ini's model item, seq 1, source=launcher; the stamp files of the + // earlier designs next to it are ignored + WriteRaw(f.dir / kStateFolder / "wronggpu-ffx-choice.ini", "model=K\nchosen=99999999999\n"); + CHECK(LoadOrMigrateRecord(f.record(), model('L'), &r, &migrated, &why) == LoadResult::Ok && migrated); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher); + // a record now: returned as it is, nothing written, the model item not even read + const std::string text = ReadRaw(f.record()); + bool asked = false; + CHECK(LoadOrMigrateRecord(f.record(), [&] { asked = true; return 'K'; }, &r, &migrated, &why) == LoadResult::Ok && !migrated && + r.model == 'L' && !asked); + CHECK(ReadRaw(f.record()) == text); + // no model item: Model M + std::error_code ec; + fs::remove(f.record(), ec); + CHECK(LoadOrMigrateRecord(f.record(), model(0), &r, &migrated, &why) == LoadResult::Ok && migrated && r.model == 'M' && r.seq == 1); + // a corrupt record is not migrated over (it stays corrupt until a real choice replaces it) + WriteRaw(f.record(), "model=L\n"); + CHECK(LoadOrMigrateRecord(f.record(), model('K'), &r, &migrated, &why) == LoadResult::Corrupt && !migrated); + CHECK(ReadRaw(f.record()) == "model=L\n"); + fs::remove(f.dir / kStateFolder / "wronggpu-ffx-choice.ini", ec); +} + +#ifdef _WIN32 +// Failures change nothing and nothing is kept for later: a write that fails (the record held open without delete sharing, +// so it cannot be replaced), the game's state lock held by another thread (through another spelling of the game folder), +// an unreadable record (never written over). After each, the next choice is written normally from the record as it is. +void TestFailures() { + Folder f; + Record after, before; + std::string why; + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); // seq 1 + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, &before) == Outcome::Written && before.model == 'L' && + before.seq == 1 && after.seq == 2); // the record replaced is reported + HANDLE h = CreateFileW(f.record().c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(h != INVALID_HANDLE_VALUE); + const std::string kept = ReadRaw(f.record()); + CHECK(RecordChoice(f.record(), 'M', Source::Ffx, &after, &why) == Outcome::WriteFailed && !why.empty()); + CloseHandle(h); + CHECK(ReadRaw(f.record()) == kept); // nothing changed, nothing to be written later + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written && after.seq == 3); + // the game's state lock (wg_state.h, the lock settings.ini's writers take too) held by another thread, through the game + // folder spelt differently: NoLock within the wait, nothing written + std::atomic held{false}, release{false}; + std::thread holder([&] { + std::wstring other = f.dir.wstring(); + for (auto& c : other) c = c == L'\\' ? L'/' : wchar_t(towupper(c)); + wgstate::StateLock l(other); + held.store(l.held()); + while (!release.load()) Sleep(1); + }); + while (!held.load()) Sleep(1); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why, nullptr, 100) == Outcome::NoLock); + bool migrated = false; + Record r; + CHECK(LoadOrMigrateRecord(f.record(), [] { return 'M'; }, &r, &migrated, &why, 100) == LoadResult::NoLock); + release.store(true); + holder.join(); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 3); + // a record held open without any sharing: Unreadable, never written over + h = CreateFileW(f.record().c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + CHECK(RecordChoice(f.record(), 'M', Source::Plugin, &after, &why) == Outcome::Unreadable); + CHECK(LoadOrMigrateRecord(f.record(), [] { return 'M'; }, &r, &migrated, &why) == LoadResult::Unreadable); + CloseHandle(h); + CHECK(Rec(f.record()).seq == 3 && Rec(f.record()).model == 'L'); + CHECK(TmpFiles(f) == 0); +} + +std::wstring Self() { + wchar_t buf[MAX_PATH]; + GetModuleFileNameW(nullptr, buf, MAX_PATH); + return buf; +} + +HANDLE Spawn(const std::wstring& args) { + std::wstring cmd = L"\"" + Self() + L"\" " + args; + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) return nullptr; + CloseHandle(pi.hThread); + return pi.hProcess; +} + +HANDLE Spawn2(std::wstring cmd) { // another program's command line + STARTUPINFOW si{}; + si.cb = sizeof si; + PROCESS_INFORMATION pi{}; + if (!CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi)) return nullptr; + CloseHandle(pi.hThread); + return pi.hProcess; +} + +DWORD Wait(HANDLE p) { + WaitForSingleObject(p, 120000); + DWORD code = 999; + GetExitCodeProcess(p, &code); + CloseHandle(p); + return code; +} + +// Several REAL processes writing the record at once (the launcher, the front end and the plugin are separate programs or +// modules that all use RecordChoice), and one reading it under the lock: no update is lost (the final seq is the number +// of writes), each writer sees its own seq grow, the reader never sees a partial record or seq going back. +void TestConcurrentProcesses() { + Folder f("-procs"); + const int kWriters = 4, kWrites = 150; + const wchar_t* models = L"MKLM"; + const wchar_t* sources[] = {L"launcher", L"ffx", L"plugin", L"plugin"}; + HANDLE reader = Spawn(L"reader \"" + f.record().wstring() + L"\" " + std::to_wstring(kWriters * kWrites)); + std::vector writers; + for (int i = 0; i < kWriters; ++i) + writers.push_back(Spawn(L"writer \"" + f.record().wstring() + L"\" " + std::wstring(1, models[i]) + L" " + sources[i] + L" " + + std::to_wstring(kWrites))); + int failed = 0; + for (HANDLE w : writers) { + CHECK(w != nullptr); + if (w && Wait(w) != 0) ++failed; + } + CHECK(failed == 0); + const DWORD readerCode = reader ? Wait(reader) : 999; + if (readerCode != 0) std::printf("reader exit %lu\n", static_cast(readerCode)); + CHECK(readerCode == 0); + Record r = Rec(f.record()); + CHECK(r.seq == uint64_t(kWriters * kWrites)); // no lost update + std::printf("concurrent processes: %d writers x %d writes, final seq %llu\n", kWriters, kWrites, static_cast(r.seq)); + CHECK(TmpFiles(f) == 0); +} + +// A process that dies while it holds the lock: the next one takes it over (WAIT_ABANDONED) and the record is whole. +void TestAbandonedLock() { + Folder f("-abandon"); + Record after; + std::string why; + CHECK(RecordChoice(f.record(), 'L', Source::Launcher, &after, &why) == Outcome::Written); + HANDLE p = Spawn(L"lock-and-die \"" + f.record().wstring() + L"\""); + CHECK(p != nullptr && Wait(p) == 97); + CHECK(RecordChoice(f.record(), 'K', Source::Ffx, &after, &why, nullptr, 2000) == Outcome::Written && after.seq == 2); + CHECK(Rec(f.record()).model == 'K'); +} + +// The upgrade migration reads wronggpu.ini's model item WHILE it holds the game's state lock, so a launcher apply (which +// holds the same lock across wronggpu.ini and the record) is wholly before or after it, in two REAL processes: +// (1) a launcher process takes the lock, writes wronggpu.ini (model=L) and dies before it writes the record: the waiting +// migration reads L, never the M it would have read before the lock; +// (2) a launcher process takes the lock, writes wronggpu.ini and then the record (L, seq 1): the waiting migration finds +// that record and writes nothing. +char IniModel(const fs::path& ini) { + const std::string text = ReadRaw(ini); + const size_t at = text.rfind("model="); + return at == std::string::npos || at + 6 >= text.size() ? 0 : text[at + 6]; +} + +void TestMigrationUnderLock() { + for (int crash = 1; crash >= 0; --crash) { + Folder f(crash ? "-mig1" : "-mig2"); + const fs::path ini = f.dir / "wronggpu.ini", signal = f.dir / "locked.txt"; + WriteRaw(ini, "[fsr]\r\nruntime_options = model=M\r\n"); + HANDLE p = Spawn(std::wstring(crash ? L"apply-and-die" : L"apply") + L" \"" + f.dir.wstring() + L"\""); + CHECK(p != nullptr); + for (int i = 0; i < 5000 && !fs::exists(signal); ++i) Sleep(1); // the launcher holds the lock now + CHECK(fs::exists(signal)); + CHECK(IniModel(ini) == 'M'); // read now, before the lock, it would still be M + Record r; + bool migrated = false; + std::string why; + CHECK(LoadOrMigrateRecord(f.record(), [&] { return IniModel(ini); }, &r, &migrated, &why, 10000) == LoadResult::Ok); + CHECK(r.model == 'L' && r.seq == 1 && r.source == Source::Launcher && migrated == (crash == 1)); + CHECK(Wait(p) == DWORD(crash ? 97 : 0)); + r = Rec(f.record()); + CHECK(r.model == 'L' && r.seq == 1); + std::error_code ec; + fs::remove(ini, ec); + fs::remove(signal, ec); + } +} + +// Two path aliases of one game folder (a directory junction, and the \\?\ form) name ONE lock: a process holding the +// game's state lock through the junction keeps a writer that uses the real path out. +void TestAliasesOneLock() { + Folder f("-alias"); + const std::wstring alias = f.dir.wstring() + L"-junction"; + RemoveDirectoryW(alias.c_str()); + HANDLE mk = Spawn2(L"cmd.exe /d /c mklink /J \"" + alias + L"\" \"" + f.dir.wstring() + L"\" >nul"); + CHECK(mk != nullptr && Wait(mk) == 0); + std::wstring a, b, c; + CHECK(wgstate::LockNameFor(f.dir.wstring(), &a) && wgstate::LockNameFor(alias, &b) && + wgstate::LockNameFor(L"\\\\?\\" + f.dir.wstring(), &c)); + CHECK(!a.empty() && a == b && a == c); + const fs::path signal = f.dir / "held.txt"; + HANDLE p = Spawn(L"hold \"" + alias + L"\" 1500"); + for (int i = 0; i < 5000 && !fs::exists(signal); ++i) Sleep(1); + CHECK(fs::exists(signal)); + Record after; + std::string why; + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, nullptr, 200) == Outcome::NoLock); + CHECK(p != nullptr && Wait(p) == 0); + CHECK(RecordChoice(f.record(), 'K', Source::Plugin, &after, &why, nullptr, 2000) == Outcome::Written && after.seq == 1); + std::error_code ec; + fs::remove(signal, ec); + CHECK(RemoveDirectoryW(alias.c_str()) != 0); // the junction only; the folder stays + CHECK(fs::exists(f.record())); +} + +int ChildApply(const fs::path& gameDir, bool crash) { + const fs::path record = RecordPathIn(gameDir); + Lock lock(record); + if (!lock.ok()) return 1; + WriteRaw(gameDir / "locked.txt", "1"); + Sleep(300); + WriteRaw(gameDir / "wronggpu.ini", "[fsr]\r\nruntime_options = model=L\r\n"); + if (crash) TerminateProcess(GetCurrentProcess(), 97); // dies holding the lock, before the record + Record after; + std::string why; + return RecordChoiceUnlocked(record, 'L', Source::Launcher, &after, &why) == Outcome::Written ? 0 : 2; +} + +// The front end's upgrade migration for the game in gameDir, run by the launcher's end-to-end test against a REAL launcher +// apply in another process (run_model_l_tests.py): reads wronggpu.ini's model item under the state lock; prints the result. +int ChildMigrate(const fs::path& gameDir) { + Record r; + bool migrated = false; + std::string why; + const LoadResult lr = LoadOrMigrateRecord(RecordPathIn(gameDir), [&] { return IniModel(gameDir / "wronggpu.ini"); }, &r, &migrated, &why, 20000); + std::printf("migrate: %s model=%c seq=%llu migrated=%d\n", lr == LoadResult::Ok ? "ok" : "failed", lr == LoadResult::Ok ? r.model : '-', + static_cast(r.seq), migrated ? 1 : 0); + return lr == LoadResult::Ok ? 0 : 1; +} + +int ChildHold(const std::wstring& gameDir, int ms) { + wgstate::StateLock lock(gameDir); + if (!lock.held()) return 1; + WriteRaw(fs::path(gameDir) / "held.txt", "1"); + Sleep(ms); + return 0; +} + +int ChildWriter(const fs::path& record, char model, const std::string& source, int count) { + const Source s = source == "launcher" ? Source::Launcher : source == "ffx" ? Source::Ffx : Source::Plugin; + uint64_t last = 0; + int bad = 0; + for (int i = 0; i < count; ++i) { + Record after; + std::string why; + const Outcome o = RecordChoice(record, model, s, &after, &why, nullptr, 20000); + if (o != Outcome::Written) { + std::printf("writer %c: %s (%s)\n", model, OutcomeWords(o), why.c_str()); + ++bad; + continue; + } + if (after.seq <= last) ++bad; // seq went back or stood still for this writer + last = after.seq; + Sleep(0); // let the other processes take the lock between two writes + } + return bad; +} + +int ChildReader(const fs::path& record, uint64_t until) { + uint64_t last = 0; + int bad = 0; + const ULONGLONG start = GetTickCount64(); + while (last < until && GetTickCount64() - start < 100000) { + { + Lock lock(record, 20000); + if (!lock.ok()) { std::printf("reader: lock not taken\n"); return 100; } + Record r; + std::string why; + const ReadResult rr = ReadRecordFile(record, &r, &why); + // a partial or corrupt record would be a failure; a read another program (a virus scanner looking at the new + // file) briefly refused is not, and is only reported + if (rr == ReadResult::Corrupt) { + ++bad; + std::printf("reader: corrupt (%s)\n", why.c_str()); + } + if (rr == ReadResult::Unreadable) std::printf("reader: one read refused (%s)\n", why.c_str()); + if (rr == ReadResult::Ok) { + if (r.seq < last) { ++bad; std::printf("reader: seq went back %llu -> %llu\n", (unsigned long long)last, (unsigned long long)r.seq); } + last = r.seq; + } + } + Sleep(1); // a Windows mutex is not fair: a reader that takes it again at once could keep the writers out + } + return bad + (last < until ? 1000 : 0); +} +#endif + +} // namespace + +int main(int argc, char** argv) { +#ifdef _WIN32 + if (argc >= 6 && std::string(argv[1]) == "writer") return ChildWriter(argv[2], argv[3][0], argv[4], std::atoi(argv[5])); + if (argc >= 4 && std::string(argv[1]) == "reader") return ChildReader(argv[2], std::strtoull(argv[3], nullptr, 10)); + if (argc >= 3 && std::string(argv[1]) == "migrate") return ChildMigrate(argv[2]); + if (argc >= 3 && std::string(argv[1]) == "apply") return ChildApply(argv[2], false); + if (argc >= 3 && std::string(argv[1]) == "apply-and-die") return ChildApply(argv[2], true); + if (argc >= 4 && std::string(argv[1]) == "hold") return ChildHold(fs::path(argv[2]).wstring(), std::atoi(argv[3])); + if (argc >= 3 && std::string(argv[1]) == "lock-and-die") { + Lock lock(argv[2]); + if (!lock.ok()) return 1; + TerminateProcess(GetCurrentProcess(), 97); // dies holding the lock + } +#else + (void)argc; + (void)argv; +#endif + TestStrictFormat(); + TestChoicesInTurn(); + TestStampedRecord(); + TestPlayerFiles(); + TestCorruptAndEnd(); + TestMigration(); +#ifdef _WIN32 + TestFailures(); + TestConcurrentProcesses(); + TestAbandonedLock(); + TestMigrationUnderLock(); + TestAliasesOneLock(); +#endif + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/clean/installer/src/app/cli.cpp b/clean/installer/src/app/cli.cpp index 1d739319..67efccb5 100644 --- a/clean/installer/src/app/cli.cpp +++ b/clean/installer/src/app/cli.cpp @@ -816,10 +816,12 @@ int Verb(const wstring& verb, const Args& a, Output& o) { if (!LoadRecord(RecordPath(dir), m) || m.legacy) { o.j.S("error", L"WrongGPU is not installed in " + dir); Print(L"WrongGPU is not installed in " + dir); return EXIT_NOT_INSTALLED; } Profile p = GameProfile(dir); std::vector> optiEdits; + bool modelGiven = false; // a model= item: the player's explicit model choice if (verb == L"set") { for (size_t i = 1; i < a.pos.size(); ++i) { const wstring& kv = a.pos[i]; const size_t eq = kv.find(L'='); + if (eq != wstring::npos && IEq(kv.substr(0, eq), L"model")) modelGiven = true; wstring why; if (eq == wstring::npos) why = L"use key=value: " + kv; else if (StartsWithI(kv, L"opti.")) { // an OptiScaler.ini key (the OptiScaler tab): checked when applied @@ -840,6 +842,13 @@ int Verb(const wstring& verb, const Args& a, Output& o) { if (NeedsElevation(dir)) { o.j.S("error", L"administrator permission is needed for " + dir); Print(L"administrator permission is needed for " + dir); return EXIT_REFUSED; } OpLogBegin(); OpRequest r; r.op = Op::Apply; r.dir = dir; r.hasProfile = true; r.profile = p; r.optiEdits = optiEdits; + r.modelChosen = modelGiven; // set model=: the player's explicit model choice, stamped (also the same model) +#ifdef WRONGGPU_TESTING + if (a.has(L"gui-apply")) { // tests: the request the launcher window's Apply makes (GuiApplyRequest), the same code + r = GuiApplyRequest(dir, p); + r.optiEdits = optiEdits; + } +#endif Ui ui; ui.step = [](int, int, const wstring&) {}; ui.log = [](const wstring& s) { LogLine(g.ctx, s); }; const OpResult res = RunOp(g.ctx, r, ui); OpLogEnd(); diff --git a/clean/installer/src/app/launcher_ui.cpp b/clean/installer/src/app/launcher_ui.cpp index 81859da8..2bc6d662 100644 --- a/clean/installer/src/app/launcher_ui.cpp +++ b/clean/installer/src/app/launcher_ui.cpp @@ -1003,7 +1003,7 @@ void StartNextQueued() { // (WM_APP_OPDONE), never lost. void OnApply() { if (PageWritesWait()) return; // one rule for every write of the page (its Apply says why) - OpRequest r; r.op = Op::Apply; r.dir = v.cur.dir; r.hasProfile = true; r.profile = v.edit; + OpRequest r = GuiApplyRequest(v.cur.dir, v.edit); // the model shown is the player's model choice, even unchanged for (size_t i = 0; i < v.opti.editable.size() && i < v.optiValues.size(); ++i) if (v.optiValues[i] != v.opti.editable[i].value) r.optiEdits.push_back({v.opti.editable[i].section + "." + v.opti.editable[i].key, v.optiValues[i]}); for (auto& e : r.optiEdits) { // the values typed are checked before anything is written diff --git a/clean/installer/src/wg_core/launcher.cpp b/clean/installer/src/wg_core/launcher.cpp index 3bdc7023..6cea53f6 100644 --- a/clean/installer/src/wg_core/launcher.cpp +++ b/clean/installer/src/wg_core/launcher.cpp @@ -17,6 +17,8 @@ #include #include "gamerules.h" +#include "../../../fsr/asi/asi_thunk.h" // wronggpu-asi.ini (ParseSelection / FormatSelection), pure +#include "../../../fsr/src/model_choice_record.h" // the game's model choice record #include "json_writer.h" #include "model.h" #include "optiscaler.h" @@ -990,6 +992,37 @@ static bool OptInKey(const wstring& exe, const IniKeyChange& c) { return false; } +// The launcher's entry in the game's model choice record (wronggpu-setup\model-choice.ini; model_choice_record.h): read, +// the next seq, written atomically; the caller holds the record's lock. A record that cannot be read is not written over; +// every failure is said in the notes and warnings. +bool WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, std::vector& notes, std::vector* warnings) { + const std::filesystem::path path = Join(StateDir(dir), wgchoice::kRecordFile); + wgchoice::Record after; + std::string why; + const wgchoice::Outcome o = wgchoice::RecordChoiceUnlocked(path, model, wgchoice::Source::Launcher, &after, &why); + if (o != wgchoice::Outcome::Written) { + const wstring w = L"The model choice record was not changed: " + FromUtf8(wgchoice::OutcomeWords(o)) + + (why.empty() ? wstring() : L" (" + FromUtf8(why) + L")") + L". The game may keep running its earlier model choice."; + LogLine(ctx, w); + notes.push_back(w); + if (warnings) warnings->push_back(w); + return false; + } + if (!why.empty()) LogLine(ctx, L"model-choice.ini: " + FromUtf8(why)); + LogLine(ctx, wstring(L"model choice record: Model ") + wchar_t(model) + L" (seq " + std::to_wstring(after.seq) + L", source=launcher)"); + return true; +} + +OpRequest GuiApplyRequest(const wstring& dir, const Profile& edit) { + OpRequest r; + r.op = Op::Apply; + r.dir = dir; + r.hasProfile = true; + r.profile = edit; + r.modelChosen = FindSetting("model") != nullptr; // Apply with a model shown is the player's model choice, even unchanged + return r; +} + std::vector> FrontEndStateKeys(const Profile& p) { std::vector> r{{"upscaler", p.get("wronggpu") == "off" ? "amd" : "network"}}; for (size_t i = 0; i < kSettingCount; ++i) @@ -1042,7 +1075,8 @@ Profile GameProfile(const wstring& dir) { return p; } -void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings) { +void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings, + bool modelChosen) { Record m; if (!LoadRecord(RecordPath(dir), m) || m.legacy) Fail(L"WrongGPU is not installed in " + dir + L".", EXIT_NOT_INSTALLED); InferOwners(ctx, m); @@ -1064,27 +1098,52 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (warnings) warnings->push_back(w); } } - auto renderFile = [&](const wchar_t* name, bool opti) { + // The game's state lock (wg_state.h, held by the launcher, the front end and the plugins for every read-modify-write + // of the game's state) is held across the model choice record and OptiScaler.ini's entry (and the state folder's other + // settings): the front end's upgrade migration, which reads wronggpu.ini's model item under the same lock, comes wholly + // before or after this. + // Not taken in time (the game is writing its state): nothing is applied. + const std::filesystem::path recordPath = Join(StateDir(dir), wgchoice::kRecordFile); + wgchoice::Lock lock(recordPath); + if (!lock.ok()) + Fail(L"Settings not applied: the game is saving WrongGPU's state right now (" + FromUtf8(wgchoice::OutcomeWords(wgchoice::Outcome::NoLock)) + + L"). Try again.", + EXIT_REFUSED); + char forcedEntry = 0; // the model whose entry OptiScaler.ini's UpscalerIndex is set to (after the record) + // What this apply has written so far, for a failure after some of it: the message then says exactly what was applied + // and what was not (no rollback: each piece is whole on its own). + std::vector applied, notApplied; + // wronggpu.ini is never rewritten here: it is the install's defaults and the player's file (the settings the launcher + // changes go to the game's WrongGPU state folder, wronggpu-setup: the model choice record below, settings.ini) + auto renderOpti = [&]() { + const wchar_t* name = L"OptiScaler.ini"; const wstring path = Join(dir, name); string in; - const bool had = ReadAll(path, in); - if (opti && !had) return; // OptiScaler.ini: only an existing file (ours) is changed - string out; wstring why; - if (opti) { - RenderOptiIni(q, in, out, ¬es); - bool wrote = false; - out = RenderGameOptiKeys(p, m.exe, out, m.inikeys, notes, &wrote); - if (wrote) - for (auto& n : kGameNotices) if (IEq(BaseName(m.exe), n.exe)) notes.push_back(n.notice); - JournalChanges(m.inikeys, name, in, out); - recordChanged = recordChanged || out != in; - } - else if (!RenderWronggpuIni(q, in, out, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); - if (out == in && (had || out.empty())) return; // unchanged, or nothing to write into a missing file + if (!ReadAll(path, in)) { // missing or unreadable: never created here; a model choice saved without it is said + if (forcedEntry) { + const wstring w = L"OptiScaler's list couldn't be updated; the model choice is saved (" + wstring(name) + + (IsFile(path) ? L" could not be read)." : L" is missing)."); + LogLine(ctx, w); + notes.push_back(w); + if (warnings) warnings->push_back(w); + } + return; + } + string out; + RenderOptiIni(q, in, out, ¬es); + if (forcedEntry) out = SetOptiModelEntry(out, forcedEntry); + bool wrote = false; + out = RenderGameOptiKeys(p, m.exe, out, m.inikeys, notes, &wrote); + if (wrote) + for (auto& n : kGameNotices) if (IEq(BaseName(m.exe), n.exe)) notes.push_back(n.notice); + JournalChanges(m.inikeys, name, in, out); + recordChanged = recordChanged || out != in; + if (out == in) return; WriteFileAtomic(path, out.data(), out.size()); const wstring h = Sha256Bytes(out.data(), out.size()); for (auto& e : m.e) if (e.action == L"copy" && IEq(e.rel, name) && e.inst != h) { e.inst = h; recordChanged = true; } notes.push_back(wstring(name) + L" written"); + applied.push_back(L"OptiScaler's list (OptiScaler.ini)"); }; // #219: the front end's settings go into the game's state folder (wg_state.h), which the front end reads over wronggpu.ini: // wronggpu.ini holds the install's defaults, is the player's to edit, and is never rewritten after the install. (The model @@ -1095,14 +1154,83 @@ void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vecto if (!RenderWronggpuIni(q, "", unused, &why)) Fail(L"Settings not applied: " + why, EXIT_USAGE); // (validates every setting) const int w = WriteStateKeys(ctx, dir, FrontEndStateKeys(q), &why); if (w < 0) Fail(L"Settings not applied: " + why, EXIT_REFUSED); - if (w > 0) notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written"); + if (w > 0) { + notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written"); + applied.push_back(L"the upscaler settings (" + Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L")"); + } } - if (HostedRecord(m)) renderFile(L"OptiScaler.ini", true); + // The model choice record (clean/fsr/src/model_choice_record.h): the launcher's model choice, with the next seq, when the + // player applied a model (Apply in the launcher, or `set model=`: always, also the same model again, so it + // wins over a newer choice made in the game), when the game has no record yet (from the profile), or when the + // launcher's own last choice can no longer run as recorded (a model whose data is not ready: Model M until it is). + // Then OptiScaler.ini's UpscalerIndex is set to that model's entry whatever it was (display only: the front end never + // takes the index for a choice, so a crash between the two leaves nothing wrong). + if (FindSetting("model")) { + const string want = q.get("model"); + const char model = want == "l" ? 'L' : want == "k" ? 'K' : 'M'; + wgchoice::Record cur; + std::string err; + const wgchoice::ReadResult rr = wgchoice::ReadRecordFile(recordPath, &cur, &err); +#ifdef WRONGGPU_TESTING + // tests: "|": the apply says it holds the lock (the record read, nothing written yet) and waits, so a + // test can start the front end's upgrade migration in another process exactly now + if (const wstring pause = EnvVar(L"WRONGGPU_TEST_PAUSE_IN_CHOICE_LOCK"); !pause.empty() && pause.find(L'|') != wstring::npos) { + const wstring sig = pause.substr(0, pause.find(L'|')); + WriteFileAtomic(sig, "1", 1); + Sleep(DWORD(_wtoi(pause.substr(pause.find(L'|') + 1).c_str()))); + } +#endif + const bool write = modelChosen || rr == wgchoice::ReadResult::Missing || + (rr == wgchoice::ReadResult::Ok && cur.source == wgchoice::Source::Launcher && cur.model != model); + const bool recorded = write && WriteLauncherModelChoice(ctx, dir, model, notes, warnings); + if (write) (recorded ? applied : notApplied).push_back(wstring(L"the model choice (Model ") + wchar_t(model) + L")"); + if (recorded) { + forcedEntry = model; +#ifdef WRONGGPU_TESTING + // tests: the apply ends here, after the record and before OptiScaler.ini (a crash between the two) + if (EnvVar(L"WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD") == L"1") TerminateProcess(GetCurrentProcess(), 97); +#endif + } + if (forcedEntry && modelChosen && HostedRecord(m)) { // the menu plugin's AMD entry chosen earlier: this choice is newer + const wstring asi = Join(dir, L"wronggpu-asi.ini"); + string text; + if (ReadAll(asi, text) && wgasi::ParseSelection(text) == wgasi::kModelAmd) { + // only the selection line changes (the player's comments and every other byte stay); ownership stays as + // recorded: a file whose bytes were WrongGPU's (the record's hash) stays WrongGPU's under its new hash, a + // file the player made or changed stays the player's (the record is not touched for it) + const string fresh = wgasi::WithSelection(text, model); + const wstring was = Sha256Bytes(text.data(), text.size()); + WriteFileAtomic(asi, fresh.data(), fresh.size()); + const wstring h = Sha256Bytes(fresh.data(), fresh.size()); + for (auto& e : m.e) + if (e.action == L"copy" && IEq(e.rel, L"wronggpu-asi.ini") && IEq(e.inst, was)) { e.inst = h; recordChanged = true; } + applied.push_back(L"OptiScaler's list back on WrongGPU (wronggpu-asi.ini)"); + notes.push_back(L"wronggpu-asi.ini: WrongGPU selected again in OptiScaler's list (the launcher's model choice is newer than AMD's FSR there)"); + } + } + } + if (HostedRecord(m)) renderOpti(); if (RecordHasRr(m)) { // Ray Reconstruction (rr.h): into the game's state folder (RR stays off while its data is not ready); // WrongGPU\wronggpu.ini (the install's defaults, the player's to edit) is never rewritten wstring why; - const int w = WriteRrState(ctx, dir, p, RrDataValid(ctx), &why, hadBefore ? &prevMode : nullptr); - if (w < 0) Fail(L"Settings not applied: " + why, EXIT_REFUSED); + int w; +#ifdef WRONGGPU_TESTING + // tests: the RR write fails after the upscaler settings (and the model choice) were written (a partial apply) + if (EnvVar(L"WRONGGPU_TEST_FAIL_RR_STATE") == L"1") { w = -1; why = L"the settings file could not be written (test)"; } else +#endif + w = WriteRrState(ctx, dir, p, RrDataValid(ctx), &why, hadBefore ? &prevMode : nullptr); + if (w < 0) { + notApplied.push_back(L"the Ray Reconstruction settings (" + why + L")"); + if (applied.empty()) Fail(L"Settings not applied: " + why, EXIT_REFUSED); + // the files this apply changed stay known as WrongGPU's (record hashes, owned files); the profile is not saved + if (recordChanged) SaveRecord(RecordPath(dir), m); + WriteOwnedFiles(dir, m); + wstring a, n; + for (auto& x : applied) a += (a.empty() ? L"" : L"; ") + x; + for (auto& x : notApplied) n += (n.empty() ? L"" : L"; ") + x; + LogLine(ctx, L"settings applied in part to " + dir + L": applied: " + a + L"; not applied: " + n); + Fail(L"Settings applied in part. Applied: " + a + L". Not applied: " + n + L". Apply again once that is fixed.", EXIT_REFUSED); + } if (w > 0) notes.push_back(Join(wgstate::kStateFolder, wgstate::kSettingsFile) + L" written (Ray Reconstruction)"); } if (RrConfigGameFor(m.exe)) { // Borderlands 4, Hogwarts Legacy: the game's Engine.ini follows rr_config_fix (rrconfig.h) @@ -1471,7 +1599,8 @@ OpResult RunOp(Context& ctx, const OpRequest& r, Ui& ui) { Fail(wstring(L"Model ") + chosen + L" can't be chosen. " + ModelNotReady(chosen, why) + L" Nothing was changed.", EXIT_NO_MODEL); } } - if (!r.optiOnly) ApplyProfile(ctx, r.dir, r.hasProfile ? r.profile : GameProfile(r.dir), res.notes, &res.warnings); + if (!r.optiOnly) + ApplyProfile(ctx, r.dir, r.hasProfile ? r.profile : GameProfile(r.dir), res.notes, &res.warnings, r.hasProfile && r.modelChosen); ApplyOptiTab(ctx, r.dir, r, res.notes); res.message = L"Settings applied; they take effect the next time the game starts"; break; diff --git a/clean/installer/src/wg_core/launcher.h b/clean/installer/src/wg_core/launcher.h index aa97acc0..9c82aa4c 100644 --- a/clean/installer/src/wg_core/launcher.h +++ b/clean/installer/src/wg_core/launcher.h @@ -180,6 +180,7 @@ struct OpRequest { std::vector> movePluginsList, moveModsList; bool otherSetupOk = false; // 0.6.1: Clean up / Adopt of WrongGPU files another mod's setup uses, confirmed (--confirm-other-setup) bool hasProfile = false; // apply: this profile (else the game's profile.ini); install: the profile a new install starts with + bool modelChosen = false; // apply: the player applied the profile's model (the launcher's Apply, set model=...): recorded Profile profile; // apply, the OptiScaler tab: edits of editable keys ("Section.Key", value); reset: the editable keys back to what the // install wrote (inikey journal, byte for byte); keep: values OptiScaler's menu saved over the launcher's are kept. @@ -210,7 +211,17 @@ bool NeedsElevation(const wstring& dir); // Writes the profile into the game's files (wronggpu.ini, OptiScaler.ini), the record's hashes of those files and // owned-files.json; saves profile.ini. // warnings: what could not be done that the player should hear (rr_config_fix: the game's Engine.ini, rrconfig.h). -void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings = nullptr); +// modelChosen: the player explicitly applied the profile's model (`set model=`): the game's model choice record +// gets the launcher's choice with the next seq even when the model is the same (clean/fsr/src/model_choice_record.h). +void ApplyProfile(Context& ctx, const wstring& dir, const Profile& p, std::vector& notes, std::vector* warnings = nullptr, + bool modelChosen = false); +// The launcher's model choice into the game's model choice record (wronggpu-setup\model-choice.ini), with the next seq, +// source=launcher. Call it holding the record's lock (wgchoice::Lock). false: not written (said in the notes and warnings). +bool WriteLauncherModelChoice(Context& ctx, const wstring& dir, char model, std::vector& notes, std::vector* warnings); +// The request of the launcher window's Apply (launcher_ui.cpp OnApply calls it; the OptiScaler tab's edits are added there): +// the profile shown, applied, with the model shown as the player's model choice (modelChosen) whenever the build has the +// model setting, also when it is unchanged. `set ... --gui-apply` (a WRONGGPU_TESTING build) runs it for the tests. +OpRequest GuiApplyRequest(const wstring& dir, const Profile& edit); Profile GameProfile(const wstring& dir); // profile.ini, else the profile its wronggpu.ini implies // #219 (0.6.5): the launcher never rewrites the game's wronggpu.ini after the install (the install's defaults, the player's to // edit). The front end's settings it manages go into the game's state folder, wronggpu-setup\settings.ini (wg_state.h), which diff --git a/clean/installer/src/wg_core/profile.cpp b/clean/installer/src/wg_core/profile.cpp index e8986878..bbd01358 100644 --- a/clean/installer/src/wg_core/profile.cpp +++ b/clean/installer/src/wg_core/profile.cpp @@ -355,6 +355,39 @@ bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* return true; } +char ModelOfWronggpuIni(const string& text) { + string options, section; + if (!IniGetFrontEnd(text, "runtime_options", &options, §ion)) return 0; + string m; + for (auto& kv : SplitOptions(options)) if (LowerA(kv.first) == "model") m = TrimA(kv.second); + if (m.size() != 1) return 0; + const char c = char(toupper((unsigned char)m[0])); + return c == 'M' || c == 'K' || c == 'L' ? c : 0; +} + +string SetOptiModelEntry(const string& text, char model) { + const char* index = "0"; +#if WRONGGPU_MODEL_L + if (model == 'L') index = kModelLEntryIndex; +#endif +#if WRONGGPU_MODEL_K || WRONGGPU_PRESET_K + if (model == 'K') index = kModelKEntryIndex; +#endif + // OptiScaler 10's custom upscaler slot: [WrongGPU] (its key, else its section); else [FSR] (the FFX route) + bool slot = IniHasKey(text, "WrongGPU", "UpscalerIndex"); + if (!slot && !IniHasKey(text, "FSR", "UpscalerIndex")) { + size_t at = 0; + while (!slot && at < text.size()) { + size_t end = text.find('\n', at); + if (end == string::npos) end = text.size(); + const string line = LowerA(TrimA(text.substr(at, end - at))); + slot = line == "[wronggpu]"; + at = end + 1; + } + } + return IniSet(text, slot ? "WrongGPU" : "FSR", "UpscalerIndex", index); +} + bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes) { out = in; // the model (WRONGGPU_MODEL_L / WRONGGPU_MODEL_K builds): the entry of WrongGPU's list OptiScaler starts with. OptiScaler diff --git a/clean/installer/src/wg_core/profile.h b/clean/installer/src/wg_core/profile.h index 27329577..0791dd92 100644 --- a/clean/installer/src/wg_core/profile.h +++ b/clean/installer/src/wg_core/profile.h @@ -5,6 +5,7 @@ // (a bad runtime value makes the runtime's create fail and AMD's FSR takes over). Written for this project. #pragma once #include "settings.h" +#include "../../../wgshared/include/wg_model_entries.h" namespace wg { @@ -64,16 +65,16 @@ bool SetSetting(Profile& p, const string& key, const string& value, wstring* why // The refusal of the model setting in a build without the Model L choice (WRONGGPU_MODEL_L off). inline const wchar_t* const kNoModelChoice = L"Model L isn't part of this build of WrongGPU: it comes with a release that runs Model L. The game stays on Model M."; -// The index of Model L's entry in the list of upscalers WrongGPU's front end gives OptiScaler (its UpscalerIndex): after -// Model M and, in a build with Preset K, Model K. +// The indexes of Model K's and Model L's entries in the list of upscalers WrongGPU's front end gives OptiScaler (its +// UpscalerIndex), from the one shared definition (clean/wgshared/include/wg_model_entries.h): Model M, then Model K (a +// build with Model K or Preset K: the front end of the same payload lists it), then Model L. #if WRONGGPU_PRESET_K || WRONGGPU_MODEL_K -inline const char* const kModelLEntryIndex = "2"; +inline constexpr bool kListsModelK = true; #else -inline const char* const kModelLEntryIndex = "1"; +inline constexpr bool kListsModelK = false; #endif -// Model K's entry (a build with the Model K choice, WRONGGPU_MODEL_K): right after Model M's, as the installer's Preset K -// start has always written it. -inline const char* const kModelKEntryIndex = "1"; +inline const char* const kModelKEntryIndex = wgentries::IndexText(wgentries::ModelEntryIndex('K', true, true)); +inline const char* const kModelLEntryIndex = wgentries::IndexText(wgentries::ModelEntryIndex('L', kListsModelK, true)); // ---- wronggpu.ini -------------------------------------------------------------------------------------------- // The runtime_options items in order (split at ';', trimmed, empty items dropped). @@ -90,6 +91,14 @@ std::map EffectiveSettings(const string& wronggpuIni, const stri // false with *why when a profile value does not validate (nothing is rendered then). bool RenderWronggpuIni(const Profile& p, const string& in, string& out, wstring* why); bool RenderOptiIni(const Profile& p, const string& in, string& out, std::vector* notes = nullptr); +// The model a wronggpu.ini text runs: its last runtime_options model item, 'M', 'K' or 'L'; 0 without one. +char ModelOfWronggpuIni(const string& text); +// The OptiScaler.ini text with its UpscalerIndex set to `model`'s entry of WrongGPU's list: 0 Model M, kModelKEntryIndex +// (a build with Model K or Preset K), kModelLEntryIndex (a build with the L choice); a model this build cannot choose: 0. +// [WrongGPU] of OptiScaler 10's custom slot when the file has that key or section, else [FSR]; whatever value was there +// (AMD's version, another one, none: the key is created). The launcher's model choice sets it after the record +// (launcher.cpp ApplyProfile); it is for display only, the front end never takes it for a choice. +string SetOptiModelEntry(const string& text, char model); // The profile a 0.5.x install implies: the effective values of its wronggpu.ini and OptiScaler.ini (defaults and the // stale defaults of earlier versions dropped; upscaler=standin counts as on). Only keys of the settings schema // (kSettings) are taken: developer and test keys (runtime_options items such as timing_log, capture_dir, model_dir, diff --git a/clean/installer/tests/launcher_partial_apply_cases.py b/clean/installer/tests/launcher_partial_apply_cases.py new file mode 100644 index 00000000..77f52799 --- /dev/null +++ b/clean/installer/tests/launcher_partial_apply_cases.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: MIT +"""A partial apply, for run_launcher_tests.py's RR group, which calls run() in its place with a game that has RR installed +(this file keeps that suite below the 256 KB source limit, as launcher_state_cases.py does). + +The RR write fails (the test seam WRONGGPU_TEST_FAIL_RR_STATE of a WRONGGPU_TESTING build) after the upscaler settings were +saved: the apply is refused, and its message says exactly what was applied (the upscaler settings) and what was not (the RR +settings), never "not applied" for what was. The RR settings stay as they were. The same apply without the fault succeeds. +Written for this project.""" + + +def run(t, exe, b, rr_ini, state_kv): + rr_before, sg_before = rr_ini(b), state_kv(b).get("sparkle_guard") + flip = "off" if sg_before == "on" else "on" + t.env["WRONGGPU_TEST_FAIL_RR_STATE"] = "1" + try: + rc = t.run("set", exe, "sparkle_guard=" + flip, "rr_mode=fast") + finally: + del t.env["WRONGGPU_TEST_FAIL_RR_STATE"] + err = t.j.get("error") or t.j.get("message", "") # (an operation's refusal is its message) + t.check("a partial apply (the RR write fails after the upscaler settings were saved): refused (exit 2); the message lists the " + "upscaler settings as applied and the RR settings as not applied; the RR settings unchanged", + rc == 2 and err.startswith("Settings applied in part.") and "Applied: the upscaler settings" in err and + "Not applied: the Ray Reconstruction settings" in err and "Settings not applied" not in err and + state_kv(b).get("sparkle_guard") == flip and rr_ini(b) == rr_before, (rc, err, rr_ini(b))) + rc = t.run("set", exe, "sparkle_guard=" + (sg_before or "off"), "rr_mode=" + rr_before.get("rr_mode", "accurate")) + t.check("...the same apply without the fault: exit 0", rc == 0, (rc, t.j.get("error"))) diff --git a/clean/installer/tests/model_choice_k_tests.cpp b/clean/installer/tests/model_choice_k_tests.cpp index f27a9c32..f3a9f084 100644 --- a/clean/installer/tests/model_choice_k_tests.cpp +++ b/clean/installer/tests/model_choice_k_tests.cpp @@ -90,6 +90,16 @@ int main() { require(EffectiveSettings(toK, "")["model"] == "k" && EffectiveSettings(fresh, "")["model"] == "m", "the file's model: K from its last model item, M otherwise"); require(EffectiveSettings("[fsr]\r\nruntime_options = model=K;model=M\r\n", "")["model"] == "m", "the file's model: the last model item counts"); + // ---- the model choice record's inputs (launcher.cpp ApplyProfile) + require(ModelOfWronggpuIni(toK) == 'K', "ModelOfWronggpuIni: model=K"); + { + string v; + const string toK = SetOptiModelEntry("[WrongGPU]\r\nUpscalerIndex=5\r\n", 'K'); + require(IniHasKey(toK, "WrongGPU", "UpscalerIndex", &v) && v == K, "SetOptiModelEntry: AMD's value to K's entry (1)"); + const string toL = SetOptiModelEntry("[FSR]\r\nUpscalerIndex=0\r\n", 'L'); + require(IniHasKey(toL, "FSR", "UpscalerIndex", &v) && v == (withL ? L : string("0")), + "SetOptiModelEntry: L's entry (2) only with the L choice (else Model M's, 0)"); + } require(EffectiveSettings(withLItem, "")["model"] == (withL ? "l" : "m"), "the file's model: L only with the Model L choice"); // the profile a game's files imply (no profile.ini): K when the files say K (an install that started on Preset K) require(ImportProfile(toK, "").get("model") == "k" && ImportProfile(fresh, "").get("model") == "m", "the imported profile: model=k from model=K"); diff --git a/clean/installer/tests/model_choice_tests.cpp b/clean/installer/tests/model_choice_tests.cpp index 612a32cd..bca5b3f0 100644 --- a/clean/installer/tests/model_choice_tests.cpp +++ b/clean/installer/tests/model_choice_tests.cpp @@ -70,6 +70,28 @@ int main() { require(EffectiveSettings(toL, "")["model"] == "l" && EffectiveSettings(fresh, "")["model"] == "m" && EffectiveSettings(withK, "")["model"] == "m", "the file's model: L from its last model item, M otherwise"); require(EffectiveSettings("[fsr]\r\nruntime_options = model=L;model=M\r\n", "")["model"] == "m", "the file's model: the last model item counts"); + // ---- the model choice record's input (launcher.cpp ApplyProfile: the model the files run) + require(ModelOfWronggpuIni(toL) == 'L' && ModelOfWronggpuIni(fresh) == 'M' && ModelOfWronggpuIni("[fsr]\r\nupscaler = network\r\n") == 0 && + ModelOfWronggpuIni("[fsr]\r\nruntime_options = model=L;model=m\r\n") == 'M' && ModelOfWronggpuIni("[fsr]\r\nruntime_options = model=Q\r\n") == 0, + "ModelOfWronggpuIni: the last model item, M / K / L, else none"); + // ---- the launcher's model choice sets OptiScaler's entry ALWAYS (after the record; display only): from AMD's or any + // other value, and the key created when it is missing; [WrongGPU] of OptiScaler 10's slot, else [FSR] + { + string v; + const string amdSlot = "[WrongGPU]\r\nUpscalerIndex=4\r\n[FSR]\r\nUpscalerIndex=3\r\n"; + const string toLSlot = SetOptiModelEntry(amdSlot, 'L'); + require(IniHasKey(toLSlot, "WrongGPU", "UpscalerIndex", &v) && v == kModelLEntryIndex && IniHasKey(toLSlot, "FSR", "UpscalerIndex", &v) && v == "3", + "SetOptiModelEntry: the slot's index from AMD's value to L's entry; [FSR] (AMD's own) untouched"); + const string toM = SetOptiModelEntry("[FSR]\r\nUpscalerIndex=auto\r\n", 'M'); + require(IniHasKey(toM, "FSR", "UpscalerIndex", &v) && v == "0", "SetOptiModelEntry: another value to Model M's entry (0)"); + const string created = SetOptiModelEntry("[Menu]\r\nShowFps=auto\r\n", 'L'); + require(IniHasKey(created, "FSR", "UpscalerIndex", &v) && v == kModelLEntryIndex && IniHasKey(created, "Menu", "ShowFps"), + "SetOptiModelEntry: no key: created under [FSR], the rest kept"); + const string createdSlot = SetOptiModelEntry("[WrongGPU]\r\nPath=custom\r\n[Menu]\r\nShowFps=auto\r\n", 'M'); + require(IniHasKey(createdSlot, "WrongGPU", "UpscalerIndex", &v) && v == "0" && !IniHasKey(createdSlot, "FSR", "UpscalerIndex"), + "SetOptiModelEntry: a [WrongGPU] section without the key: created there"); + require(SetOptiModelEntry(toLSlot, 'L') == toLSlot, "SetOptiModelEntry: the same entry again changes nothing"); + } // ---- OptiScaler.ini: the entry OptiScaler starts with ----------------------------------------------------------- const string L = kModelLEntryIndex; diff --git a/clean/installer/tests/run_launcher_tests.py b/clean/installer/tests/run_launcher_tests.py index 129b4b64..cebd7b6c 100644 --- a/clean/installer/tests/run_launcher_tests.py +++ b/clean/installer/tests/run_launcher_tests.py @@ -1181,6 +1181,7 @@ def test_rr(t, opti, synth_f): st = t.j.get("settings", {}) t.check("get: the RR settings, profile and file agree; no outside edits", rc == 0 and st.get("rr_mode", {}).get("profile") == "accurate" and st.get("rr_mode", {}).get("file") == "accurate" and st.get("rr_enabled", {}).get("profile") == "on" and not t.j.get("outside_edits"), (st, t.j.get("outside_edits"))) + __import__("launcher_partial_apply_cases").run(t, exe, b, rr_ini, state_kv) # a partial apply (RR write fails) # rc5 (owner 2026-11-05: Fast is the default): a player's rr_mode=accurate survives Repair and Update, never rewritten rc = t.run("repair", exe, "--opti=" + opti, "--noscan", "--force", "--experimental") rcg = t.run("get", exe) diff --git a/clean/installer/tests/run_model_k_tests.py b/clean/installer/tests/run_model_k_tests.py index de469038..2fd29a8f 100644 --- a/clean/installer/tests/run_model_k_tests.py +++ b/clean/installer/tests/run_model_k_tests.py @@ -25,7 +25,7 @@ sys.path.insert(0, HERE) import run_model_l_tests as ml # noqa: E402 (T, the Model L case and the install helpers; it sets WRONGGPU_TESTING) from run_installer_tests import read, write # noqa: E402 -from run_model_l_tests import m_case, l_case, recorded_hash, suite, suite_options_model, upscaler_index # noqa: E402 +from run_model_l_tests import m_case, l_case, recorded_hash, suite, suite_options_model, upscaler_index, choice_record # noqa: E402 def k_case(): @@ -66,8 +66,8 @@ def test_choice(t): rc = t.run("model", "convert", "--preset=K", "--model=" + ksrc) t.check("Model K's data converted (model convert --preset=K)", rc == 0 and ml.holds(t.model_path("K", "model.wgcm"), k_case()), (rc, t.j)) rc = t.run("set", exe, "model=K") - w = read(wini).decode("utf-8", "replace") - t.check("set model=K: exit 0; wronggpu.ini's last model item is model=K", rc == 0 and suite_options_model(w) == "K", (rc, t.j.get("message"), w)) + t.check("set model=K: exit 0; wronggpu.ini byte for byte as the install wrote it (the model is the record's, never written there)", + rc == 0 and read(wini) == m_w, (rc, t.j.get("message"), read(wini)[-200:])) o = read(oini).decode("utf-8", "replace") t.check("...OptiScaler's UpscalerIndex names Model K's entry (1: right after Model M)", upscaler_index(o) == "1", o) t.check("...the record's hashes follow both files (the file-ownership rule: they are WrongGPU's writes)", @@ -75,8 +75,13 @@ def test_choice(t): (recorded_hash(b, "wronggpu.ini"), recorded_hash(b, "OptiScaler.ini"))) t.check("...profile.ini says model=k", b"model=k\r\n" in profile_text(b)) k_w, k_o = read(wini), read(oini) + r1 = choice_record(b) + t.check("...the model choice record: exactly model=K, seq, source=launcher", + r1.get("model") == "K" and r1.get("source") == "launcher" and sorted(r1) == ["model", "seq", "source"], r1) rc = t.run("set", exe, "model=K") - t.check("set model=K again: nothing changes", rc == 0 and read(wini) == k_w and read(oini) == k_o, rc) + r2 = choice_record(b) + t.check("set model=K again: wronggpu.ini and OptiScaler.ini unchanged; the record's seq grows (the newest choice)", + rc == 0 and read(wini) == k_w and read(oini) == k_o and int(r2.get("seq", "0")) == int(r1.get("seq", "0")) + 1, (rc, r1, r2)) rc = t.run("get", exe, "model") t.check("get model: k", rc == 0 and t.j.get("settings", {}).get("model", {}).get("profile") == "k", t.j.get("settings")) rc = t.run("set", exe, "model=M") @@ -89,11 +94,11 @@ def test_choice(t): rc = t.run("model", "convert", "--preset=L", "--model=" + lsrc) t.check("L control: Model L's data converted", rc == 0, (rc, t.j)) rc = t.run("set", exe, "model=L") - t.check("L control: set model=L writes model=L and index 2 (after Model K's entry)", - rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "L" and upscaler_index(read(oini).decode("utf-8", "replace")) == "2", - (rc, t.j.get("message"), read(wini), read(oini))) + t.check("L control: set model=L records L and sets index 2 (after Model K's entry); wronggpu.ini unchanged", + rc == 0 and choice_record(b).get("model") == "L" and upscaler_index(read(oini).decode("utf-8", "replace")) == "2" and read(wini) == m_w, + (rc, t.j.get("message"), choice_record(b), read(oini))) rc = t.run("set", exe, "model=K") - t.check("L to K: model=K and index 1", rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "K" and + t.check("L to K: record K and index 1", rc == 0 and choice_record(b).get("model") == "K" and upscaler_index(read(oini).decode("utf-8", "replace")) == "1", (rc, t.j.get("message"))) rc = t.run("set", exe, "model=L") rc2 = t.run("set", exe, "model=M") @@ -103,16 +108,16 @@ def test_choice(t): os.remove(os.path.join(t.lad, "WrongGPU", "model", "K", "model.wgcm")) rc = t.run("repair", exe, "--opti=" + opti, "--force") msgs = " ".join(t.j.get("warnings", []) + t.j.get("notes", [])) - t.check("repair of a game set to K without Model K's data: exit 0, the files say Model M, the player is told how to convert it", - rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "M" and "Model K's data on this PC is not ready" in msgs and - "model convert --preset=K" in msgs, (rc, t.j.get("message"), msgs[:600])) + t.check("repair of a game set to K without Model K's data: exit 0, the record says Model M, the player is told how to convert it", + rc == 0 and choice_record(b).get("model") == "M" and "Model K's data on this PC is not ready" in msgs and + "model convert --preset=K" in msgs, (rc, t.j.get("message"), msgs[:600], choice_record(b))) t.check("...the choice stays in profile.ini (model=k)", b"model=k\r\n" in profile_text(b)) rc = t.run("uninstall", exe) - # A build with Preset K seeds the plugin's own settings file wronggpu-asi.ini on every OptiScaler install; an uninstall leaves - # it in place and lists it (optiscaler.h SeedAsiSelection), as it did before the K choice. Nothing else may differ. + # A build with Preset K seeds the plugin's own settings file wronggpu-asi.ini on every OptiScaler install; since #224 the + # install records it as WrongGPU's, and an uninstall removes it while nobody changed it (install.cpp). Nothing may differ. left = suite.diff(before, suite.snapshot(root)) - t.check("uninstall: the game folder byte for byte as before the install, except the plugin's own wronggpu-asi.ini", - rc == 0 and left.startswith("bin/x64/wronggpu-asi.ini: absent -> ") and ";" not in left, (rc, left)) + t.check("uninstall: the game folder byte for byte as before the install (the seeded wronggpu-asi.ini removed with it)", + rc == 0 and left == "", (rc, left)) def main(): diff --git a/clean/installer/tests/run_model_l_tests.py b/clean/installer/tests/run_model_l_tests.py index 0a51ca91..d9df4fdd 100644 --- a/clean/installer/tests/run_model_l_tests.py +++ b/clean/installer/tests/run_model_l_tests.py @@ -25,6 +25,7 @@ import shutil import subprocess import sys +import time os.environ["WRONGGPU_TESTING"] = "1" HERE = os.path.dirname(os.path.abspath(__file__)) @@ -218,6 +219,23 @@ def upscaler_index(text): return found.get("wronggpu", found.get("fsr")) +def set_upscaler_index(text, value): + """OptiScaler.ini text with the UpscalerIndex WrongGPU manages ([WrongGPU] when there, else [FSR]) set to `value` (None: the + line removed): a player's change in the game. Other lines, and every line's own ending, stay.""" + lines = text.splitlines(keepends=True) + target = "wronggpu" if any(s.strip().lower() == "[wronggpu]" for s in lines) else "fsr" + out, sec = [], None + for line in lines: + if line.strip().startswith("["): + sec = line.strip().strip("[]").lower() + if sec == target and line.strip().lower().startswith("upscalerindex") and "=" in line: + if value is None: + continue + line = "UpscalerIndex=" + value + line[len(line.rstrip("\r\n")):] + out.append(line) + return "".join(out) + + def recorded_hash(b, name): """The hash the install record holds for a recorded file (its copy entry: action existed orig inst rel).""" for line in read(os.path.join(b, "wronggpu-setup", "install.record")).decode("utf-8", "replace").replace("\r", "").split("\n"): @@ -227,6 +245,22 @@ def recorded_hash(b, name): return None +def choice_record(b): + """The game's model choice record (wronggpu-setup\\model-choice.ini; clean/fsr/src/model_choice_record.h) as a dict, {} without one.""" + p = os.path.join(b, "wronggpu-setup", "model-choice.ini") + if not os.path.exists(p): + return {} + r = {} + for line in read(p).decode("utf-8", "replace").splitlines(): + if line and not line.startswith(";") and "=" in line: + k, v = line.split("=", 1) + r[k] = v + return r + + +RECORD_TOOL = None # --record-tool + + def test_choice(t): """The launcher's Model L choice (a build with WRONGGPU_MODEL_L on and the test map): set model=L/M on an installed game. L only with Model L's data on this PC; it writes wronggpu.ini's model item and OptiScaler's UpscalerIndex, the @@ -255,26 +289,149 @@ def test_choice(t): rc = t.run("model", "convert", "--preset=L", "--model=" + lsrc) t.check("Model L's data converted (model convert --preset=L)", rc == 0, (rc, t.j)) rc = t.run("set", exe, "model=L") - w = read(wini).decode("utf-8", "replace") - t.check("set model=L: exit 0; wronggpu.ini's last model item is model=L", rc == 0 and suite_options_model(w) == "L", (rc, t.j.get("message"), w)) + t.check("set model=L: exit 0; wronggpu.ini byte for byte as the install wrote it (the model is the record's, never written there)", + rc == 0 and read(wini) == m_w, (rc, t.j.get("message"), read(wini)[-200:])) t.check("...OptiScaler's UpscalerIndex names Model L's entry (1: after Model M in a build without Preset K)", upscaler_index(read(oini).decode("utf-8", "replace")) == "1", read(oini).decode("utf-8", "replace")) t.check("...the record's hashes follow both files (the file-ownership rule: they are WrongGPU's writes)", recorded_hash(b, "wronggpu.ini") == hashlib.sha256(read(wini)).hexdigest() and recorded_hash(b, "OptiScaler.ini") == hashlib.sha256(read(oini)).hexdigest(), (recorded_hash(b, "wronggpu.ini"), recorded_hash(b, "OptiScaler.ini"))) t.check("...profile.ini says model=l", b"model=l\r\n" in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) + r1 = choice_record(b) + t.check("...the model choice record: exactly model=L, seq, source=launcher", r1.get("model") == "L" and + r1.get("source") == "launcher" and r1.get("seq", "").isdigit() and sorted(r1) == ["model", "seq", "source"], r1) + rc = t.run("set", exe, "model=L") + r2 = choice_record(b) + t.check("set model=L again: the record's seq grows (the newest choice); wronggpu.ini and OptiScaler.ini unchanged", + rc == 0 and r2.get("model") == "L" and int(r2.get("seq", "0")) == int(r1.get("seq", "0")) + 1 and read(wini) == m_w, (r1, r2)) + # an explicit model choice in the launcher (set model=..., or the launcher's Apply) wins over a NEWER choice made in the + # game even when the profile's model is unchanged; a launcher change of another setting does not touch the record + rec_path = os.path.join(b, "wronggpu-setup", "model-choice.ini") + newer = int(r2.get("seq", "0")) + 1 + write(rec_path, ("model=M\r\nseq=%d\r\nsource=plugin\r\n" % newer).encode("ascii")) + o_before = read(oini) + rc = t.run("set", exe, "fps_overlay=on") + t.check("set fps_overlay=on: the plugin's newer choice (M) stays the record", rc == 0 and choice_record(b) == {"model": "M", "seq": str(newer), "source": "plugin"}, + (rc, choice_record(b))) + rc = t.run("set", exe, "fps_overlay=keep") # ("keep" leaves the key as it is: the file goes back by hand, and + write(oini, o_before) # the next model choice rewrites it and its hash) + rc = t.run("set", exe, "model=L") + r2b = choice_record(b) + t.check("set model=L (the profile already says L) after the plugin's newer M: L is recorded with the next seq", + rc == 0 and r2b.get("model") == "L" and r2b.get("source") == "launcher" and int(r2b.get("seq", "0")) == newer + 1, r2b) + # the launcher window's Apply (the request its button makes, GuiApplyRequest, run by `set ... --gui-apply`): the model + # shown is a choice even unchanged, so it wins over a newer choice made in the game + newer = int(r2b.get("seq", "0")) + 1 + write(rec_path, ("model=M\r\nseq=%d\r\nsource=ffx\r\n" % newer).encode("ascii")) + rc = t.run("set", exe, "fps_overlay=keep", "--gui-apply") + r2c = choice_record(b) + t.check("the launcher's Apply with the unchanged model L after a newer choice in OptiScaler's list (M): L is recorded with the next seq", + rc == 0 and r2c.get("model") == "L" and r2c.get("source") == "launcher" and int(r2c.get("seq", "0")) == newer + 1 and read(wini) == m_w, + (rc, r2c)) + r2 = r2c + # the menu plugin's file as the player made it, with comments, on AMD (selection=amd): an explicit model choice changes + # only its selection line (every other byte stays) and does not claim it (its ownership stays as recorded) + asi = os.path.join(b, "wronggpu-asi.ini") + had_asi, asi_owner = os.path.exists(asi), recorded_hash(b, "wronggpu-asi.ini") + asi_was = read(asi) if had_asi else None + write(asi, b"# mine: AMD for screenshots\r\n Selection = AMD \r\n; keep this\n") + rc = t.run("set", exe, "model=L") + t.check("set model=L over the player's wronggpu-asi.ini on AMD: only its selection line changes (to Model L), the player's " + "comments and line ends stay, its ownership in the install record unchanged", + rc == 0 and read(asi) == b"# mine: AMD for screenshots\r\nselection=wronggpu-l\r\n; keep this\n" and + recorded_hash(b, "wronggpu-asi.ini") == asi_owner, (rc, read(asi), asi_owner, recorded_hash(b, "wronggpu-asi.ini"))) + if had_asi: + write(asi, asi_was) # (as the install left it) + else: + os.remove(asi) # (the player's file: the uninstall below would rightly keep it) + r2 = choice_record(b) rc = t.run("set", exe, "model=M") t.check("set model=M: wronggpu.ini and OptiScaler.ini back byte for byte as the install wrote them", rc == 0 and read(wini) == m_w and read(oini) == m_o, (rc, read(wini)[-200:], read(oini)[-200:])) t.check("...profile.ini has no model line again", b"model=" not in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) + r3 = choice_record(b) + t.check("...the record: model=M, source=launcher, the next seq", r3.get("model") == "M" and r3.get("source") == "launcher" and + int(r3.get("seq", "0")) == int(r2.get("seq", "0")) + 1, r3) + # the launcher's model choice ALWAYS sets OptiScaler's entry, after the record: from AMD's value (5), and the key created + # when it is missing + write(oini, set_upscaler_index(read(oini).decode("utf-8", "replace"), "5").encode("utf-8")) + rc = t.run("set", exe, "model=M") + r4 = choice_record(b) + t.check("set model=M over AMD's entry (5): OptiScaler's entry is Model M's again (0); the record's seq grows", + rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "0" and r4.get("model") == "M" and + int(r4.get("seq", "0")) == int(r3.get("seq", "0")) + 1, (rc, r4, read(oini)[-300:])) + write(oini, set_upscaler_index(read(oini).decode("utf-8", "replace"), None).encode("utf-8")) + rc = t.run("set", exe, "model=L") + t.check("set model=L without an UpscalerIndex key: the key is created with Model L's entry (1)", + rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "1" and choice_record(b).get("model") == "L", + (rc, read(oini)[-300:])) + # an apply interrupted between the record and OptiScaler.ini (a crash): the record has the choice, the entry is stale, + # which is harmless (the front end never takes the entry for a choice); the next apply sets the entry + write(oini, set_upscaler_index(read(oini).decode("utf-8", "replace"), "5").encode("utf-8")) + r5 = choice_record(b) + t.env["WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD"] = "1" + rc = t.run("set", exe, "model=L") + t.env.pop("WRONGGPU_TEST_STOP_AFTER_CHOICE_RECORD") + r6 = choice_record(b) + t.check("set model=L stopped after the record (exit 97): the record has L with the next seq, OptiScaler's entry is still 5", + rc == 97 and r6.get("model") == "L" and r6.get("source") == "launcher" and int(r6.get("seq", "0")) == int(r5.get("seq", "0")) + 1 and + upscaler_index(read(oini).decode("utf-8", "replace")) == "5", (rc, r5, r6)) + rc = t.run("set", exe, "model=L") + t.check("...the next set model=L: OptiScaler's entry is Model L's (1) again, the record's seq grows", + rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "1" and int(choice_record(b).get("seq", "0")) == int(r6.get("seq", "0")) + 1, + (rc, choice_record(b))) + rc = t.run("set", exe, "model=M") + t.check("...set model=M: wronggpu.ini back byte for byte as the install wrote it, OptiScaler's entry Model M's (0; the key the player" + " removed was created again, so OptiScaler.ini differs only in where that line is)", + rc == 0 and read(wini) == m_w and upscaler_index(read(oini).decode("utf-8", "replace")) == "0" and + sorted(read(oini).split(b"\r\n")) == sorted(m_o.split(b"\r\n")), + (rc, read(wini) == m_w, set(read(oini).split(b"\r\n")) ^ set(m_o.split(b"\r\n")), read(wini)[-200:])) + # OptiScaler.ini missing: the model choice is still saved, and the player is told OptiScaler's list could not be updated + os.replace(oini, oini + ".away") + r7 = choice_record(b) + rc = t.run("set", exe, "model=L") + msgs = " ".join(t.j.get("warnings", []) + t.j.get("notes", [])) + t.check("set model=L without OptiScaler.ini: exit 0, the record has L with the next seq, and it says OptiScaler's list couldn't be updated", + rc == 0 and choice_record(b).get("model") == "L" and int(choice_record(b).get("seq", "0")) == int(r7.get("seq", "0")) + 1 and + "OptiScaler's list couldn't be updated; the model choice is saved" in msgs and not os.path.exists(oini), (rc, msgs[:400], choice_record(b))) + os.replace(oini + ".away", oini) + rc = t.run("set", exe, "model=M") + t.check("...set model=M with OptiScaler.ini back: its entry is Model M's (0)", rc == 0 and upscaler_index(read(oini).decode("utf-8", "replace")) == "0", rc) + # the front end's upgrade migration (no record yet) against a REAL launcher apply in another process: the launcher holds the + # game's state lock (test hook: it pauses after reading the record, before writing it); the migration, started then, waits + # for the lock and finds the launcher's record (L), so it writes nothing (without the lock it would have written M first) + if RECORD_TOOL: + os.remove(rec_path) + sig = os.path.join(t.work, "choice-lock.signal") + if os.path.exists(sig): + os.remove(sig) + if os.path.exists(t.out): + os.remove(t.out) + env = dict(t.env, WRONGGPU_TEST_PAUSE_IN_CHOICE_LOCK=sig + "|1500") + cmd = [t.exe, "set", exe, "model=L", "--noscan", "--log=" + t.log, "--out=" + t.out, "--data=" + os.path.join(t.work, "data")] + launcher = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + for _ in range(500): + if os.path.exists(sig): + break + time.sleep(0.01) + mig = subprocess.run([RECORD_TOOL, "migrate", b], env=t.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60) + lrc = launcher.wait(timeout=120) + out = mig.stdout.decode("utf-8", "replace").strip() + rr = choice_record(b) + t.check("migration against a real launcher apply holding the lock: the launcher records L (seq 1), the migration waits and writes nothing", + os.path.exists(sig) and lrc == 0 and mig.returncode == 0 and out == "migrate: ok model=L seq=1 migrated=0" and + rr == {"model": "L", "seq": "1", "source": "launcher"}, (lrc, mig.returncode, out, rr)) + else: + print(" (the migration race against a real launcher apply: no --record-tool given, not run)") # a game saved on L whose data goes away: a repair keeps the player's choice, the files say Model M with a warning rc = t.run("set", exe, "model=L") os.remove(os.path.join(t.lad, "WrongGPU", "model", "L", "model.wgcm")) # (t.model is the case here, not the path helper) rc = t.run("repair", exe, "--opti=" + opti, "--force") msgs = " ".join(t.j.get("warnings", []) + t.j.get("notes", [])) - t.check("repair of a game set to L without Model L's data: exit 0, the files say Model M, the player is told how to convert it", - rc == 0 and suite_options_model(read(wini).decode("utf-8", "replace")) == "M" and "Model L's data on this PC is not ready" in msgs and - "model convert --preset=L" in msgs, (rc, t.j.get("message"), msgs[:600])) + t.check("repair of a game set to L without Model L's data: exit 0, the record says Model M (the launcher's own choice can't run)," + " the player is told how to convert it", + rc == 0 and choice_record(b).get("model") == "M" and choice_record(b).get("source") == "launcher" and + "Model L's data on this PC is not ready" in msgs and "model convert --preset=L" in msgs, (rc, t.j.get("message"), msgs[:600], choice_record(b))) t.check("...the choice stays in profile.ini (model=l)", b"model=l\r\n" in read(os.path.join(b, "wronggpu-setup", "profile.ini"))) rc = t.run("uninstall", exe) t.check("uninstall: the game folder byte for byte as before the install", rc == 0 and suite.snapshot(root) == before, (rc, suite.diff(before, suite.snapshot(root)))) @@ -321,7 +478,11 @@ def main(): ap.add_argument("--reference-launcher", help="WrongGPU.exe of the base branch (same payload and test map)") ap.add_argument("--launcher-choice", help="WrongGPU.exe built with -DWRONGGPU_MODEL_L=ON and the test map (the model choice)") ap.add_argument("--work", default=os.path.join(HERE, "..", "build-tests", "model-l")) + ap.add_argument("--record-tool", help="clean/fsr's test_model_choice_record.exe: the front end's upgrade migration in its own " + "process, for the race against a real launcher apply (skipped without it)") a = ap.parse_args() + global RECORD_TOOL + RECORD_TOOL = os.path.abspath(a.record_tool) if a.record_tool else None if a.write_test_map: write(a.write_test_map, map_bytes(l_case())) print("test map: " + a.write_test_map) diff --git a/clean/wgshared/include/wg_model_entries.h b/clean/wgshared/include/wg_model_entries.h new file mode 100644 index 00000000..b0966641 --- /dev/null +++ b/clean/wgshared/include/wg_model_entries.h @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT +#pragma once +// The ONE definition of where WrongGPU's model entries are in the list of upscaler versions the front end gives a host +// (FFX_API_QUERY_DESC_TYPE_GET_VERSIONS: frontend.cpp ListVersions, from the registry's SR model rows). A host such as +// OptiScaler stores the player's entry as its position in that list (UpscalerIndex; OptiScaler shows the list sorted, but +// the index it stores is the position in the list the DLL returned), so this order is what the launcher writes: +// Model M first, then Model K (a build with Model K), then Model L (a build with Model L). +// The launcher (profile.h: kModelKEntryIndex / kModelLEntryIndex) and the front end use it; test_frontend +// (TestModelEntryOrder) fails when the list ListVersions returns and this order disagree, for each build's K / L flags. +// The index is for display only: which model runs is the model choice record's (clean/fsr/src/model_choice_record.h). + +namespace wgentries { + +// The position of `model`'s entry ('M', 'K', 'L') in a build with or without Model K and Model L; -1 when the build does +// not list that model. +constexpr int ModelEntryIndex(char model, bool withK, bool withL) { + return model == 'M' ? 0 : model == 'K' ? (withK ? 1 : -1) : model == 'L' ? (withL ? (withK ? 2 : 1) : -1) : -1; +} + +// The same as the decimal text an ini holds ("0", "1", "2"; nullptr for -1). +constexpr const char* IndexText(int index) { return index == 0 ? "0" : index == 1 ? "1" : index == 2 ? "2" : nullptr; } + +} // namespace wgentries diff --git a/clean/wgshared/include/wg_state.h b/clean/wgshared/include/wg_state.h index 31aebd24..8fc60083 100644 --- a/clean/wgshared/include/wg_state.h +++ b/clean/wgshared/include/wg_state.h @@ -674,13 +674,14 @@ inline Settings ParseSettings(const std::string& in) { } return s; } -// The file's text: a new file (nothing read) starts with a comment saying what it is; a read one keeps its BOM and every line -// with its own line end, the changed keys rewritten and new keys at the end. No stamp (UpdateSettings adds it when the file is -// WrongGPU's). -inline std::string RenderSettings(const Settings& s) { +// The file's text: a new file (nothing read) starts with a comment saying what it is (newFileHeader: complete lines; null: +// settings.ini's); a read one keeps its BOM and every line with its own line end, the changed keys rewritten and new keys at +// the end. No stamp (UpdateStateFile adds it when the file is WrongGPU's). +inline std::string RenderSettings(const Settings& s, const char* newFileHeader = nullptr) { std::string out = s.bom ? "\xEF\xBB\xBF" : ""; if (!s.present && s.lines.empty()) { - out += "; WrongGPU: settings chosen in the launcher or in a WrongGPU menu in the game (they take precedence over wronggpu.ini)\r\n"; + out += newFileHeader ? newFileHeader + : "; WrongGPU: settings chosen in the launcher or in a WrongGPU menu in the game (they take precedence over wronggpu.ini)\r\n"; for (const auto& p : s.kv) out += p.first + "=" + p.second + "\r\n"; return out; } @@ -780,7 +781,11 @@ using SettingsDecision = std::function kMaxStateBytes) { o.write.error = ERROR_FILE_TOO_LARGE; return fail(SetResult::WriteFailed, ERROR_FILE_TOO_LARGE); } @@ -868,6 +873,9 @@ inline SetOutcome UpdateSettings(const std::wstring& gameDir, const SettingsDeci o.written = true; return o; } +inline SetOutcome UpdateSettings(const std::wstring& gameDir, const SettingsDecision& decide, DWORD waitMs = kDefaultWaitMs) { + return UpdateStateFile(gameDir, kSettingsFile, decide, waitMs, nullptr); +} // UpdateSettings with fixed changes (a key already at its value is not written again). inline SetOutcome SetSettings(const std::wstring& gameDir, const std::vector>& changes, DWORD waitMs = kDefaultWaitMs) { for (const auto& c : changes) diff --git a/tools/ci/check_vendored_model_entries.py b/tools/ci/check_vendored_model_entries.py new file mode 100644 index 00000000..65b18579 --- /dev/null +++ b/tools/ci/check_vendored_model_entries.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: MIT +"""Vendored-copy check (CI): OptiScaler WrongGPU edition holds a byte-identical copy of +clean/wgshared/include/wg_model_entries.h (the order of WrongGPU's model entries in the version list its FFX DLL gives a +host; OptiScaler stores the player's entry as a position in that list). The two must never differ. + +This check fails when + - clean/wgshared/include/wg_model_entries.h no longer has the SHA-256 pinned below (a change to the order needs the + fork's copy updated first, then FORK_COMMIT and HEADER_SHA256 here), or + - the fork's copy at FORK_COMMIT is not byte-identical to it (fetched from GitHub; --offline skips this part). +Run from the repository root: python tools/ci/check_vendored_model_entries.py [--offline] +""" +import hashlib +import subprocess +import sys +import urllib.request +from pathlib import Path + +HEADER = 'clean/wgshared/include/wg_model_entries.h' +HEADER_SHA256 = 'dbc42cf67378a610c35935829683f3928a98e83f1bfb49b53e1f36152da9ab4f' +FORK_REPO = 'phantoslayer21/OptiScaler' +FORK_COMMIT = 'f31d091df2989f70c1e4ab296942de69240af227' +FORK_PATH = 'OptiScaler/include/wronggpu/wg_model_entries.h' + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +def main(argv): + root = Path(subprocess.check_output(['git', 'rev-parse', '--show-toplevel'], text=True).strip()) + ours = (root / HEADER).read_bytes() + problems = [] + + if sha256(ours) != HEADER_SHA256: + problems.append('%s has SHA-256 %s, pinned %s: update the fork\'s copy (%s), then FORK_COMMIT and ' + 'HEADER_SHA256 in this script' % (HEADER, sha256(ours), HEADER_SHA256, FORK_PATH)) + + if '--offline' not in argv: + url = 'https://raw.githubusercontent.com/%s/%s/%s' % (FORK_REPO, FORK_COMMIT, FORK_PATH) + try: + with urllib.request.urlopen(url, timeout=60) as r: + theirs = r.read() + except OSError as e: + problems.append('could not fetch the fork\'s copy (%s): %s' % (url, e)) + else: + if theirs != ours: + problems.append('the fork\'s copy at %s (SHA-256 %s) differs from %s (SHA-256 %s)' + % (FORK_COMMIT[:12], sha256(theirs), HEADER, sha256(ours))) + + for p in problems: + print('FAIL: ' + p) + if problems: + return 1 + print('vendored wg_model_entries.h: %s matches the pin%s' % (HEADER, '' if '--offline' in argv else + ' and the fork\'s copy at ' + FORK_COMMIT[:12])) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:]))