fix: SK engine and launcher fixes from 2026-10-14

- fix(engine): DAT share hook now patches only the CreateFile imports of
  acclient.exe and MSVCR70.dll instead of hooking kernel32 process-wide, so
  Direct3D and driver file opens are no longer routed through the detour
  ("Could not initialize Direct3D" on some machines). Uninstall restores the
  import slots on engine unload.
- fix(launcher): a saved UserPreferences.ini that makes the client exit
  within 30 s is quarantined and the previous live file is restored.
- fix(engine): target selects and attacks run during the gesture defer.
- feat(launcher): first login on a new server; pick any character on the
  account.
- feat(settings): loot timers show their optimized defaults, with a
  "Use optimized defaults" button.

Release notes are in Changelog/2026-10-14-*.md.
This commit is contained in:
BlankenshipG 2026-10-14 22:35:26 -04:00
commit 8919f7f169
25 changed files with 1373 additions and 163 deletions

View file

@ -0,0 +1,61 @@
# 2026.10.5.61 - engine: DAT share hook no longer intercepts Direct3D and driver file opens
Previous release: 2026.10.5.60.
## Problem
On one PC every RynthCore launch ended with "Could not initialize Direct3D. Please ensure that
DirectX 9.0 or higher is installed." (twice), then "The game encountered a fatal DirectX issue
while attempting to start...", and AC exited with code 1 about 6 seconds in. The same client
started from another launcher (no engine) worked. 2026.10.5.60 (saved UserPreferences.ini
recovery) did not change it.
In all three logs (builds 2026.10.14.2 and 2026.10.5.60) the error came 27-36 ms after the
engine started loading RynthChat, the plugin right after RynthAi. RynthAi took 378, 390 and
1175 ms to load, and the error moved with it, so AC's device creation was waiting on the engine
and failed as soon as it continued.
The DAT share hook (on with "Allow multiple clients") detoured the kernel32 `CreateFileA` and
`CreateFileW` exports with MinHook. That caught every caller in the process, including
d3d9.dll and the GPU driver, which open files (shader caches) while AC creates its device. Each
of those opens ran through managed code, which can wait on the runtime while plugins load, and
the detour did not hand back the Win32 last error: callers read it even after a successful
CreateFile (ERROR_ALREADY_EXISTS with OPEN_ALWAYS), and on some drivers that fails device
creation.
## Change
- The hook patches only the import slots of the modules that open AC's data files:
`acclient.exe` (imports CreateFileA) and its CRT `MSVCR70.dll` (CreateFileA/W, used by
fopen/_wfopen; the "W" DAT lines in the log come from here). Direct3D, drivers, the runtime
and plugins call CreateFile without the engine in the way.
- The detour sets the Win32 last error back to the value CreateFile left before returning.
- The import slots are written back at engine shutdown (new step
`DatFileShareHooks.Uninstall`), because the detours belong to the engine generation that hot
reload unloads.
- A detour calls whatever its slot held before, so a Decal detour on the kernel32 export still
runs.
- The startup log now lists the hooked slots, for example
`Compat: DAT share - hooked MSVCR70.dll!CreateFileW import (...)`, and the DAT open lines
(`Compat: DAT share - W [filtered]: client_portal.dat ...`) still appear when multi-client is
on.
## Code
- `src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs`: MinHook export hooks replaced by
IAT slot hooks (`HookModuleImports`, `InstallSlot`, `Uninstall`, `IatHook` record); detours
take the slot's original delegate and restore the last error (`SetWin32LastError`).
- `src/RynthCore.Engine/EngineLifecycle.cs`: `DatFileShareHooks.Uninstall` before
`MH_DisableHook(ALL)`.
## Tests
- `dotnet build src\RynthCore.Engine\RynthCore.Engine.csproj -c Release`: 0 errors, no new
warnings. No test project covers the hook; it needs a running client.
- Import tables checked on this PC: `acclient.exe` imports `KERNEL32!CreateFileA` (and
`CreateFileMappingA`); `MSVCR70.dll` imports `KERNEL32!CreateFileA` and `CreateFileW`.
## For an affected PC before updating
Set `"EnableDatShareHook": false` in `%APPDATA%\RynthCore\engine.json` (or turn off "Allow
multiple clients"), then launch. If the client starts, this hook was the cause.

View file

@ -0,0 +1,88 @@
# 2026.10.5.58 - launcher: first login on a new server, every character on the account
Previous release: 2026.10.5.57. Launcher project version 0.1.6 (was 0.1.5).
## Problem
An account set up for a new server never got in. The `SK` profile (Conquest,
`acconquest.ddns.net:9000`, and earlier Aelrynth) had no password saved, so
the launcher started the client with `-v ""`. The client refuses an empty
password before it connects: it shows "You can only run the game from the
launcher program" and exits about 4 seconds later. All six `SK` launches in the
logs (Aelrynth, 2026-10-13 08:31 to 23:47; Conquest, 23:48) ended this way, and
the launcher only recorded each one as a crash.
An empty password would fail on the server too. ACE creates a new account on its
first login (`AllowAutoAccountCreation`), but only when a password is sent, and
it boots a login without one.
Also:
- A new account profile had no server picked unless you chose one, and the
launch list then put it on the first server profile.
- The launch list showed "(None - no auto-login) | offline" as if it were a
character name.
## Change
- **First Login dialog.** A manual launch of an account with no usable password
(none saved, or one that can't be decrypted on this Windows user) asks for it
first, instead of starting a client that can only fail. It has:
- An optional list of the account names used in your other profiles, to pick
an account you already have.
- The account name. On ACE, a new name creates the account on this first
login, if the server allows it.
- A password with confirmation, saved encrypted like the other accounts. If
another profile has the same account name with a saved password, a checkbox
reuses it (the encrypted copy is copied, never the plain text).
- "Log in as": stop at character select, or any character already known for
the account.
Cancelling skips that account and logs why. Automatic launches don't show the
dialog. They skip the account, logging it at most once every 5 minutes.
- **Characters on the account.** With no character chosen, the client stops at
character select, where you can create characters. The engine already saves
the account's character list from character select, including newly created
characters.
- Stopping at character select before any character is known saves an empty
choice, not "(None)". Once the first character exists and is the only one,
the next launch logs it in.
- With several characters, the launch list's dropdown, and the new "Log in as"
in Edit Account, list them all. You pick which one logs in, or stop at
character select.
- **Account Profile dialog.**
- New "Log in as" list.
- A new account defaults to the server selected in the list.
- A server must be picked when there are server profiles.
- Account names over 50 characters (ACE's limit), or with ':' on GDLE (whose
login argument is `account:password`), are refused.
- **Launch list status.** "Needs password | launch to set up" for an account
without one, and "Character select" instead of the "(None)" text.
- **Never an empty password.**
- `AcLaunchArgumentBuilder.BuildArguments` refuses to build a command line with
an empty password, with the reason.
- The launch preview says the password is missing instead of showing `-v ""`.
- `RynthCore.Injector launch` refuses too.
## Tests
- tools/LauncherSettingsTests: 152 checks pass.
- The old checks that an account without a password "still launches as before
(empty)" now check that it's refused, with the reason, on ACE and GDLE.
- New: account-name checks, and a "first login on a new server" scenario:
- known account names
- reusing another profile's saved password (the copied encrypted password
still decrypts)
- the Log in as choices and what each saves
- the dialog's input checks
- tools/AelrynthTests: 89/89.
- The launcher and the injector build. The dialogs were not shown in a test run.
## Files
- `src/RynthCore.App/FirstLoginRules.cs` (new), `AcLaunchArgumentBuilder.cs`, `LaunchAccountProfile.cs`
- `src/RynthCore.App.Avalonia/FirstLoginDialog.axaml` and `.axaml.cs` (new)
- `src/RynthCore.App.Avalonia/AccountProfileDialog.axaml` and `.axaml.cs`, `MainWindow.axaml.cs`,
`RynthCore.App.Avalonia.csproj`
- `src/RynthCore.Injector/LaunchCommand.cs`
- `tools/LauncherSettingsTests/Program.cs`, `LauncherSettingsTests.csproj`

View file

@ -0,0 +1,41 @@
# 2026.10.5.57 - attacks and target selects no longer wait behind gestures
Previous release: 2026.10.5.56.
Goes with RynthAi 0.5.64-legacy-ui (fewer weapon swaps, faster point-blank
stall recovery: `RynthSuite/Changelog/2026-10-14-combat-speed-swaps-stalls-0.5.64.md`).
## Problem
While a gesture is in flight (the CMotionInterp pending-motion list is not
empty), `AcMainThreadQueue` defers the whole action ring for up to
`DrainDeferMaxMs` (2.5 s). With a crossbow or bow, a gesture is in flight
nearly all the time. In Silentkelpie's 2026-10-14 logs, target selects and
attacks ran 1.0-1.9 s late, and some attacks went past the 1.5 s stale limit
and were dropped.
## Change
- New `AcMainThreadQueue.RunsDuringGesture`. The retail client does these from
a key press at any moment, swing or not, so they now run during the defer:
- `SetSelectedObject` (the target select).
- `NativeAttack` (ClientCombatSystem StartAttackRequest / EndAttackRequest,
which the client itself holds until the motion allows it).
- `CancelAttack` (the 0x1B7 packet).
- These run from the head of the ring up to the first entry that doesn't
qualify, using `ActionRing.TryPeek` and `Pop`. FIFO order is kept: nothing
overtakes a held entry.
- Stance changes, movement, raw attack packets and item moves stay deferred as
before. When the gesture-safe entries empty the ring, the defer clock resets,
so the next held entry gets its full defer.
## Tests
- Engine builds. All RynthCore tool tests pass (EngineRobustnessTests 1159
checks, among others). There is no unit harness for the drain (it needs AC's main
thread). The change is checked live through RynthAi's logs: attacks should no
longer be reported late or stale behind crossbow gestures.
## Files
- `src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs`

View file

@ -0,0 +1,61 @@
# 2026.10.5.60 - launcher: undo a saved UserPreferences.ini that stops the client starting
Previous release: 2026.10.5.59. Launcher project version 0.1.7 (was 0.1.6).
## Problem
A client launched from RynthCore showed "Could not initialize Direct3D. Please ensure that
DirectX 9.0 or higher is installed." twice, then "The game encountered a fatal DirectX issue
while attempting to start. Try a different screen resolution or bit depth...", and exited
about 12 seconds after start. The same client started fine from another launcher.
The engine was not involved: its D3D9 hooks only start at login, and the log had no D3D9
lines. The difference was the launcher. Before every launch it copies the account's saved
game settings (`%APPDATA%\RynthCore\prefs\<account>@<server>.ini`, or the file set on the
profile) over the live `Documents\Asheron's Call\UserPreferences.ini`. The game reads its
resolution and full-screen mode from that file. A saved copy with a display mode the PC can't
use (another monitor, an old resolution) fails every launch, and the saved copy is only
refreshed after a normal session, so it was restored again on every launch. Another launcher
uses the live file, which is why it worked.
## Change
- When a client quits within 30 s (the existing "counted as crash" window) and its launch
swapped in a saved UserPreferences.ini that differs from the live file:
- The saved copy is renamed to `<name>.ini.failed-yyyyMMdd-HHmmss` (kept, never swapped in
again). The account's old name-only copy (`<account>.ini`) is set aside too when it holds
the same settings, because it re-seeds a missing per-server copy.
- The live UserPreferences.ini is put back to what it was before the swap, unless another
launch has swapped it since.
- The activity log says what happened. The next launch uses the live file, and the next
normal session saves a fresh copy.
- A file the user picked on the profile (UserPrefsPath) is never renamed; the live file is
still put back and the activity log points at the profile setting.
- Nothing changes when the saved copy matched the live file (the swap can't have caused the
exit), e.g. a missing password or a server that is down.
## Code
- `src/RynthCore.App/UserPrefsSwapRecovery.cs` (new): `UserPrefsSwap` record (stash path,
live path, stash bytes, live bytes before the swap), `SwapChangedPrefs`, `Recover`
(quarantine + restore), `QuarantinePath`.
- `src/RynthCore.App/AcClientLaunchSettingsService.cs`: `SwapUserPreferences` returns the
`UserPrefsSwap` (was `bool`) and reads the live file before overwriting it.
- `src/RynthCore.App.Avalonia/MainWindow.axaml.cs`: the three launch paths (RynthCore, Decal /
Decal + RynthCore, no injection) use `ApplyPrefsSwap` and record the swap per PID
(`TrackPrefsSwap`); `DetectQuickExits` calls `RecoverFailedPrefsSwap` for a quick exit. A swap
generation counter decides whether the live file can still be put back.
`ResolveLegacyUserPrefsPath` is shared with `ResolveUserPrefsPath`.
- `RynthCore.App.Avalonia.csproj`: links the new file; version 0.1.7.
## Tests
- `tools/LauncherSettingsTests`: 5 new scenarios (swap changed the live file or not; failed
stash set aside and live file restored; a different name-only stash kept; profile override
and later swap leave files alone; no live file before). `PASS: 163 checks`.
- `dotnet build src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj -c Release`: 0 errors.
## For an affected PC now
Rename or delete `%APPDATA%\RynthCore\prefs\<account>@<server>.ini` (and `<account>.ini`) for
the failing account, or clear the UserPreferences file on its profile, then launch again.

View file

@ -0,0 +1,40 @@
# 2026.10.5.59 - Loot Timers show their optimized defaults, with a button to use them
Previous release: 2026.10.5.58 (installed engine 2026.10.5.57).
Goes with RynthSuite's `Changelog/2026-10-14-loot-baseline-0.5.65.md` (RynthAi 0.5.65), which
measured the loot timer baseline and applied it to RynthAi's own Advanced Settings. The
engine's Settings panel (Looting tab) still showed the old list with no defaults.
## Change
- **Settings > Looting > Loot Timers (ms) - (optimized default).** Each timer's label ends
with its optimized default in brackets:
- Content Settle (100)
- Empty Corpse Wait (300)
- Assess Window (300)
- Loot Retry Timeout (1000)
- Corpse Open Retry (1500)
- Corpse Timeout (12000)
- **Use optimized defaults** button: sets all six timers to those values and saves them to
RynthAi like a typed value. It works in the in-game panel and in the launcher's panel.
- Each timer has a tooltip (what it waits for, and the measured appraisal times for Assess
Window).
- Inter-Item Delay and Closing Delay are no longer shown: RynthAi's corpse looting never reads
them (RynthAi hid them in 0.5.65). They are still carried so a save doesn't send them missing.
- The engine's own defaults for the timers (used until RynthAi sends its settings) now match
the optimized defaults: Assess Window 200 -> 300 ms, Loot Retry Timeout 500 -> 1000 ms.
## Code
- `UI/Data/SettingsData.cs`: new `LootTimerDefaults` (the six values, same as RynthSuite's
`LootBaseline.cs`; `Label`, `Apply`, `AllDefault`). `SettingRow` gains an optional
`Edit` action for buttons that change settings, built with `EditButton`.
- `ImGui/Panels/SettingsFace.cs` and `UI/Panels/SettingsPanel.cs`: a button row with `Edit`
applies it to the panel's copy and saves it (the launcher panel also rebuilds the tab so the
number boxes show the new values).
## Tests
- `dotnet build src\RynthCore.Engine\RynthCore.Engine.csproj -c Release`: 0 errors. No test
project compiles `SettingsData.cs`.

View file

@ -2,7 +2,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="RynthCore.App.Avalonia.AccountProfileDialog"
Width="600"
Height="620"
Height="720"
CanResize="False"
WindowStartupLocation="CenterOwner"
Title="Account Profile"
@ -24,6 +24,9 @@
<TextBlock x:Name="PasswordHintText"
Foreground="#9AA8B3"
TextWrapping="Wrap" />
<TextBlock Text="Log in as" Foreground="#EAF0F4" />
<ComboBox x:Name="LoginAsBox" HorizontalAlignment="Stretch" />
<TextBlock x:Name="LoginAsHintText" Foreground="#9AA8B3" TextWrapping="Wrap" />
<TextBlock Text="Alias" Foreground="#EAF0F4" />
<TextBox x:Name="AliasBox" />

View file

@ -12,11 +12,21 @@ internal partial class AccountProfileDialog : Window
{
private readonly LaunchAccountProfile _profile;
private readonly List<LaunchServerProfile> _servers;
private readonly Func<string, string, List<string>> _knownCharactersFor;
public AccountProfileDialog(LaunchAccountProfile profile, List<LaunchServerProfile> servers)
private List<string> _knownCharacters = [];
// Set once the player picks in "Log in as"; until then the saved choice is kept as it is
// (an empty one means "the only character, else character select").
private bool _loginAsChanged;
private bool _loadingLoginAs;
/// <param name="knownCharactersFor">(account name, server name) -> the characters known for it.</param>
public AccountProfileDialog(LaunchAccountProfile profile, List<LaunchServerProfile> servers,
Func<string, string, List<string>> knownCharactersFor)
{
_profile = profile;
_servers = servers;
_knownCharactersFor = knownCharactersFor;
InitializeComponent();
ServerComboBox.ItemsSource = _servers.Select(s => s.DisplayName).ToList();
@ -30,15 +40,52 @@ internal partial class AccountProfileDialog : Window
PasswordHintText.Text = profile.PasswordNeedsReentry
? "Password needs re-entering: the saved one can't be read on this Windows user (settings copied from another user or PC?). Type it again to launch this account."
: !profile.HasSavedPassword
? "No password is saved for this profile yet."
? "No password is saved for this profile yet. The game client won't start without one; you'll be asked for it on the first launch."
: "A password is saved for this profile, encrypted for this Windows user. It stays hidden unless you replace or clear it.";
ServerComboBox.SelectionChanged += (_, _) => RefreshLoginAs();
AccountBox.TextChanged += (_, _) => RefreshLoginAs();
LoginAsBox.SelectionChanged += (_, _) =>
{
if (!_loadingLoginAs)
_loginAsChanged = true;
};
RefreshLoginAs();
SaveButton.Click += (_, _) => SaveAndClose();
CancelButton.Click += (_, _) => Close(false);
BrowseUserPrefsButton.Click += async (_, _) => await BrowseUserPrefsAsync();
SnapshotUserPrefsButton.Click += (_, _) => SnapshotLiveUserPrefs();
}
/// <summary>Lists the characters known for the account on the chosen server in "Log in as".</summary>
private void RefreshLoginAs()
{
string accountName = AccountBox.Text?.Trim() ?? string.Empty;
string serverName = ServerComboBox.SelectedIndex >= 0 ? _servers[ServerComboBox.SelectedIndex].Name : string.Empty;
_knownCharacters = accountName.Length > 0 ? _knownCharactersFor(accountName, serverName) : [];
string? current = _loginAsChanged ? LoginAsBox.SelectedItem as string : null;
List<string> choices = FirstLoginRules.LoginChoices(_knownCharacters, _profile.CharacterName);
_loadingLoginAs = true;
try
{
LoginAsBox.ItemsSource = choices;
LoginAsBox.SelectedItem = current != null && choices.Contains(current) ? current
: choices.Contains(_profile.CharacterName) ? _profile.CharacterName
: FirstLoginRules.StopAtCharacterSelect;
}
finally
{
_loadingLoginAs = false;
}
LoginAsHintText.Text = _knownCharacters.Count == 0
? "No characters are known for this account on this server yet. Launch it: the client stops at character select, where you can create characters, and RynthCore picks them up there."
: $"{_knownCharacters.Count} character(s) on this account. Pick the one that logs in automatically, or stop at character select. The launch list's dropdown changes this too.";
}
private async System.Threading.Tasks.Task BrowseUserPrefsAsync()
{
var topLevel = GetTopLevel(this);
@ -112,10 +159,24 @@ internal partial class AccountProfileDialog : Window
return;
}
if (ServerComboBox.SelectedIndex >= 0)
_profile.ServerId = _servers[ServerComboBox.SelectedIndex].Id;
LaunchServerProfile? server = ServerComboBox.SelectedIndex >= 0 ? _servers[ServerComboBox.SelectedIndex] : null;
if (server == null && _servers.Count > 0)
{
ValidationText.Text = "Pick the server this account is for.";
return;
}
if (AcLaunchArgumentBuilder.AccountNameProblem(AccountBox.Text, server?.Emulator ?? AcEmulatorKind.Ace) is string nameProblem)
{
ValidationText.Text = nameProblem;
return;
}
if (server != null)
_profile.ServerId = server.Id;
_profile.AccountName = AccountBox.Text.Trim();
if (_loginAsChanged)
_profile.CharacterName = FirstLoginRules.CharacterNameFor(LoginAsBox.SelectedItem as string, _knownCharacters);
if (ClearPasswordCheckBox.IsChecked == true)
{
_profile.ClearPassword();

View file

@ -0,0 +1,44 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="RynthCore.App.Avalonia.FirstLoginDialog"
Width="560"
SizeToContent="Height"
CanResize="False"
WindowStartupLocation="CenterOwner"
Title="First Login"
Background="#132028">
<Grid RowDefinitions="*,Auto" Margin="18">
<StackPanel Spacing="10">
<TextBlock x:Name="HeaderText" Foreground="#EAF0F4" FontSize="16" FontWeight="SemiBold" TextWrapping="Wrap" />
<TextBlock x:Name="IntroText" Foreground="#9AA8B3" TextWrapping="Wrap" />
<TextBlock Text="Use an account you already have (optional)" Foreground="#EAF0F4" />
<ComboBox x:Name="KnownAccountBox" HorizontalAlignment="Stretch" PlaceholderText="Pick an account name, or type a new one below" />
<TextBlock Text="Account" Foreground="#EAF0F4" />
<TextBox x:Name="AccountBox" Watermark="A new name creates the account on this server's first login (ACE)" />
<CheckBox x:Name="ReuseSavedPasswordCheckBox" Foreground="#EAF0F4" IsVisible="False" />
<StackPanel x:Name="PasswordPanel" Spacing="10">
<TextBlock Text="Password" Foreground="#EAF0F4" />
<TextBox x:Name="PasswordBox" PasswordChar="*" RevealPassword="False" />
<TextBlock Text="Confirm password" Foreground="#EAF0F4" />
<TextBox x:Name="ConfirmBox" PasswordChar="*" RevealPassword="False" />
</StackPanel>
<TextBlock Text="The password is saved encrypted for this Windows user, like the other accounts."
Foreground="#9AA8B3" TextWrapping="Wrap" />
<TextBlock Text="Log in as" Foreground="#EAF0F4" />
<ComboBox x:Name="LoginAsBox" HorizontalAlignment="Stretch" />
<TextBlock x:Name="LoginAsHintText" Foreground="#9AA8B3" TextWrapping="Wrap" />
<TextBlock x:Name="ValidationText" Foreground="#E2B348" TextWrapping="Wrap" />
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,16,0,0">
<Button x:Name="CancelButton" Content="Cancel" />
<Button x:Name="LoginButton" Content="Log In" />
</StackPanel>
</Grid>
</Window>

View file

@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using Avalonia.Controls;
using RynthCore.App;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Asked before launching an account that has no usable password (a new server, or a profile added
/// without one): the account name (one you already use, or a new one), its password, and which
/// character logs in. Edits the profile passed in only when the player presses Log In.
/// </summary>
internal partial class FirstLoginDialog : Window
{
private readonly LaunchAccountProfile _profile;
private readonly LaunchServerProfile _server;
private readonly IReadOnlyList<LaunchAccountProfile> _allProfiles;
private readonly Func<string, List<string>> _knownCharactersFor;
private List<string> _knownCharacters = [];
private LaunchAccountProfile? _passwordSource;
public FirstLoginDialog(
LaunchAccountProfile profile,
LaunchServerProfile server,
IReadOnlyList<LaunchAccountProfile> allProfiles,
Func<string, List<string>> knownCharactersFor)
{
_profile = profile;
_server = server;
_allProfiles = allProfiles;
_knownCharactersFor = knownCharactersFor;
InitializeComponent();
string serverLabel = server.DisplayName;
HeaderText.Text = $"First login on {serverLabel}";
IntroText.Text = profile.PasswordNeedsReentry
? "The saved password for this account can't be read on this Windows user (settings copied from another user or PC?). Enter it again to log in."
: "No password is saved for this account yet, and the game client won't start without one. "
+ "ACE servers create a new account the first time it logs in (if the server allows it). "
+ "With no character picked, the client stops at character select, where you can create characters. "
+ "Every character on the account is remembered, and you pick which one logs in from the launch list.";
KnownAccountBox.ItemsSource = FirstLoginRules.KnownAccountNames(allProfiles, profile.Id);
KnownAccountBox.IsEnabled = KnownAccountBox.ItemCount > 0;
KnownAccountBox.SelectionChanged += (_, _) =>
{
if (KnownAccountBox.SelectedItem is string picked)
AccountBox.Text = picked;
};
AccountBox.Text = profile.AccountName;
AccountBox.TextChanged += (_, _) => OnAccountChanged();
ReuseSavedPasswordCheckBox.IsCheckedChanged += (_, _) => UpdatePasswordPanel();
LoginButton.Click += (_, _) => LogInAndClose();
CancelButton.Click += (_, _) => Close(false);
OnAccountChanged();
}
/// <summary>Re-reads the account's characters and whether another profile's password can be reused.</summary>
private void OnAccountChanged()
{
string name = AccountBox.Text?.Trim() ?? string.Empty;
_passwordSource = FirstLoginRules.SavedPasswordSource(_allProfiles, name, _profile.Id);
if (_passwordSource != null)
{
string from = _passwordSource.DisplayName;
ReuseSavedPasswordCheckBox.Content = $"Use the password saved for '{name}' in profile {from}";
ReuseSavedPasswordCheckBox.IsVisible = true;
}
else
{
ReuseSavedPasswordCheckBox.IsVisible = false;
ReuseSavedPasswordCheckBox.IsChecked = false;
}
UpdatePasswordPanel();
_knownCharacters = name.Length > 0 ? _knownCharactersFor(name) : [];
string? keep = LoginAsBox.SelectedItem as string;
List<string> choices = FirstLoginRules.LoginChoices(_knownCharacters, _profile.CharacterName);
LoginAsBox.ItemsSource = choices;
LoginAsBox.SelectedItem = keep != null && choices.Contains(keep) ? keep
: choices.Contains(_profile.CharacterName) ? _profile.CharacterName
: FirstLoginRules.StopAtCharacterSelect;
LoginAsHintText.Text = _knownCharacters.Count == 0
? $"No characters are known for this account on {_server.DisplayName} yet. Create them at character select; RynthCore picks them up there."
: $"{_knownCharacters.Count} character(s) known for this account. Pick one to log in automatically, or stop at character select.";
}
private void UpdatePasswordPanel()
{
bool reuse = ReuseSavedPasswordCheckBox.IsVisible && ReuseSavedPasswordCheckBox.IsChecked == true;
PasswordPanel.IsVisible = !reuse;
}
private void LogInAndClose()
{
bool reuse = _passwordSource != null && ReuseSavedPasswordCheckBox.IsChecked == true;
string name = AccountBox.Text?.Trim() ?? string.Empty;
if (FirstLoginRules.Problem(name, PasswordBox.Text, ConfirmBox.Text, reuse, _server.Emulator) is string problem)
{
ValidationText.Text = problem;
return;
}
_profile.AccountName = name;
_profile.ServerId = _server.Id;
if (reuse)
_profile.CopyPasswordFrom(_passwordSource!);
else
_profile.SetPassword(PasswordBox.Text); // encrypted at once; the plain text isn't kept
PasswordBox.Text = string.Empty;
ConfirmBox.Text = string.Empty;
_profile.CharacterName = FirstLoginRules.CharacterNameFor(LoginAsBox.SelectedItem as string, _knownCharacters);
Close(true);
}
}

View file

@ -33,6 +33,7 @@ internal partial class MainWindow : Window
// handle most of the work; this cooldown is a final belt-and-braces.
private static readonly TimeSpan AutoLaunchCooldown = TimeSpan.FromSeconds(2);
private static readonly TimeSpan AutoLaunchServerDownLogCooldown = TimeSpan.FromSeconds(30);
private static readonly TimeSpan AutoLaunchNeedsPasswordLogCooldown = TimeSpan.FromMinutes(5);
// Auto-inject only after the external AC client has been continuously
// graphics-ready for this long. The window gives Decal/UBLoader time to
@ -90,6 +91,11 @@ internal partial class MainWindow : Window
// After CreateProcess+inject+resume, hold the prefs lock this long so AC
// has a chance to read UserPreferences.ini before another account swaps.
private static readonly TimeSpan UserPrefsSettleDelay = TimeSpan.FromSeconds(2);
// The UserPreferences.ini swap each launched PID started with, so a quick exit can set the
// saved copy aside and put the previous live file back (UserPrefsSwapRecovery).
private readonly Dictionary<int, PrefsSwapLaunch> _prefsSwapByPid = [];
// Counts swaps; a quick exit only restores the live file when no later swap replaced it.
private long _prefsSwapGeneration;
private readonly Dictionary<int, DateTime> _autoInjectFirstReadyAtUtc = [];
private readonly HashSet<int> _autoInjectAttemptedPids = [];
private readonly HashSet<int> _autoInjectInFlightPids = [];
@ -99,6 +105,7 @@ internal partial class MainWindow : Window
private readonly Dictionary<string, ComboBox> _launchTargetInjectionDropdowns = [];
private readonly Dictionary<string, DateTime> _autoLaunchAttemptTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchServerDownNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchNeedsPasswordNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ServerAvailabilityState> _serverStatuses = new(StringComparer.OrdinalIgnoreCase);
private readonly List<PluginDefinition> _plugins =
[
@ -727,8 +734,10 @@ internal partial class MainWindow : Window
private async System.Threading.Tasks.Task AddAccountAsync()
{
var draft = new RynthCore.App.LaunchAccountProfile();
var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles);
// Defaults to the server selected in the list (a new server's first account), not the
// first profile, which RefreshLaunchTargets would otherwise assign.
var draft = new RynthCore.App.LaunchAccountProfile { ServerId = GetSelectedServer()?.Id ?? string.Empty };
var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters);
bool? accepted = await dialog.ShowDialog<bool?>(this);
if (accepted != true)
return;
@ -749,7 +758,7 @@ internal partial class MainWindow : Window
return;
LaunchAccountProfile draft = selected.Clone();
var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles);
var dialog = new AccountProfileDialog(draft, _settings.ServerProfiles, GetDetectedCharacters);
bool? accepted = await dialog.ShowDialog<bool?>(this);
if (accepted != true)
return;
@ -1637,6 +1646,29 @@ internal partial class MainWindow : Window
}
}
// No usable password: the client would refuse to start ("You can only run the game from
// the launcher program") and exit within seconds. A manual launch asks for it (and the
// account) in the First Login dialog; an automatic one skips the account.
if (string.IsNullOrWhiteSpace(overrideArguments))
{
var ready = new List<LaunchAccountProfile>(accountsToLaunch.Count);
foreach (LaunchAccountProfile account in accountsToLaunch)
{
if (!AcLaunchArgumentBuilder.NeedsPassword(account))
ready.Add(account);
else if (isAutomaticLaunch)
AppendActivity($"Auto launch skipped for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
else if (await PromptFirstLoginAsync(account))
ready.Add(account);
else
AppendActivity($"Launch cancelled for {account.DisplayName}: no password entered.");
}
if (ready.Count == 0)
return;
accountsToLaunch = ready;
}
SaveRuntimePaths(appendActivity: !isAutomaticLaunch);
SaveLaunchBehavior(appendActivity: !isAutomaticLaunch);
@ -1784,10 +1816,7 @@ internal partial class MainWindow : Window
try
{
if (needsPrefsSwap)
{
_launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity);
}
PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null;
InjectionResult result = await Task.Run(() =>
_injector.LaunchSuspendedAndInject(
@ -1811,6 +1840,7 @@ internal partial class MainWindow : Window
{
_launchedSessionPids.Add(trackedPid);
_launchedPidInfo[trackedPid] = (accountKey, DateTime.UtcNow);
TrackPrefsSwap(trackedPid, prefsSwap);
RegisterPidExitWatch(trackedPid);
}
@ -1864,10 +1894,7 @@ internal partial class MainWindow : Window
try
{
if (needsPrefsSwap)
{
_launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity);
}
PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null;
// enginePath != null: "Decal + RynthCore" - Decal is injected first, then the
// RynthCore loader, before the client resumes.
@ -1894,6 +1921,7 @@ internal partial class MainWindow : Window
{
_launchedSessionPids.Add(trackedPid);
_launchedPidInfo[trackedPid] = (accountKey, DateTime.UtcNow);
TrackPrefsSwap(trackedPid, prefsSwap);
RegisterPidExitWatch(trackedPid);
}
@ -1943,10 +1971,7 @@ internal partial class MainWindow : Window
try
{
if (needsPrefsSwap)
{
_launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity);
}
PrefsSwapLaunch? prefsSwap = needsPrefsSwap ? ApplyPrefsSwap(account, launchContext.ServerName, resolvedPrefsPath) : null;
Process? proc = null;
Exception? launchEx = null;
@ -1978,6 +2003,7 @@ internal partial class MainWindow : Window
{
_launchedSessionPids.Add(proc.Id);
_launchedPidInfo[proc.Id] = (BuildAccountKey(launchContext.AccountName, launchContext.ServerName), DateTime.UtcNow);
TrackPrefsSwap(proc.Id, prefsSwap);
RegisterPidExitWatch(proc.Id);
LaunchContextStore.WriteForProcess(proc.Id, launchContext);
WritePendingSessionState(proc.Id, launchContext);
@ -2004,6 +2030,38 @@ internal partial class MainWindow : Window
}
}
/// <summary>
/// Shows the First Login dialog for <paramref name="account"/> (no usable password). True when
/// the player entered one: the profile is updated and saved (password encrypted at once).
/// </summary>
private async Task<bool> PromptFirstLoginAsync(LaunchAccountProfile account)
{
LaunchServerProfile? server = ResolveServerForAccount(account);
if (server == null)
{
AppendActivity($"Launch blocked for {account.DisplayName}: add a server profile first.");
return false;
}
LaunchAccountProfile draft = account.Clone();
var dialog = new FirstLoginDialog(draft, server, _settings.AccountProfiles,
accountName => GetDetectedCharacters(accountName, server.Name));
bool? accepted = await dialog.ShowDialog<bool?>(this);
if (accepted != true)
return false;
account.CopyFrom(draft);
SaveSettings();
RefreshLists();
RefreshSummary();
string loginAs = string.IsNullOrWhiteSpace(account.CharacterName) || account.CharacterName == LaunchAccountProfile.NoneOption
? "stopping at character select"
: $"logging in as {account.CharacterName}";
AppendActivity($"First login on {server.DisplayName}: account '{account.AccountName}', password saved (encrypted), {loginAs}.");
return true;
}
private LaunchContextRecord BuildLaunchContext(LaunchAccountProfile account, LaunchServerProfile? server)
{
string targetCharacter = ResolveTargetCharacterForLaunch(account, server);
@ -3856,6 +3914,7 @@ internal partial class MainWindow : Window
AppendActivity($"Account '{entry.Value.AccountKey}' client (PID {entry.Key}) exited after {uptime.TotalSeconds:F0}s — counted as crash.");
int hist = _crashHistoryByAccount.TryGetValue(entry.Value.AccountKey, out List<DateTime>? h) ? h.Count : 0;
LauncherDiag.Info($"DetectQuickExits: PID {entry.Key} ({entry.Value.AccountKey}) uptime={uptime.TotalSeconds:F1}s -> RecordCrash. crashHist now {hist}.");
RecoverFailedPrefsSwap(entry.Key, entry.Value.AccountKey, uptime);
}
else if (!string.IsNullOrEmpty(entry.Value.AccountKey))
{
@ -3872,6 +3931,7 @@ internal partial class MainWindow : Window
foreach (int pid in toRemove)
{
_launchedPidInfo.Remove(pid);
_prefsSwapByPid.Remove(pid);
// Drop the exit-watcher Process handle so the OS can reclaim
// the kernel object. Exited already fired (or never will),
// so we no longer need to hold the handle alive.
@ -4212,17 +4272,14 @@ internal partial class MainWindow : Window
if (!string.IsNullOrWhiteSpace(account.UserPrefsPath))
return account.UserPrefsPath.Trim();
if (string.IsNullOrWhiteSpace(account.AccountName))
string legacyPath = ResolveLegacyUserPrefsPath(account);
if (string.IsNullOrEmpty(legacyPath))
return string.Empty;
string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string prefsDir = Path.Combine(appdata, "RynthCore", "prefs");
string safeName = SafePrefsFileName(account.AccountName);
string legacyPath = Path.Combine(prefsDir, $"{safeName}.ini");
if (string.IsNullOrWhiteSpace(serverName))
return legacyPath;
string scopedPath = Path.Combine(prefsDir, $"{safeName}@{SafePrefsFileName(serverName)}.ini");
string prefsDir = Path.GetDirectoryName(legacyPath)!;
string scopedPath = Path.Combine(prefsDir, $"{SafePrefsFileName(account.AccountName)}@{SafePrefsFileName(serverName)}.ini");
if (!File.Exists(scopedPath) && File.Exists(legacyPath))
{
try { File.Copy(legacyPath, scopedPath, overwrite: false); }
@ -4232,9 +4289,98 @@ internal partial class MainWindow : Window
return scopedPath;
}
/// <summary>
/// The account's old name-only stash (%APPDATA%\RynthCore\prefs\name.ini), which seeds a
/// missing per-server one. Empty when the account has no name yet.
/// </summary>
private static string ResolveLegacyUserPrefsPath(LaunchAccountProfile account)
{
if (string.IsNullOrWhiteSpace(account.AccountName))
return string.Empty;
string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(appdata, "RynthCore", "prefs", $"{SafePrefsFileName(account.AccountName)}.ini");
}
private static string SafePrefsFileName(string name) =>
string.Join("_", name.Trim().Split(Path.GetInvalidFileNameChars()));
/// <summary>
/// A launch's UserPreferences.ini swap. <see cref="IsProfileOverride"/>: the stash is a file the
/// user picked on the profile (never renamed by the launcher). <see cref="LegacyPath"/>: the
/// account's name-only stash, set aside with a failed per-server one when identical.
/// </summary>
private sealed record PrefsSwapLaunch(UserPrefsSwap Swap, long Generation, bool IsProfileOverride, string LegacyPath);
/// <summary>
/// Copies the account's saved UserPreferences.ini over the live one (caller holds
/// _userPrefsSwapLock) and returns what was swapped, or null when nothing was.
/// </summary>
private PrefsSwapLaunch? ApplyPrefsSwap(LaunchAccountProfile account, string? serverName, string resolvedPrefsPath)
{
UserPrefsSwap? swap = _launchSettings.SwapUserPreferences(resolvedPrefsPath, _settings.AllowMultipleClients, AppendActivity);
if (swap == null)
return null;
long generation = ++_prefsSwapGeneration;
bool isOverride = !string.IsNullOrWhiteSpace(account.UserPrefsPath);
LauncherDiag.Info($"PrefsSwap: account='{account.AccountName}' server='{serverName}' gen={generation} override={isOverride} changedLive={UserPrefsSwapRecovery.SwapChangedPrefs(swap)} stash='{swap.StashPath}'");
return new PrefsSwapLaunch(swap, generation, isOverride, ResolveLegacyUserPrefsPath(account));
}
/// <summary>Remembers which swap a launched client started with (no-op without a swap).</summary>
private void TrackPrefsSwap(int pid, PrefsSwapLaunch? prefsSwap)
{
if (prefsSwap != null)
_prefsSwapByPid[pid] = prefsSwap;
}
/// <summary>
/// A client quit within CrashQuickExitWindow. If it started with a saved UserPreferences.ini
/// that differs from the live one, that saved copy is the likely cause (the game reads its
/// display mode from it: "Could not initialize Direct3D"), and it would be swapped in again on
/// every launch because it is only refreshed after a normal session. So: set the saved copy
/// aside (renamed, kept), and put the previous live file back when no later launch replaced it.
/// The next normal session saves a fresh copy.
/// </summary>
private void RecoverFailedPrefsSwap(int pid, string accountKey, TimeSpan uptime)
{
if (!_prefsSwapByPid.Remove(pid, out PrefsSwapLaunch? launch))
return;
if (!UserPrefsSwapRecovery.SwapChangedPrefs(launch.Swap))
{
LauncherDiag.Info($"PrefsSwap: PID {pid} ({accountKey}) quick exit, but its stash matched the live file; left alone.");
return;
}
bool restoreLive = launch.Generation == _prefsSwapGeneration;
try
{
UserPrefsRecoveryResult result = UserPrefsSwapRecovery.Recover(
launch.Swap,
quarantineStash: !launch.IsProfileOverride,
restoreLive,
launch.LegacyPath,
DateTime.Now);
LauncherDiag.Info($"PrefsSwap: PID {pid} ({accountKey}) recovery: quarantined='{result.QuarantinedStashPath}' legacy='{result.QuarantinedLegacyPath}' liveRestored={result.LiveRestored}.");
string stashName = Path.GetFileName(launch.Swap.StashPath);
string what = launch.IsProfileOverride
? $"the UserPreferences file set on its profile ({launch.Swap.StashPath}). Fix or clear that file in the account's settings if launches keep failing"
: $"this account's saved game settings ({stashName}). They were set aside as {Path.GetFileName(result.QuarantinedStashPath ?? stashName)}, so the next launch uses the current UserPreferences.ini";
string live = result.LiveRestored
? " The previous UserPreferences.ini was put back."
: " UserPreferences.ini was left as is (another launch has swapped it since).";
AppendActivity($"Account '{accountKey}' client (PID {pid}) quit after {uptime.TotalSeconds:F0}s using {what}.{live}");
}
catch (Exception ex)
{
AppendActivity($"Account '{accountKey}': could not undo the UserPreferences.ini swap after a quick exit: {ex.Message}");
}
}
/// <summary>
/// Copies the current live UserPreferences.ini to the resolved stash for
/// the named account. Called on tracked-client exit so per-account prefs
@ -4347,6 +4493,13 @@ internal partial class MainWindow : Window
continue;
}
// Needs the First Login dialog, which only a manual launch shows.
if (AcLaunchArgumentBuilder.NeedsPassword(account))
{
MaybeLogAutoLaunchNeedsPassword(account, nowUtc);
continue;
}
if (_autoLaunchAttemptTimesUtc.TryGetValue(account.Id, out DateTime lastAttemptUtc) &&
nowUtc - lastAttemptUtc < AutoLaunchCooldown)
{
@ -4399,6 +4552,18 @@ internal partial class MainWindow : Window
AppendActivity($"Auto launch waiting for {account.DisplayName}: {(server?.DisplayName ?? "the selected server")} is reporting down.");
}
private void MaybeLogAutoLaunchNeedsPassword(LaunchAccountProfile account, DateTime nowUtc)
{
if (_autoLaunchNeedsPasswordNoticeTimesUtc.TryGetValue(account.Id, out DateTime lastNoticeUtc) &&
nowUtc - lastNoticeUtc < AutoLaunchNeedsPasswordLogCooldown)
{
return;
}
_autoLaunchNeedsPasswordNoticeTimesUtc[account.Id] = nowUtc;
AppendActivity($"Auto launch waiting for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
}
private bool IsServerKnownDown(LaunchServerProfile? server)
{
if (server == null)
@ -4476,7 +4641,7 @@ internal partial class MainWindow : Window
string character = !string.IsNullOrWhiteSpace(session.CharacterName) ? session.CharacterName
: !string.IsNullOrWhiteSpace(session.TargetCharacter) ? session.TargetCharacter
: !string.IsNullOrWhiteSpace(account.CharacterName) ? account.CharacterName
: !string.IsNullOrWhiteSpace(account.CharacterName) && account.CharacterName != LaunchAccountProfile.NoneOption ? account.CharacterName
: "Logged in";
string elapsed = FormatElapsed(DateTime.UtcNow - (session.LoginCompletedAtUtc ?? session.LaunchStartedAtUtc));
return ($"{character} | online {elapsed}", "#66D687");
@ -4490,12 +4655,16 @@ internal partial class MainWindow : Window
Process? process = targets.FirstOrDefault(p => p.Id == pid);
DateTime since = process != null ? GetProcessStartTimeUtc(process) : context.CreatedAtUtc.ToUniversalTime();
string character = !string.IsNullOrWhiteSpace(context.TargetCharacter) ? context.TargetCharacter
: !string.IsNullOrWhiteSpace(account.CharacterName) ? account.CharacterName
: "Pending";
: !string.IsNullOrWhiteSpace(account.CharacterName) && account.CharacterName != LaunchAccountProfile.NoneOption ? account.CharacterName
: "Character select";
string elapsed = FormatElapsed(DateTime.UtcNow - since);
return ($"{character} | starting {elapsed}", "#E2B348");
}
if (AcLaunchArgumentBuilder.NeedsPassword(account))
return ("Needs password | launch to set up", "#E2B348");
if (account.CharacterName == LaunchAccountProfile.NoneOption)
return ("Character select | offline", "#73828D");
return (!string.IsNullOrWhiteSpace(account.CharacterName) ? $"{account.CharacterName} | offline" : "Offline", "#73828D");
}

View file

@ -1,12 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.4.
<!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.6.
No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the
product version derived from it is what the launcher/About show (BuildVersion.Format). -->
<Version>0.1.5</Version>
<AssemblyVersion>0.1.5.0</AssemblyVersion>
<FileVersion>0.1.5.0</FileVersion>
<Version>0.1.7</Version>
<AssemblyVersion>0.1.7.0</AssemblyVersion>
<FileVersion>0.1.7.0</FileVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows7.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
@ -53,7 +53,9 @@
<Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" />
<Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" />
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\RynthCore.App\FirstLoginRules.cs" Link="Shared\FirstLoginRules.cs" />
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
<Compile Include="..\RynthCore.App\UserPrefsSwapRecovery.cs" Link="Shared\UserPrefsSwapRecovery.cs" />
<Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" />
<Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" />
<Compile Include="..\RynthCore.App\LaunchContextStore.cs" Link="Shared\LaunchContextStore.cs" />

View file

@ -28,38 +28,45 @@ internal sealed class AcClientLaunchSettingsService
/// My Documents\Asheron's Call, then re-applies the ComputeUniquePort flag.
/// If <paramref name="stashPath"/> is empty or missing, no swap is performed
/// and the live file is left as-is.
/// Returns what was swapped (null when nothing was), so a client that quits at
/// startup can be traced back to the stash and the swap undone
/// (<see cref="UserPrefsSwapRecovery"/>).
/// </summary>
public bool SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null)
public UserPrefsSwap? SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null)
{
if (string.IsNullOrWhiteSpace(stashPath))
return false;
return null;
if (!File.Exists(stashPath))
{
log?.Invoke($"User prefs swap skipped: stash file not found at {stashPath}.");
return false;
return null;
}
string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call");
string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName);
byte[] stashBytes;
byte[]? previousLiveBytes;
try
{
Directory.CreateDirectory(prefsDirectory);
stashBytes = File.ReadAllBytes(stashPath);
previousLiveBytes = File.Exists(prefsPath) ? File.ReadAllBytes(prefsPath) : null;
File.Copy(stashPath, prefsPath, overwrite: true);
}
catch (Exception ex)
{
log?.Invoke($"User prefs swap failed copying {stashPath}: {ex.Message}");
return false;
return null;
}
// Re-apply the ComputeUniquePort flag — the stash may have it set to
// the wrong value (e.g. user set it up before enabling multi-client).
UpdateUserPreferences(allowMultipleClients, log: null);
log?.Invoke($"User prefs swap: applied stash {Path.GetFileName(stashPath)}.");
return true;
return new UserPrefsSwap(stashPath, prefsPath, stashBytes, previousLiveBytes);
}
private static void UpdateUserPreferences(bool allowMultipleClients, Action<string>? log)

View file

@ -9,10 +9,28 @@ internal sealed class AcLaunchArgumentBuilder
/// <summary>Text shown in place of the password in previews.</summary>
public const string PasswordMask = "********";
/// <summary>
/// True when <paramref name="account"/> can't be launched until a password is entered: none
/// is saved, or the saved one can't be decrypted on this Windows user. Every supported
/// emulator logs on with a password, and the client refuses an empty one before it connects
/// ("You can only run the game from the launcher program").
/// </summary>
public static bool NeedsPassword(LaunchAccountProfile account)
{
ArgumentNullException.ThrowIfNull(account);
return account.PasswordNeedsReentry || !account.HasSavedPassword;
}
/// <summary>Why an account without a password can't be launched (no secrets in it).</summary>
public static string MissingPasswordMessage(string? accountName) =>
$"No password is saved for account '{accountName}'. The AC client won't start without one " +
"(\"You can only run the game from the launcher program\"). Launch it by hand to enter it, or edit the account.";
/// <summary>
/// The client's command line, with the saved password decrypted now. The result carries the
/// password: hand it to the process and never log, display or keep it. Throws when the saved
/// password can't be decrypted on this Windows user (never launches with an empty one instead).
/// password: hand it to the process and never log, display or keep it. Throws when no password
/// is saved or the saved one can't be decrypted on this Windows user (never launches with an
/// empty one instead).
/// </summary>
public string BuildArguments(LaunchServerProfile server, LaunchAccountProfile account)
{
@ -23,6 +41,8 @@ internal sealed class AcLaunchArgumentBuilder
if (!account.TryGetPasswordForLaunch(out string password, out string problem))
throw new InvalidOperationException(problem);
if (password.Length == 0)
throw new InvalidOperationException(MissingPasswordMessage(account.AccountName));
return Build(server, account, password);
}
@ -40,8 +60,10 @@ internal sealed class AcLaunchArgumentBuilder
if (account.PasswordNeedsReentry)
return LaunchAccountProfile.PasswordNeedsReentryMessage(account.AccountName);
if (!account.HasSavedPassword)
return MissingPasswordMessage(account.AccountName);
return Build(server, account, account.HasSavedPassword ? PasswordMask : string.Empty);
return Build(server, account, PasswordMask);
}
private static string Build(LaunchServerProfile server, LaunchAccountProfile account, string password)
@ -79,11 +101,33 @@ internal sealed class AcLaunchArgumentBuilder
errors.Add("Server port must be greater than zero.");
if (string.IsNullOrWhiteSpace(account.AccountName))
errors.Add("Account name is required.");
else if (AccountNameProblem(account.AccountName, server.Emulator) is string nameProblem)
errors.Add(nameProblem);
if (errors.Count > 0)
throw new InvalidOperationException(string.Join(" ", errors));
}
/// <summary>Longest account name ACE accepts (AuthenticationHandler rejects longer ones).</summary>
public const int MaxAccountNameLength = 50;
/// <summary>
/// Why <paramref name="accountName"/> can't log on to a server of <paramref name="emulator"/>
/// (null = fine). GDLE takes "account:password" in one argument, so a colon in the name would
/// split it in the wrong place.
/// </summary>
public static string? AccountNameProblem(string? accountName, AcEmulatorKind emulator)
{
string name = accountName?.Trim() ?? string.Empty;
if (name.Length == 0)
return "Account name is required.";
if (name.Length > MaxAccountNameLength)
return $"Account name is longer than {MaxAccountNameLength} characters.";
if (emulator == AcEmulatorKind.Gdle && name.Contains(':'))
return "Account names can't contain ':' on GDLE servers.";
return null;
}
private static string Quote(string value)
{
value ??= string.Empty;

View file

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.App;
/// <summary>
/// The rules behind the launcher's "First login" dialog, shown when an account is launched with no
/// usable password (a new server, or a profile added without one). Pure: no UI, no files.
///
/// The client refuses an empty password before it connects ("You can only run the game from the
/// launcher program"), so a password is always required. ACE creates an account the first time a
/// new name logs on with a password (AllowAutoAccountCreation), so a new name here is how an
/// account is created. With no character known yet the client stops at character select, where
/// characters are created; the engine saves the account's character list from there.
/// </summary>
internal static class FirstLoginRules
{
/// <summary>The "Log in as" entry that stops at character select.</summary>
public const string StopAtCharacterSelect = "Stop at character select (create or pick a character there)";
/// <summary>
/// Account names from the other profiles, distinct (case-insensitive) and sorted, for picking
/// an account you already use elsewhere.
/// </summary>
internal static List<string> KnownAccountNames(IEnumerable<LaunchAccountProfile> profiles, string excludeProfileId)
{
return profiles
.Where(p => !string.Equals(p.Id, excludeProfileId, StringComparison.OrdinalIgnoreCase))
.Select(p => p.AccountName?.Trim() ?? string.Empty)
.Where(n => n.Length > 0)
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(n => n, StringComparer.OrdinalIgnoreCase)
.ToList();
}
/// <summary>
/// Another profile with the same account name and a password readable on this Windows user,
/// whose saved password can be reused (null = none). The same name on another server is a
/// different account, so the caller offers this as a choice, never silently.
/// </summary>
internal static LaunchAccountProfile? SavedPasswordSource(
IEnumerable<LaunchAccountProfile> profiles, string accountName, string excludeProfileId)
{
string name = accountName?.Trim() ?? string.Empty;
if (name.Length == 0)
return null;
return profiles.FirstOrDefault(p =>
!string.Equals(p.Id, excludeProfileId, StringComparison.OrdinalIgnoreCase)
&& string.Equals(p.AccountName?.Trim(), name, StringComparison.OrdinalIgnoreCase)
&& p.HasSavedPassword
&& !p.PasswordNeedsReentry);
}
/// <summary>
/// The "Log in as" choices: stop at character select, then the account's known characters
/// (the saved one first if the list hasn't seen it yet).
/// </summary>
internal static List<string> LoginChoices(IReadOnlyList<string> knownCharacters, string? savedCharacter)
{
var choices = new List<string> { StopAtCharacterSelect };
if (!string.IsNullOrWhiteSpace(savedCharacter)
&& savedCharacter != LaunchAccountProfile.NoneOption
&& !knownCharacters.Contains(savedCharacter, StringComparer.OrdinalIgnoreCase))
{
choices.Add(savedCharacter);
}
choices.AddRange(knownCharacters.Where(c => !string.IsNullOrWhiteSpace(c)));
return choices;
}
/// <summary>
/// The CharacterName to save for <paramref name="choice"/>. Stopping at character select with
/// no character known yet saves "" rather than the explicit "(None)": once the first character
/// is created and it is the only one, the launcher picks it for the next launch.
/// </summary>
internal static string CharacterNameFor(string? choice, IReadOnlyList<string> knownCharacters)
{
if (string.IsNullOrWhiteSpace(choice) || choice == StopAtCharacterSelect)
return knownCharacters.Count == 0 ? string.Empty : LaunchAccountProfile.NoneOption;
return choice;
}
/// <summary>What's wrong with the entries (null = ready to log in).</summary>
internal static string? Problem(string? accountName, string? password, string? confirm, bool reuseSavedPassword, AcEmulatorKind emulator)
{
if (AcLaunchArgumentBuilder.AccountNameProblem(accountName, emulator) is string nameProblem)
return nameProblem;
if (reuseSavedPassword)
return null;
if (string.IsNullOrEmpty(password))
return "Enter the password. The client won't start without one; for a new account it becomes the account's password.";
if (!string.Equals(password, confirm, StringComparison.Ordinal))
return "The two passwords don't match.";
return null;
}
}

View file

@ -130,6 +130,24 @@ internal sealed class LaunchAccountProfile
PasswordNeedsReentry = false;
}
/// <summary>
/// Reuses <paramref name="source"/>'s saved password (the same account name on another server).
/// The encrypted blob is copied as it is, so the plain text is never handled; it is readable
/// here because both profiles belong to the same Windows user's settings.
/// </summary>
public void CopyPasswordFrom(LaunchAccountProfile source)
{
ArgumentNullException.ThrowIfNull(source);
if (!string.IsNullOrEmpty(source.LegacyPlainPassword))
{
SetPassword(source.LegacyPlainPassword);
return;
}
PasswordProtected = source.PasswordProtected;
LegacyPlainPassword = null;
PasswordNeedsReentry = source.PasswordNeedsReentry;
}
public void ClearPassword()
{
PasswordProtected = string.Empty;

View file

@ -0,0 +1,87 @@
using System;
using System.IO;
namespace RynthCore.App;
/// <summary>
/// One launch's swap of a saved UserPreferences.ini over the live file in
/// My Documents\Asheron's Call: the saved copy it came from, and the live file as it was before.
/// <paramref name="PreviousLiveBytes"/> is null when there was no live file.
/// </summary>
internal sealed record UserPrefsSwap(
string StashPath,
string LivePath,
byte[] StashBytes,
byte[]? PreviousLiveBytes);
/// <summary>What <see cref="UserPrefsSwapRecovery.Recover"/> did. Null paths mean that file was left alone.</summary>
internal sealed record UserPrefsRecoveryResult(
string? QuarantinedStashPath,
string? QuarantinedLegacyPath,
bool LiveRestored);
/// <summary>
/// Undoes a UserPreferences.ini swap whose client quit at startup. The game reads its
/// resolution and full-screen mode from that file, so a saved copy with a display mode the PC
/// can't use stops every launch with "Could not initialize Direct3D". The saved copy is only
/// refreshed after a normal session, so without this it would be restored on every launch.
/// Pure file work: no UI, no launcher state.
/// </summary>
internal static class UserPrefsSwapRecovery
{
/// <summary>Where a failed saved copy is kept: next to it, renamed so it is never swapped in again.</summary>
internal static string QuarantinePath(string stashPath, DateTime nowLocal) =>
$"{stashPath}.failed-{nowLocal:yyyyMMdd-HHmmss}";
/// <summary>
/// True when the swap changed the live file. When the saved copy matched the live file, the
/// swap can't have caused the failure, so nothing is undone.
/// </summary>
internal static bool SwapChangedPrefs(UserPrefsSwap swap) =>
swap.PreviousLiveBytes == null || !swap.StashBytes.AsSpan().SequenceEqual(swap.PreviousLiveBytes);
/// <summary>
/// Sets the failed saved copy aside (when <paramref name="quarantineStash"/>) and puts the
/// previous live file back (when <paramref name="restoreLive"/>).
/// <paramref name="legacyStashPath"/> is the account's name-only copy: it seeds a missing
/// per-server copy, so it is set aside too when it holds the same failed settings.
/// </summary>
internal static UserPrefsRecoveryResult Recover(
UserPrefsSwap swap,
bool quarantineStash,
bool restoreLive,
string? legacyStashPath,
DateTime nowLocal)
{
string? quarantined = null;
string? quarantinedLegacy = null;
if (quarantineStash && File.Exists(swap.StashPath))
{
quarantined = QuarantinePath(swap.StashPath, nowLocal);
File.Move(swap.StashPath, quarantined, overwrite: true);
if (!string.IsNullOrWhiteSpace(legacyStashPath)
&& !string.Equals(Path.GetFullPath(legacyStashPath), Path.GetFullPath(swap.StashPath), StringComparison.OrdinalIgnoreCase)
&& File.Exists(legacyStashPath)
&& File.ReadAllBytes(legacyStashPath).AsSpan().SequenceEqual(swap.StashBytes))
{
quarantinedLegacy = QuarantinePath(legacyStashPath, nowLocal);
File.Move(legacyStashPath, quarantinedLegacy, overwrite: true);
}
}
bool restored = false;
if (restoreLive)
{
// No live file before the swap: remove it so the game writes its own defaults.
if (swap.PreviousLiveBytes != null)
File.WriteAllBytes(swap.LivePath, swap.PreviousLiveBytes);
else if (File.Exists(swap.LivePath))
File.Delete(swap.LivePath);
restored = true;
}
return new UserPrefsRecoveryResult(quarantined, quarantinedLegacy, restored);
}
}

View file

@ -709,6 +709,10 @@ internal static class AcMainThreadQueue
// drop: dropping arbitrary item/movement actions desyncs the bot far
// worse than a late injection, and the pre-2026-06-12 behavior was
// "always inject" anyway, so proceeding past the cap is never worse).
// Gesture-safe entries at the head still run (RunsDuringGesture): while deferring they
// run from the head of the ring up to the first one that doesn't (FIFO order is kept:
// nothing overtakes a held entry).
bool gestureSafeOnly = false;
if (_ring.Count > 0)
{
// In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate).
@ -716,18 +720,19 @@ internal static class AcMainThreadQueue
{
long nowDefer = NowMs;
if (_drainDeferSinceMs == 0) _drainDeferSinceMs = nowDefer;
if (nowDefer - _drainDeferSinceMs <= DrainDeferMaxMs)
return;
gestureSafeOnly = nowDefer - _drainDeferSinceMs <= DrainDeferMaxMs;
}
_drainDeferSinceMs = 0;
if (!gestureSafeOnly) _drainDeferSinceMs = 0;
}
long runAt = NowMs;
int epochNow = Volatile.Read(ref _loginEpoch);
// Bounded to what is queued now plus a capacity's worth: an action that re-queues
// itself can never spin the main thread.
int budget = Capacity * 2;
while (budget-- > 0 && _ring.TryDequeue(out Entry e))
while (budget-- > 0 && _ring.TryPeek(out Entry e))
{
if (gestureSafeOnly && !RunsDuringGesture(e.Kind)) break;
_ring.Pop();
long age = runAt - e.At;
if (PlayerLifecycleLog.DecideQueued(runAt, e.At, IsTeardown(e)) == WorldTransitionState.Verdict.Drop)
{
@ -880,8 +885,25 @@ internal static class AcMainThreadQueue
// now run on the correct thread, which is the whole point.)
}
}
// The gesture-safe entries emptied the ring: the next held entry gets its own full defer.
if (gestureSafeOnly && _ring.Count == 0) _drainDeferSinceMs = 0;
}
/// <summary>
/// Entries that run while a gesture is in flight (2026-10-14). Each is what the retail
/// client does from a key press at any moment, swing or not: the target select, the
/// keyboard attack (ClientCombatSystem StartAttackRequest/EndAttackRequest, which the client
/// itself holds until the motion allows) and the 0x1B7 cancel. With a crossbow or bow a
/// gesture is in flight nearly all the time, so these waited up to DrainDeferMaxMs every
/// cycle (Silentkelpie: target select and attacks 1.0-1.9 s late, stale attacks dropped).
/// Stance changes, movement, raw attack packets and item moves stay deferred.
/// </summary>
internal static bool RunsDuringGesture(ActionKind kind) => kind switch
{
ActionKind.SetSelectedObject or ActionKind.NativeAttack or ActionKind.CancelAttack => true,
_ => false,
};
// ── RequestId slot (0xC8 appraisal sends from AutoIdService, and every other
// off-thread CombatActionHooks.RequestId caller: plugin RequestIdFn, the
// PluginManager.TickAll login self-identify) ─────────────────────────────

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
@ -27,12 +28,19 @@ namespace RynthCore.Engine.Compatibility;
/// Other paths pass through untouched.
///
/// Why IAT-hook instead of MinHook on the kernel32 export:
/// Decal coexistence. Decal almost certainly already detours kernel32!CreateFile
/// (that's how Decal-injected Thwargle clients can multibox without a
/// second AC install). IAT-hooking acclient.exe's import slot intercepts only
/// acclient.exe's own calls; our detour's call into the saved IAT pointer
/// still routes through any Decal MinHook trampoline on the kernel32 export.
/// No collision; both hooks fire in order.
/// Only the modules that open AC's data files are hooked: acclient.exe
/// (imports CreateFileA) and its CRT MSVCR70.dll (CreateFileA/W, behind
/// fopen/_wfopen). A kernel32 export hook also caught every other module,
/// including d3d9.dll and the GPU driver while AC created its device: their
/// CreateFile calls went through managed code, could wait on the runtime
/// while plugins loaded, and on some PCs AC then failed with "Could not
/// initialize Direct3D" (2026-10-14). The detour preserves the Win32 last
/// error, because callers read it after a successful CreateFile too
/// (ERROR_ALREADY_EXISTS).
/// Decal coexistence: our detour calls the pointer the IAT slot held, so any
/// Decal detour on the kernel32 export still runs. Both hooks fire in order.
/// The slots are restored at engine shutdown (<see cref="Uninstall"/>): the
/// detours live in this engine generation, which hot reload unloads.
/// </summary>
internal static class DatFileShareHooks
{
@ -77,23 +85,16 @@ internal static class DatFileShareHooks
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
// Pinned via static field — Marshal.GetFunctionPointerForDelegate keeps a
// weak handle, so the delegate must be reachable for the process lifetime.
private static CreateFileWDelegate? _wDetour;
private static CreateFileADelegate? _aDetour;
/// <summary>
/// One patched import slot. <see cref="Slot"/> is the address inside the IAT array (not a
/// function address); <see cref="Original"/> is what it held (the real kernel32!CreateFile,
/// or another hooker's detour), written back by <see cref="Uninstall"/>. <see cref="Detour"/>
/// keeps the delegate reachable: the function pointer handed to native code is only valid
/// while it is.
/// </summary>
private sealed record IatHook(string Module, string Function, IntPtr Slot, IntPtr Original, Delegate Detour);
// The IAT slot pointer (the address inside the IAT array, NOT the original
// function address) — needed for the unhook path.
private static IntPtr _wIatSlot;
private static IntPtr _aIatSlot;
// What was in the IAT slot when we patched it. Could be the real
// kernel32!CreateFile, or another hooker's detour if they got there first.
private static IntPtr _wOriginalPtr;
private static IntPtr _aOriginalPtr;
private static CreateFileWDelegate? _wOriginal;
private static CreateFileADelegate? _aOriginal;
private static readonly List<IatHook> _iatHooks = [];
private static string _statusMessage = "Not probed yet.";
@ -137,80 +138,23 @@ internal static class DatFileShareHooks
return;
}
// Hook the kernel32 exports directly with MinHook so we catch ALL
// callers in the process — acclient.exe itself, the CRT layer
// (msvcrt.dll, which is how AC's fopen-style DAT loads route), and
// any plugin or runtime DLL. IAT-hooking acclient.exe alone misses
// CRT-mediated calls because they go through msvcrt's own IAT slot.
IntPtr hKernel32 = GetModuleHandleW("kernel32.dll");
if (hKernel32 == IntPtr.Zero)
{
_statusMessage = "kernel32.dll module handle not found.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
// acclient.exe opens DATs with its own CreateFileA import; its CRT
// (MSVCR70.dll, statically imported, so loaded by now) does fopen/_wfopen
// opens through its CreateFileA/W imports. Nothing else is hooked.
HookModuleImports("acclient.exe", moduleBase);
HookModuleImports("MSVCR70.dll", GetModuleHandleW("MSVCR70.dll"));
// Two-phase install. Phase 1: create both hooks (inactive),
// assign typed trampolines into _aOriginal/_wOriginal. Phase 2:
// memory barrier then Enable. Critical ordering: the detour can
// fire from ANY caller in the process the moment Enable returns,
// and the detour calls _aOriginal/_wOriginal — those fields MUST
// be set first or the first invocation null-derefs and kills the
// engine init thread.
IntPtr aTarget = GetProcAddress(hKernel32, "CreateFileA");
IntPtr wTarget = GetProcAddress(hKernel32, "CreateFileW");
int patched = 0;
if (aTarget != IntPtr.Zero)
if (_iatHooks.Count == 0)
{
_aDetour = CreateFileADetour;
IntPtr aDetourPtr = Marshal.GetFunctionPointerForDelegate(_aDetour);
_aOriginalPtr = MinHook.HookCreate(aTarget, aDetourPtr);
_aOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(_aOriginalPtr);
patched++;
}
if (wTarget != IntPtr.Zero)
{
_wDetour = CreateFileWDetour;
IntPtr wDetourPtr = Marshal.GetFunctionPointerForDelegate(_wDetour);
_wOriginalPtr = MinHook.HookCreate(wTarget, wDetourPtr);
_wOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(_wOriginalPtr);
patched++;
}
// Publish trampolines to other cores before enabling.
Thread.MemoryBarrier();
if (aTarget != IntPtr.Zero)
{
MinHook.Enable(aTarget);
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileA @ 0x{aTarget.ToInt32():X8} (trampoline 0x{_aOriginalPtr.ToInt32():X8}).");
}
else
{
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileA export not found.");
}
if (wTarget != IntPtr.Zero)
{
MinHook.Enable(wTarget);
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileW @ 0x{wTarget.ToInt32():X8} (trampoline 0x{_wOriginalPtr.ToInt32():X8}).");
}
else
{
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileW export not found.");
}
if (patched == 0)
{
_statusMessage = "MinHook on kernel32 CreateFile exports failed.";
_statusMessage = "no CreateFile import slots found in acclient.exe or MSVCR70.dll.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
IsInstalled = true;
_statusMessage = $"DAT share hook installed ({patched} kernel32 export(s) detoured).";
_statusMessage = $"DAT share hook installed ({_iatHooks.Count} import slot(s): " +
string.Join(", ", _iatHooks.Select(h => $"{h.Module}!{h.Function}")) +
"); Direct3D and drivers call CreateFile unhooked.";
RynthLog.Info($"Compat: {_statusMessage}");
}
catch (Exception ex)
@ -220,9 +164,84 @@ internal static class DatFileShareHooks
}
}
/// <summary>
/// Points <paramref name="moduleName"/>'s kernel32 CreateFileA/W import slots at detours that
/// call whatever each slot held. A module that isn't loaded, or doesn't import one of them,
/// is skipped (logged).
/// </summary>
private static void HookModuleImports(string moduleName, IntPtr moduleBase)
{
if (moduleBase == IntPtr.Zero)
{
RynthLog.Compat($"Compat: DAT share - {moduleName} is not loaded; its CreateFile imports are not hooked.");
return;
}
if (TryPatchIatSlot(moduleBase, "CreateFileW", out IntPtr wSlot, out IntPtr wCurrent))
{
CreateFileWDelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(wCurrent);
CreateFileWDelegate detour = (name, access, share, security, disposition, flags, template) =>
CreateFileWDetour(original, name, access, share, security, disposition, flags, template);
InstallSlot(moduleName, "CreateFileW", wSlot, wCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour));
}
if (TryPatchIatSlot(moduleBase, "CreateFileA", out IntPtr aSlot, out IntPtr aCurrent))
{
CreateFileADelegate original = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(aCurrent);
CreateFileADelegate detour = (name, access, share, security, disposition, flags, template) =>
CreateFileADetour(original, name, access, share, security, disposition, flags, template);
InstallSlot(moduleName, "CreateFileA", aSlot, aCurrent, detour, Marshal.GetFunctionPointerForDelegate(detour));
}
}
/// <summary>
/// Records the hook (so the delegate stays reachable) before the slot is written: the
/// detour can run on any thread the moment the pointer lands.
/// </summary>
private static void InstallSlot(string moduleName, string function, IntPtr slot, IntPtr original, Delegate detour, IntPtr detourPtr)
{
var hook = new IatHook(moduleName, function, slot, original, detour);
_iatHooks.Add(hook);
Thread.MemoryBarrier();
if (WriteIatPointer(slot, detourPtr))
{
RynthLog.Info($"Compat: DAT share - hooked {moduleName}!{function} import (slot 0x{slot.ToInt32():X8}, was 0x{original.ToInt32():X8}).");
return;
}
_iatHooks.Remove(hook);
}
/// <summary>
/// Writes every patched slot back to what it held, at engine shutdown. The detours are in
/// this engine generation, which hot reload unloads; a slot left pointing at them would
/// crash the next CreateFile.
/// </summary>
public static void Uninstall()
{
if (_iatHooks.Count == 0)
return;
int restored = 0;
foreach (IatHook hook in _iatHooks)
{
if (WriteIatPointer(hook.Slot, hook.Original))
restored++;
}
RynthLog.Info($"Compat: DAT share - restored {restored}/{_iatHooks.Count} CreateFile import slot(s).");
_iatHooks.Clear();
IsInstalled = false;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
// Plain import (no SetLastError marshalling): it must leave the value it sets.
[DllImport("kernel32.dll", EntryPoint = "SetLastError")]
private static extern void SetWin32LastError(uint dwErrCode);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
@ -402,10 +421,8 @@ internal static class DatFileShareHooks
&& path.EndsWith(DatExtension, StringComparison.OrdinalIgnoreCase);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint GetLastError();
private static IntPtr CreateFileWDetour(
CreateFileWDelegate original,
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
@ -435,21 +452,25 @@ internal static class DatFileShareHooks
{
}
IntPtr result = _wOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
IntPtr result = original(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
// Captured by the SetLastError=true delegate; the caller may read it even on success.
int lastError = Marshal.GetLastPInvokeError();
if (isAnyDatExt)
{
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
int err = result == new IntPtr(-1) ? lastError : 0;
string fname = Path.GetFileName(path!);
string note = isDat ? "filtered" : "passthrough";
RynthLog.Info($"Compat: DAT share - W [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
}
SetWin32LastError((uint)lastError);
return result;
}
private static IntPtr CreateFileADetour(
CreateFileADelegate original,
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
@ -479,17 +500,19 @@ internal static class DatFileShareHooks
{
}
IntPtr result = _aOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
IntPtr result = original(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
int lastError = Marshal.GetLastPInvokeError();
if (isAnyDatExt)
{
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
int err = result == new IntPtr(-1) ? lastError : 0;
string fname = Path.GetFileName(path!);
string note = isDat ? "filtered" : "passthrough";
RynthLog.Info($"Compat: DAT share - A [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
}
SetWin32LastError((uint)lastError);
return result;
}
}

View file

@ -207,6 +207,9 @@ internal static class EngineLifecycle
// Process-wide events: under CoreCLR they would hold this generation.
Step("EntryPoint.UninstallManagedExceptionHandlers", EntryPoint.UninstallManagedExceptionHandlers);
// IAT slots aren't MinHook hooks: write them back before this generation unloads.
Step("DatFileShareHooks.Uninstall", Compatibility.DatFileShareHooks.Uninstall);
Step("MH_DisableHook(ALL)", () =>
{
// DisableHook restores the original code at every hooked function — that's

View file

@ -323,8 +323,9 @@ internal sealed class SettingsFace : IImGuiPanel
ImGuiNET.ImGui.PopStyleColor();
}
// Label | [caption]; Click posts its own work (never runs plugin code on AC's thread).
private static void ButtonRow(SettingRow row, float w)
// Label | [caption]; Edit changes the copy and saves it like any other row, Click posts its
// own work (never runs plugin code on AC's thread).
private void ButtonRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
@ -333,7 +334,14 @@ internal sealed class SettingsFace : IImGuiPanel
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
{
if (row.Edit != null)
{
row.Edit(_data);
SettingsCommands.Save(_data.Clone());
}
row.Click?.Invoke();
}
Tooltip(row);
}

View file

@ -237,14 +237,16 @@ internal sealed class RynthAiSettings
// Salvage with the 0x027D request sent straight to the server, no salvage panel on screen
// (default on; used when the engine has API v81; an older RynthAi doesn't send it).
public bool SalvageWithoutPanel { get; set; } = true;
// Inter-Item Delay and Closing Delay: RynthAi's corpse looting never reads them (not shown in
// the panel since 2026.10.5.59), carried so a save doesn't send them missing.
public int LootInterItemDelayMs { get; set; } = 50;
public int LootContentSettleMs { get; set; } = 100;
public int LootEmptyCorpseMs { get; set; } = 300;
public int LootContentSettleMs { get; set; } = LootTimerDefaults.ContentSettleMs;
public int LootEmptyCorpseMs { get; set; } = LootTimerDefaults.EmptyCorpseMs;
public int LootClosingDelayMs { get; set; } = 200;
public int LootAssessWindowMs { get; set; } = 200;
public int LootRetryTimeoutMs { get; set; } = 500;
public int LootOpenRetryMs { get; set; } = 1500;
public int LootCorpseTimeoutMs { get; set; } = 12000;
public int LootAssessWindowMs { get; set; } = LootTimerDefaults.AssessWindowMs;
public int LootRetryTimeoutMs { get; set; } = LootTimerDefaults.RetryTimeoutMs;
public int LootOpenRetryMs { get; set; } = LootTimerDefaults.OpenRetryMs;
public int LootCorpseTimeoutMs { get; set; } = LootTimerDefaults.CorpseTimeoutMs;
public int SalvageOpenDelayFirstMs { get; set; } = 400;
public int SalvageOpenDelayFastMs { get; set; } = 50;
public int SalvageAddDelayFirstMs { get; set; } = 600;
@ -329,6 +331,43 @@ internal static unsafe class SettingsCommands
}
}
/// <summary>
/// The optimized loot timer defaults, in ms: the same values as RynthSuite's LootBaseline.cs
/// (RynthAi 0.5.65), measured from live corpse looting on ACE (226 corpses, 39 pickups). Keep
/// the two in step. The Loot Timers rows show each one in brackets after the label.
/// </summary>
internal static class LootTimerDefaults
{
public const int ContentSettleMs = 100;
public const int EmptyCorpseMs = 300;
/// <summary>Above the 256 ms 95th percentile of the measured appraisal replies.</summary>
public const int AssessWindowMs = 300;
/// <summary>No pickup needed a retry at 1000 ms (it counts from when the character is still).</summary>
public const int RetryTimeoutMs = 1000;
public const int OpenRetryMs = 1500;
public const int CorpseTimeoutMs = 12000;
/// <summary>A row label with its optimized default: "Assess Window (300)".</summary>
public static string Label(string name, int defaultMs) => $"{name} ({defaultMs})";
/// <summary>Writes the six optimized defaults into <paramref name="s"/>.</summary>
public static void Apply(RynthAiSettings s)
{
s.LootContentSettleMs = ContentSettleMs;
s.LootEmptyCorpseMs = EmptyCorpseMs;
s.LootAssessWindowMs = AssessWindowMs;
s.LootRetryTimeoutMs = RetryTimeoutMs;
s.LootOpenRetryMs = OpenRetryMs;
s.LootCorpseTimeoutMs = CorpseTimeoutMs;
}
/// <summary>True when all six timers are at the optimized defaults.</summary>
public static bool AllDefault(RynthAiSettings s) =>
s.LootContentSettleMs == ContentSettleMs && s.LootEmptyCorpseMs == EmptyCorpseMs &&
s.LootAssessWindowMs == AssessWindowMs && s.LootRetryTimeoutMs == RetryTimeoutMs &&
s.LootOpenRetryMs == OpenRetryMs && s.LootCorpseTimeoutMs == CorpseTimeoutMs;
}
// ── Schema ─────────────────────────────────────────────────────────────────
internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status,
@ -418,7 +457,10 @@ internal sealed record SettingRow(
Func<RynthAiSettings, string>? GetText = null,
Action<RynthAiSettings, string>? SetText = null,
// Text rows: greyed hint shown while the box is empty.
string? Hint = null)
string? Hint = null,
// Button rows that change settings: applied to the panel's copy, which is then saved like
// any other edit (Click, when also set, runs after).
Action<RynthAiSettings>? Edit = null)
{
public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s);
}
@ -521,6 +563,10 @@ internal static class SettingsSchema
private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click);
// A button that edits the settings (the panel saves the result like a typed value).
private static SettingRow EditButton(string label, string buttonText, Action<RynthAiSettings> edit, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Edit: edit);
private static SettingRow Text(string label, Func<RynthAiSettings, string> get, Action<RynthAiSettings, string> set,
string? tip = null, string? hint = null) =>
new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint);
@ -1075,15 +1121,30 @@ internal static class SettingsSchema
Bool("Salvage Without The Panel", s => s.SalvageWithoutPanel, (s, v) => s.SalvageWithoutPanel = v,
"Salvage (and combine bags) by sending the salvage request to the server directly:\nAC's salvage panel never opens. When a request changes nothing, that batch is tried once\nthrough the panel. Needs an engine with plugin API v82; otherwise the panel is used."),
Spacer(),
Section("Loot Timers (ms)"),
Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25),
Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25),
Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25),
Int("Closing Delay", s => s.LootClosingDelayMs, (s, v) => s.LootClosingDelayMs = v, 0, 5000, 25),
Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25),
Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100),
Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100),
Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500),
// The optimized default is in brackets after each label (LootTimerDefaults). Inter-Item
// Delay and Closing Delay are not shown: RynthAi's corpse looting never reads them.
Section("Loot Timers (ms) - (optimized default)"),
EditButton("Optimized defaults", "Use optimized defaults", LootTimerDefaults.Apply,
"Set all six loot timers to the optimized defaults, measured from live looting on ACE\n" +
"(226 corpses). RynthAi's log line [LootSettings] marks each timer baseline or custom."),
Int(LootTimerDefaults.Label("Content Settle", LootTimerDefaults.ContentSettleMs),
s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25,
"Wait after an open for the container's items. Only used when the items\naren't already known; on ACE they always were."),
Int(LootTimerDefaults.Label("Empty Corpse Wait", LootTimerDefaults.EmptyCorpseMs),
s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25,
"Wait for a corpse's contents before probing it or calling it empty."),
Int(LootTimerDefaults.Label("Assess Window", LootTimerDefaults.AssessWindowMs),
s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25,
"Hold items for their appraisal. Measured replies: 127 ms typical,\n256 ms at the 95th percentile, 350 ms at most."),
Int(LootTimerDefaults.Label("Loot Retry Timeout", LootTimerDefaults.RetryTimeoutMs),
s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100,
"Wait, once the character is still, before resending a pickup that hasn't\nlanded. Too short resends pickups the server is still doing."),
Int(LootTimerDefaults.Label("Corpse Open Retry", LootTimerDefaults.OpenRetryMs),
s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100,
"Wait before sending another open to a corpse that hasn't opened."),
Int(LootTimerDefaults.Label("Corpse Timeout", LootTimerDefaults.CorpseTimeoutMs),
s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500,
"Give up on a claimed corpse after this long. The clock stops during combat\nand buffing."),
Spacer(),
Section("Salvage Timers (ms) - First / Fast"),
Int("Open (First)", s => s.SalvageOpenDelayFirstMs, (s, v) => s.SalvageOpenDelayFirstMs = v, 0, 5000, 50),

View file

@ -334,7 +334,18 @@ internal static class SettingsPanel
case SettingKind.Spacer:
return Spacer();
case SettingKind.Button:
return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip);
return ButtonRow(row.Label, row.ButtonText ?? row.Label, () =>
{
// A settings edit is pushed like a typed value; the tab is rebuilt so the
// number boxes show the new values.
if (row.Edit != null)
{
row.Edit(state.Data);
Push(state);
state.Rebuild?.Invoke();
}
row.Click?.Invoke();
}, row.Tooltip);
case SettingKind.TraceCategories:
return TraceCategoriesRow(state, row);
case SettingKind.ServerPick:

View file

@ -253,6 +253,13 @@ internal static class LaunchCommand
"Password needs re-entering: edit the account in the launcher and type it again.");
return 2;
}
if (pwd.Length == 0)
{
// The client refuses an empty password before it connects ("You can only run the
// game from the launcher program") and exits within seconds.
Log($"No password is saved for account '{acct}'. Launch it once from the launcher to enter it, or edit the account.");
return 2;
}
string arguments = server.Emulator == EmulatorKind.Gdle
? string.Join(" ",

View file

@ -29,6 +29,8 @@
<Compile Include="..\..\src\RynthCore.App\LaunchServerProfile.cs" Link="App\LaunchServerProfile.cs" />
<Compile Include="..\..\src\RynthCore.App\KnownServerCatalog.cs" Link="App\KnownServerCatalog.cs" />
<Compile Include="..\..\src\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="App\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\..\src\RynthCore.App\FirstLoginRules.cs" Link="App\FirstLoginRules.cs" />
<Compile Include="..\..\src\RynthCore.App\UserPrefsSwapRecovery.cs" Link="App\UserPrefsSwapRecovery.cs" />
</ItemGroup>
</Project>

View file

@ -179,8 +179,21 @@ internal static class Program
string preview = builder.BuildMaskedArguments(ace, a);
Check(!preview.Contains("t3st") && preview.Contains("-v " + AcLaunchArgumentBuilder.PasswordMask), "preview masked: " + preview);
LaunchAccountProfile noPw = loaded.AccountProfiles.First(x => x.Id == "b");
Check(builder.BuildMaskedArguments(ace, noPw).Contains("-v \"\""), "preview of an account without a password");
Check(builder.BuildArguments(ace, noPw).Contains("-v \"\""), "no saved password still launches as before (empty)");
Check(AcLaunchArgumentBuilder.NeedsPassword(noPw) && !AcLaunchArgumentBuilder.NeedsPassword(a), "NeedsPassword: only the account without one");
Check(builder.BuildMaskedArguments(ace, noPw).StartsWith("No password is saved for account 'B'"),
"preview of an account without a password says so: " + builder.BuildMaskedArguments(ace, noPw));
// The client exits with "You can only run the game from the launcher program" on an
// empty password (Conquest, 2026-10-13), so the launch is refused instead.
string refusal = Throws(() => builder.BuildArguments(ace, noPw));
Check(refusal.StartsWith("No password is saved for account 'B'"), "no saved password: launch refused: " + refusal);
Check(Throws(() => builder.BuildArguments(gdle, noPw)).StartsWith("No password"), "GDLE refused too");
// Account names: ACE's 50-character limit; GDLE's "account:password" argument.
Check(AcLaunchArgumentBuilder.AccountNameProblem("SK", AcEmulatorKind.Ace) == null, "a short name is fine");
Check(AcLaunchArgumentBuilder.AccountNameProblem(new string('x', 51), AcEmulatorKind.Ace)?.Contains("50") == true, "51 characters: too long");
Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Ace) == null, "a colon is fine on ACE");
Check(AcLaunchArgumentBuilder.AccountNameProblem("a:b", AcEmulatorKind.Gdle) != null, "a colon is refused on GDLE");
Check(AcLaunchArgumentBuilder.AccountNameProblem(" ", AcEmulatorKind.Ace) != null, "blank is refused");
LaunchAccountProfile copy = a.Clone();
Check(copy.PasswordProtected == a.PasswordProtected, "Clone keeps the encrypted password");
@ -309,6 +322,96 @@ internal static class Program
Check(KnownServerCatalog.FindByHost("172.111.230.127")?.Id == "frostace", "FrostACE by IP");
Check(KnownServerCatalog.FindByHost("") == null && KnownServerCatalog.FindByHost(null) == null, "empty host");
});
// ── First Login dialog rules (a new server: no password, no characters yet) ──
Scenario("first login on a new server", root, () =>
{
var withPw = new LaunchAccountProfile { Id = "ilt", AccountName = "silentkelpie" };
withPw.SetPassword(Pw);
var noPwSame = new LaunchAccountProfile { Id = "other", AccountName = "SilentKelpie" };
var conquest = new LaunchAccountProfile { Id = "new", AccountName = "SK", CharacterName = LaunchAccountProfile.NoneOption };
var all = new List<LaunchAccountProfile> { withPw, noPwSame, conquest };
Check(FirstLoginRules.KnownAccountNames(all, "new").SequenceEqual(new[] { "silentkelpie" }),
"known names: the others, distinct ignoring case, not this profile's own");
Check(FirstLoginRules.SavedPasswordSource(all, "SILENTKELPIE", "new")?.Id == "ilt",
"the same name with a saved password can be reused (case ignored)");
Check(FirstLoginRules.SavedPasswordSource(all, "SK", "new") == null, "a new name has none to reuse");
Check(FirstLoginRules.SavedPasswordSource(all, "silentkelpie", "ilt") == null, "never the profile itself");
var copy = new LaunchAccountProfile { AccountName = "silentkelpie" };
copy.CopyPasswordFrom(withPw);
Check(copy.PasswordProtected == withPw.PasswordProtected && copy.TryGetPasswordForLaunch(out string reused, out _) && reused == Pw,
"reuse copies the encrypted blob, and it decrypts");
var none = new List<string>();
List<string> firstChoices = FirstLoginRules.LoginChoices(none, conquest.CharacterName);
Check(firstChoices.SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect }),
"no characters yet: only stop at character select (the old (None) isn't listed)");
Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, none) == "",
"stop with none known saves \"\" so the first character created is picked next time");
var chars = new List<string> { "Alpha", "Beta" };
Check(FirstLoginRules.LoginChoices(chars, "Gamma").SequenceEqual(new[] { FirstLoginRules.StopAtCharacterSelect, "Gamma", "Alpha", "Beta" }),
"several characters: all listed, the saved one kept even if not seen yet");
Check(FirstLoginRules.CharacterNameFor("Beta", chars) == "Beta", "picking a character saves it");
Check(FirstLoginRules.CharacterNameFor(FirstLoginRules.StopAtCharacterSelect, chars) == LaunchAccountProfile.NoneOption,
"stop with characters known saves the explicit (None)");
Check(FirstLoginRules.Problem("SK", "", "", false, AcEmulatorKind.Ace)?.StartsWith("Enter the password") == true, "a password is required");
Check(FirstLoginRules.Problem("SK", "a", "b", false, AcEmulatorKind.Ace)?.Contains("don't match") == true, "the confirmation must match");
Check(FirstLoginRules.Problem("SK", "pw", "pw", false, AcEmulatorKind.Ace) == null, "name + matching password: ready");
Check(FirstLoginRules.Problem("silentkelpie", "", "", true, AcEmulatorKind.Ace) == null, "reusing a saved password needs no typing");
Check(FirstLoginRules.Problem("a:b", "pw", "pw", false, AcEmulatorKind.Gdle) != null, "GDLE name with a colon refused");
Check(FirstLoginRules.Problem("", "pw", "pw", false, AcEmulatorKind.Ace) != null, "a name is required");
});
// A saved UserPreferences.ini whose display mode the PC can't use made every launch
// fail with "Could not initialize Direct3D"; a quick exit must undo that swap.
Scenario("prefs swap: did the swap change the live file", root, () =>
{
byte[] a = "[Display]\nResolution=2560x1440\n"u8.ToArray();
byte[] b = "[Display]\nResolution=1920x1080\n"u8.ToArray();
Check(!UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, (byte[])a.Clone())), "same bytes: not the cause");
Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, b)), "different bytes: changed");
Check(UserPrefsSwapRecovery.SwapChangedPrefs(new UserPrefsSwap("s", "l", a, null)), "no live file before: changed");
});
Scenario("prefs swap: failed stash set aside, live file put back", root, () =>
{
var (swap, legacy) = PrefsSwapFiles(legacyMatches: true);
var now = new DateTime(2026, 10, 14, 16, 30, 5);
UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: true, restoreLive: true, legacy, now);
Check(!File.Exists(swap.StashPath), "stash no longer swappable");
Check(r.QuarantinedStashPath == swap.StashPath + ".failed-20261014-163005" && File.Exists(r.QuarantinedStashPath), "stash kept as .failed-<time>");
Check(!File.Exists(legacy) && r.QuarantinedLegacyPath != null, "identical name-only stash set aside too (it would re-seed)");
Check(r.LiveRestored && File.ReadAllBytes(swap.LivePath).SequenceEqual(swap.PreviousLiveBytes!), "live file back to its pre-swap bytes");
});
Scenario("prefs swap: different name-only stash kept", root, () =>
{
var (swap, legacy) = PrefsSwapFiles(legacyMatches: false);
UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, true, true, legacy, DateTime.Now);
Check(File.Exists(legacy) && r.QuarantinedLegacyPath == null, "name-only stash with other settings left alone");
});
Scenario("prefs swap: later swap or profile override", root, () =>
{
var (swap, legacy) = PrefsSwapFiles(legacyMatches: true);
File.WriteAllText(swap.LivePath, "another account's settings");
UserPrefsRecoveryResult r = UserPrefsSwapRecovery.Recover(swap, quarantineStash: false, restoreLive: false, legacy, DateTime.Now);
Check(File.Exists(swap.StashPath) && File.Exists(legacy), "override: the user's file is never renamed");
Check(!r.LiveRestored && File.ReadAllText(swap.LivePath) == "another account's settings", "later swap: live file untouched");
});
Scenario("prefs swap: no live file before", root, () =>
{
var (swap, _) = PrefsSwapFiles(legacyMatches: false);
swap = swap with { PreviousLiveBytes = null };
UserPrefsSwapRecovery.Recover(swap, true, true, null, DateTime.Now);
Check(!File.Exists(swap.LivePath), "live file removed so the game writes its defaults");
});
}
finally
{
@ -347,6 +450,23 @@ internal static class Program
private static InjectionMode Mode(AppSettings s, string id) => s.AccountProfiles.First(a => a.Id == id).InjectionMode;
/// <summary>
/// A swap as the launcher leaves it: the failed per-server stash copied over the live file,
/// plus the account's name-only stash (same bytes when <paramref name="legacyMatches"/>).
/// </summary>
private static (UserPrefsSwap Swap, string LegacyPath) PrefsSwapFiles(bool legacyMatches)
{
string stash = Path.Combine(_dir, "SK@Conquest.ini");
string legacy = Path.Combine(_dir, "SK.ini");
string live = Path.Combine(_dir, "UserPreferences.ini");
byte[] bad = "[Display]\nResolution=2560x1440\nWindowed=False\n"u8.ToArray();
byte[] good = "[Display]\nResolution=1920x1080\nWindowed=True\n"u8.ToArray();
File.WriteAllBytes(stash, bad);
File.WriteAllBytes(legacy, legacyMatches ? bad : good);
File.WriteAllBytes(live, bad);
return (new UserPrefsSwap(stash, live, bad, good), legacy);
}
private static void CheckSharedFilesSafe()
{
foreach (string path in new[] { Main_, Bak })
@ -413,6 +533,13 @@ internal static class Program
Id = "s", Name = "Test", Host = "127.0.0.1", Port = 9000, Emulator = kind
};
/// <summary>The message <paramref name="action"/> throws ("" when it doesn't throw).</summary>
private static string Throws(Action action)
{
try { action(); return string.Empty; }
catch (Exception ex) { return ex.Message; }
}
private static string PwOf(AppSettings s, string id) =>
s.AccountProfiles.First(a => a.Id == id).TryGetPasswordForLaunch(out string pw, out _) ? pw : "<unreadable>";