RynthCore as of 2026-09-05 (internal f9abab9)

A snapshot of the working tree for aelrynth.com/git/: the code, build files
and public docs. Internal review notes and agent instructions are left out.
MIT licensed; see LICENSE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-09-25 21:22:59 -04:00
commit 68c301dac8
277 changed files with 86286 additions and 0 deletions

View file

@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RynthCore.App;
internal sealed class AcClientLaunchSettingsService
{
private const string UserPreferencesFileName = "UserPreferences.ini";
private const string NetSectionName = "Net";
private const string ComputeUniquePortKey = "ComputeUniquePort";
private const string IntroVideoFileName = "turbine_logo_ac.avi";
private const string DisabledIntroVideoSuffix = ".rynthcore-disabled";
public void Apply(string acClientPath, bool allowMultipleClients, bool skipIntroVideos, Action<string>? log = null)
{
if (string.IsNullOrWhiteSpace(acClientPath) || !File.Exists(acClientPath))
return;
string gameDirectory = Path.GetDirectoryName(acClientPath) ?? string.Empty;
UpdateUserPreferences(allowMultipleClients, log);
UpdateIntroVideoState(gameDirectory, skipIntroVideos, log);
}
/// <summary>
/// Copies a per-account UserPreferences.ini stash over the live file in
/// 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.
/// </summary>
public bool SwapUserPreferences(string? stashPath, bool allowMultipleClients, Action<string>? log = null)
{
if (string.IsNullOrWhiteSpace(stashPath))
return false;
if (!File.Exists(stashPath))
{
log?.Invoke($"User prefs swap skipped: stash file not found at {stashPath}.");
return false;
}
string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call");
string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName);
try
{
Directory.CreateDirectory(prefsDirectory);
File.Copy(stashPath, prefsPath, overwrite: true);
}
catch (Exception ex)
{
log?.Invoke($"User prefs swap failed copying {stashPath}: {ex.Message}");
return false;
}
// 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;
}
private static void UpdateUserPreferences(bool allowMultipleClients, Action<string>? log)
{
string documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string prefsDirectory = Path.Combine(documentsDirectory, "Asheron's Call");
string prefsPath = Path.Combine(prefsDirectory, UserPreferencesFileName);
Directory.CreateDirectory(prefsDirectory);
List<string> lines = File.Exists(prefsPath)
? File.ReadAllLines(prefsPath).ToList()
: [];
bool changed = SetIniValue(lines, NetSectionName, ComputeUniquePortKey, allowMultipleClients ? "True" : "False");
if (!changed)
return;
File.WriteAllLines(prefsPath, lines);
log?.Invoke($"Launch setting applied: ComputeUniquePort={(allowMultipleClients ? "True" : "False")} in UserPreferences.ini.");
}
private static void UpdateIntroVideoState(string gameDirectory, bool skipIntroVideos, Action<string>? log)
{
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
return;
string introVideoPath = Path.Combine(gameDirectory, IntroVideoFileName);
string parkedIntroVideoPath = introVideoPath + DisabledIntroVideoSuffix;
if (skipIntroVideos)
{
if (File.Exists(parkedIntroVideoPath))
return;
if (!File.Exists(introVideoPath))
return;
File.Move(introVideoPath, parkedIntroVideoPath);
log?.Invoke("Launch setting applied: intro video parked so AC opens without the turbine logo movie.");
return;
}
if (!File.Exists(parkedIntroVideoPath) || File.Exists(introVideoPath))
return;
File.Move(parkedIntroVideoPath, introVideoPath);
log?.Invoke("Launch setting applied: intro video restored.");
}
private static bool SetIniValue(List<string> lines, string sectionName, string key, string value)
{
string sectionHeader = $"[{sectionName}]";
int sectionIndex = lines.FindIndex(line => string.Equals(line.Trim(), sectionHeader, StringComparison.OrdinalIgnoreCase));
if (sectionIndex < 0)
{
if (lines.Count > 0 && !string.IsNullOrWhiteSpace(lines[^1]))
lines.Add(string.Empty);
lines.Add(sectionHeader);
lines.Add($"{key}={value}");
return true;
}
int nextSectionIndex = sectionIndex + 1;
while (nextSectionIndex < lines.Count && !IsSectionHeader(lines[nextSectionIndex]))
nextSectionIndex++;
for (int i = sectionIndex + 1; i < nextSectionIndex; i++)
{
string line = lines[i].Trim();
if (!line.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase))
continue;
string updatedLine = $"{key}={value}";
if (string.Equals(lines[i], updatedLine, StringComparison.Ordinal))
return false;
lines[i] = updatedLine;
return true;
}
lines.Insert(nextSectionIndex, $"{key}={value}");
return true;
}
private static bool IsSectionHeader(string line)
{
string trimmed = line.Trim();
return trimmed.StartsWith("[", StringComparison.Ordinal) && trimmed.EndsWith("]", StringComparison.Ordinal);
}
}

View file

@ -0,0 +1,88 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace RynthCore.App;
internal sealed class AcClientLoginAutomationService
{
private const uint WmMouseMove = 0x0200;
private const uint WmLButtonDown = 0x0201;
private const uint WmLButtonUp = 0x0202;
private const nuint MkLButton = 0x0001;
private const int LogoBypassX = 350;
private const int LogoBypassY = 100;
private const int ClickAttempts = 4;
[DllImport("user32.dll", SetLastError = true)]
private static extern nint PostMessageW(nint hWnd, uint msg, nuint wParam, nint lParam);
public async Task TryBypassLoginLogosAsync(int processId, Action<string>? log = null)
{
try
{
nint hwnd = await WaitForMainWindowAsync(processId).ConfigureAwait(false);
if (hwnd == nint.Zero)
{
log?.Invoke($"Skip Login Logos: no main window found for PID {processId}.");
return;
}
await Task.Delay(2500).ConfigureAwait(false);
for (int i = 0; i < ClickAttempts; i++)
{
if (!TrySendClick(hwnd, LogoBypassX, LogoBypassY))
{
log?.Invoke($"Skip Login Logos: click {i + 1}/{ClickAttempts} failed for PID {processId}.");
return;
}
log?.Invoke($"Skip Login Logos: sent click {i + 1}/{ClickAttempts} to PID {processId}.");
await Task.Delay(1000).ConfigureAwait(false);
}
}
catch (Exception ex)
{
log?.Invoke($"Skip Login Logos failed for PID {processId}: {ex.Message}");
}
}
private static async Task<nint> WaitForMainWindowAsync(int processId)
{
DateTime deadline = DateTime.UtcNow.AddSeconds(20);
while (DateTime.UtcNow < deadline)
{
try
{
using Process process = Process.GetProcessById(processId);
if (process.HasExited)
return nint.Zero;
process.Refresh();
if (process.MainWindowHandle != nint.Zero)
return process.MainWindowHandle;
}
catch
{
return nint.Zero;
}
await Task.Delay(500).ConfigureAwait(false);
}
return nint.Zero;
}
private static bool TrySendClick(nint hwnd, int x, int y)
{
if (hwnd == nint.Zero)
return false;
nint lParam = (nint)((y << 16) | (x & 0xFFFF));
nint move = PostMessageW(hwnd, WmMouseMove, 0, lParam);
nint down = PostMessageW(hwnd, WmLButtonDown, MkLButton, lParam);
nint up = PostMessageW(hwnd, WmLButtonUp, 0, lParam);
return move != 0 && down != 0 && up != 0;
}
}

View file

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.App;
internal sealed class AcLaunchArgumentBuilder
{
public string BuildArguments(LaunchServerProfile server, LaunchAccountProfile account)
{
ArgumentNullException.ThrowIfNull(server);
ArgumentNullException.ThrowIfNull(account);
Validate(server, account);
return server.Emulator switch
{
AcEmulatorKind.Ace => string.Join(" ",
"-a", Quote(account.AccountName),
"-v", Quote(account.Password),
"-h", Quote(server.ConnectionString),
"-rodat", server.RodatEnabled ? "on" : "off"),
AcEmulatorKind.Gdle => string.Join(" ",
"-h", Quote(server.Host),
"-p", server.Port.ToString(CultureInfo.InvariantCulture),
"-a", Quote($"{account.AccountName}:{account.Password}"),
"-rodat", server.RodatEnabled ? "on" : "off"),
_ => throw new InvalidOperationException($"Unsupported emulator type '{server.Emulator}'.")
};
}
public string Describe(LaunchServerProfile server, LaunchAccountProfile account)
{
return $"{server.DisplayName} / {account.DisplayName}";
}
private static void Validate(LaunchServerProfile server, LaunchAccountProfile account)
{
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(server.Name))
errors.Add("Server name is required.");
if (string.IsNullOrWhiteSpace(server.Host))
errors.Add("Server host is required.");
if (server.Port <= 0)
errors.Add("Server port must be greater than zero.");
if (string.IsNullOrWhiteSpace(account.AccountName))
errors.Add("Account name is required.");
if (errors.Count > 0)
throw new InvalidOperationException(string.Join(" ", errors));
}
private static string Quote(string value)
{
value ??= string.Empty;
if (value.Length == 0)
return "\"\"";
if (!NeedsQuoting(value))
return value;
return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
}
private static bool NeedsQuoting(string value)
{
foreach (char ch in value)
{
if (char.IsWhiteSpace(ch) || ch == '"')
return true;
}
return false;
}
}

View file

@ -0,0 +1,60 @@
using System.Collections.Generic;
namespace RynthCore.App;
internal sealed class AppSettings
{
public string AcClientPath { get; set; } = string.Empty;
public string EnginePath { get; set; } = string.Empty;
public string LaunchArguments { get; set; } = string.Empty;
public string SelectedServerProfileId { get; set; } = string.Empty;
public string SelectedAccountProfileId { get; set; } = string.Empty;
public List<string> CheckedLaunchAccountProfileIds { get; set; } = [];
public string SelectedMainTabId { get; set; } = "launcher";
public bool AllowMultipleClients { get; set; }
public bool SkipIntroVideos { get; set; }
public bool SkipLoginLogos { get; set; }
public bool AutoLaunch { get; set; }
public bool AutoInjectAfterLaunch { get; set; } = true;
public bool WatchForAcStart { get; set; } = true;
public int LaunchStaggerMs { get; set; } = 250;
public int CrashRelaunchLimitInWindow { get; set; } = 3;
public int CrashRelaunchWindowMinutes { get; set; } = 5;
public bool OverrideWindowTitle { get; set; } = true;
/// When true, the launcher kills any RynthCore-mode acclient.exe it
/// launched that hasn't reached IsLoggedIn within
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,
/// patcher hangs, and "you have been disconnected" failure screens at
/// the front of the launch flow. Off by default — destructive.
/// Decal-mode clients are skipped (no engine = no IsLoggedIn signal).
public bool KillStuckClients { get; set; }
public int StuckClientTimeoutSeconds { get; set; } = 60;
/// When true (default), the launcher kills+relaunches a RynthCore-mode
/// client whose per-PID heartbeat shows the WEDGE signature: login=1 and
/// fps=0 sustained for <see cref="WedgeRestartSeconds"/> while the engine
/// heartbeat keeps flowing (AC main thread dead, process alive — the AV
/// class). Containment for the residual corruption AVs: an overnight soak
/// loses ~2 minutes to a wedge instead of the rest of the night.
/// Minimized windows are exempt (some drivers stop presenting). Relaunch
/// rides the existing crash-relaunch machinery (counts toward the
/// circuit breaker) and needs AutoLaunch for the relaunch half.
public bool AutoRestartWedgedClients { get; set; } = true;
public int WedgeRestartSeconds { get; set; } = 90;
public List<string> EnabledPluginIds { get; set; } = [];
public List<string> PluginDllPaths { get; set; } = [];
/// User-added plugin DLL paths whose checkboxes are currently unchecked.
/// The path stays in <see cref="PluginDllPaths"/> (so the row remains in
/// the UI), but is filtered out when syncing PluginPaths into engine.json.
/// Case-insensitive set semantics; comparisons must use OrdinalIgnoreCase.
public List<string> DisabledPluginDllPaths { get; set; } = [];
public List<LaunchServerProfile> ServerProfiles { get; set; } = [];
public List<LaunchAccountProfile> AccountProfiles { get; set; } = [];
public double? WindowX { get; set; }
public double? WindowY { get; set; }
public double? WindowWidth { get; set; }
public double? WindowHeight { get; set; }
}

View file

@ -0,0 +1,102 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.App;
internal static class AppSettingsStore
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
Converters =
{
new JsonStringEnumConverter()
}
};
private static string SettingsDirectory =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
private static string BackupPath => SettingsPath + ".bak";
/// <summary>
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
/// possibly recovered from the .bak). Null when the load was clean. The
/// launcher surfaces this after startup — this store is shared source and
/// must not depend on launcher-only logging.
/// </summary>
public static string? LastLoadDiagnostic { get; private set; }
public static AppSettings Load()
{
LastLoadDiagnostic = null;
if (!File.Exists(SettingsPath))
return new AppSettings();
if (TryLoadFrom(SettingsPath, out AppSettings? settings))
return settings!;
// The primary file is corrupt (truncated write, disk issue). This file
// holds every server/account profile — NEVER silently reset to defaults.
// Quarantine the bad file for post-mortem, then try the backup the
// atomic Save() keeps.
string quarantine = SettingsPath + ".corrupt-" + DateTime.Now.ToString("yyyyMMdd-HHmmss");
try { File.Move(SettingsPath, quarantine); }
catch { quarantine = "(quarantine move failed)"; }
if (File.Exists(BackupPath) && TryLoadFrom(BackupPath, out AppSettings? backup))
{
try { File.Copy(BackupPath, SettingsPath, overwrite: true); } catch { }
LastLoadDiagnostic = $"appsettings.json was corrupt — recovered from .bak (bad file kept at {quarantine}).";
return backup!;
}
LastLoadDiagnostic = $"appsettings.json was corrupt and no usable .bak exists — starting with defaults (bad file kept at {quarantine}).";
return new AppSettings();
}
private static bool TryLoadFrom(string path, out AppSettings? settings)
{
settings = null;
try
{
string json = File.ReadAllText(path);
AppSettings loaded = JsonSerializer.Deserialize<AppSettings>(json, JsonOptions) ?? new AppSettings();
using JsonDocument document = JsonDocument.Parse(json);
JsonElement root = document.RootElement;
if (!root.TryGetProperty(nameof(AppSettings.AutoLaunch), out _) &&
root.TryGetProperty("AutoRelaunch", out JsonElement legacyAutoRelaunch) &&
legacyAutoRelaunch.ValueKind is JsonValueKind.True or JsonValueKind.False)
{
loaded.AutoLaunch = legacyAutoRelaunch.GetBoolean();
}
settings = loaded;
return true;
}
catch
{
return false;
}
}
public static void Save(AppSettings settings)
{
// Atomic write: serialize to a temp file, then swap it in. A crash or
// power cut mid-write can no longer truncate the live file (which holds
// every server/account profile and is rewritten constantly); the swap
// also maintains a .bak Load() can recover from.
Directory.CreateDirectory(SettingsDirectory);
string tmp = SettingsPath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions));
if (File.Exists(SettingsPath))
File.Replace(tmp, SettingsPath, BackupPath);
else
File.Move(tmp, SettingsPath);
}
}

View file

@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
namespace RynthCore.App;
internal static class CharacterCacheStore
{
/// Strict reader — only returns characters from the server-scoped file
/// for this (account, server) pair. Will NOT fall through to the
/// account-only file. Use this when correctness across accounts/servers
/// matters more than tolerance for missing data (e.g. UI dropdowns where
/// stale legacy files would leak the wrong account's characters).
public static List<string> ReadStrict(string accountName, string serverName)
{
try
{
if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(serverName))
return [];
string safeAccount = SanitizeFileName(accountName);
string safeServer = SanitizeFileName(serverName);
return ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount));
}
catch
{
return [];
}
}
public static List<string> Read(string accountName, string serverName = "")
{
try
{
if (string.IsNullOrWhiteSpace(accountName))
return [];
string safeAccount = SanitizeFileName(accountName);
if (!string.IsNullOrWhiteSpace(serverName))
{
string safeServer = SanitizeFileName(serverName);
List<string> serverCharacters = ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount));
if (serverCharacters.Count > 0)
return serverCharacters;
}
return ReadCharacterFile(GetAccountScopedPath(safeAccount));
}
catch
{
return [];
}
}
public static void Write(string accountName, string serverName, IReadOnlyCollection<string> characters)
{
if (string.IsNullOrWhiteSpace(accountName))
return;
List<string> sanitizedCharacters = SanitizeCharacters(characters);
if (sanitizedCharacters.Count == 0)
return;
Directory.CreateDirectory(GetRootDirectory());
string safeAccount = SanitizeFileName(accountName);
string json = BuildCharacterListJson(sanitizedCharacters, DateTime.Now);
if (!string.IsNullOrWhiteSpace(serverName))
{
string safeServer = SanitizeFileName(serverName);
File.WriteAllText(GetServerScopedPath(safeServer, safeAccount), json);
return;
}
File.WriteAllText(GetAccountScopedPath(safeAccount), json);
}
public static void UpsertCharacter(string accountName, string serverName, string characterName)
{
if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(characterName))
return;
List<string> characters = Read(accountName, serverName);
if (!characters.Contains(characterName, StringComparer.OrdinalIgnoreCase))
characters.Add(characterName);
Write(accountName, serverName, characters);
}
public static void DeleteForAccount(string accountName)
{
if (string.IsNullOrWhiteSpace(accountName))
return;
try
{
string rootDirectory = GetRootDirectory();
if (!Directory.Exists(rootDirectory))
return;
string safeAccount = SanitizeFileName(accountName);
foreach (string file in Directory.GetFiles(rootDirectory, $"characters_*_{safeAccount}.json"))
{
try { File.Delete(file); } catch { }
}
string accountScopedPath = GetAccountScopedPath(safeAccount);
if (File.Exists(accountScopedPath))
{
try { File.Delete(accountScopedPath); } catch { }
}
}
catch
{
}
}
private static string GetRootDirectory() =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string GetServerScopedPath(string safeServerName, string safeAccountName) =>
Path.Combine(GetRootDirectory(), $"characters_{safeServerName}_{safeAccountName}.json");
private static string GetAccountScopedPath(string safeAccountName) =>
Path.Combine(GetRootDirectory(), $"characters_{safeAccountName}.json");
private static List<string> ReadCharacterFile(string filePath)
{
if (!File.Exists(filePath))
return [];
using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(filePath));
if (!document.RootElement.TryGetProperty("Characters", out JsonElement value) || value.ValueKind != JsonValueKind.Array)
return [];
return value.EnumerateArray()
.Select(element => element.GetString()?.Trim() ?? string.Empty)
.Where(character => !string.IsNullOrWhiteSpace(character))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static List<string> SanitizeCharacters(IEnumerable<string>? characters)
{
return (characters ?? [])
.Select(character => character?.Trim() ?? string.Empty)
.Where(character => !string.IsNullOrWhiteSpace(character))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static string BuildCharacterListJson(IReadOnlyList<string> characters, DateTime updatedAt)
{
using var stream = new MemoryStream();
using (var writer = new Utf8JsonWriter(stream))
{
writer.WriteStartObject();
writer.WritePropertyName("Characters");
writer.WriteStartArray();
foreach (string character in characters)
writer.WriteStringValue(character);
writer.WriteEndArray();
writer.WriteString("UpdatedAt", updatedAt.ToString("O", CultureInfo.InvariantCulture));
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.ToArray());
}
private static string SanitizeFileName(string name)
{
var sb = new StringBuilder(name.Length);
foreach (char c in name)
sb.Append(char.IsLetterOrDigit(c) ? c : '_');
return sb.ToString();
}
}

View file

@ -0,0 +1,73 @@
using System;
using System.IO;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>
/// Locates a local Decal install via the same registry probe ThwargLauncher
/// uses. Decal records its agent directory at HKLM\SOFTWARE\Decal\Agent (the
/// launcher is x86, so we transparently see the Wow6432Node redirect on 64-bit
/// Windows). Inject.dll lives directly in that directory and exports
/// DecalStartup, which is the entry point the suspended-launch injector calls.
/// </summary>
internal static class DecalLocator
{
private const string AgentSubKey = @"SOFTWARE\Decal\Agent";
private const string AgentPathValue = "AgentPath";
private const string PortalPathValue = "PortalPath";
private const string InjectDllName = "Inject.dll";
private const string AcClientName = "acclient.exe";
/// <summary>Returns the absolute path to Decal's Inject.dll, or null if
/// Decal is not registered or the file cannot be found beside its agent
/// directory.</summary>
public static string? TryGetInjectDllPath()
{
try
{
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(AgentSubKey);
if (key == null)
return null;
string? agentPath = key.GetValue(AgentPathValue) as string;
if (string.IsNullOrWhiteSpace(agentPath))
return null;
string injectPath = Path.Combine(agentPath, InjectDllName);
return File.Exists(injectPath) ? injectPath : null;
}
catch
{
return null;
}
}
/// <summary>Returns the AC client install Decal expects, derived from its
/// PortalPath registry value (e.g. C:\Turbine\Asheron's Call). Used when an
/// account is set to Decal mode and the launcher's global AcClientPath
/// points elsewhere (e.g. the RynthCore-private duplicate). Returns null if
/// not registered or the file is missing.</summary>
public static string? TryGetDecalAcClientPath()
{
try
{
using RegistryKey? key = Registry.LocalMachine.OpenSubKey(AgentSubKey);
if (key == null)
return null;
string? portalPath = key.GetValue(PortalPathValue) as string;
if (string.IsNullOrWhiteSpace(portalPath))
return null;
string acPath = Path.Combine(portalPath, AcClientName);
return File.Exists(acPath) ? acPath : null;
}
catch
{
return null;
}
}
public static bool IsInstalled() => TryGetInjectDllPath() != null;
}

View file

@ -0,0 +1,17 @@
namespace RynthCore.App;
/// <summary>
/// Per-account choice of which modding stack to inject when launching the AC
/// client. Selected from the launcher's per-row Injection Method dropdown.
/// </summary>
internal enum InjectionMode
{
/// <summary>RynthCore.Loader.dll → RynthCore.Engine.dll injected via the
/// in-process injector. The native RynthCore stack.</summary>
RynthCore = 0,
/// <summary>Decal's Inject.dll injected with its DecalStartup export. The
/// account runs against Decal + UBService + VTank or whatever Decal plugins
/// the user has registered.</summary>
Decal = 1,
}

View file

@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
namespace RynthCore.App;
internal sealed class LaunchAccountProfile
{
/// Sentinel stored in CharacterName when the user has explicitly opted out of auto-login.
/// At launch time, ResolveTargetCharacterForLaunch translates this to an empty string so
/// the engine's CharacterCapture sees a blank TargetCharacter and skips auto-login entirely.
public const string NoneOption = "(None — no auto-login)";
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string AccountName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string CharacterName { get; set; } = string.Empty;
public string Alias { get; set; } = string.Empty;
public string ServerId { get; set; } = string.Empty;
// Saved AC client window placement, restored on next launch and updated
// when the user moves/resizes the window. Null until first save.
public int? WindowX { get; set; }
public int? WindowY { get; set; }
public int? WindowWidth { get; set; }
public int? WindowHeight { get; set; }
/// Optional path to a per-account stash of UserPreferences.ini. If set, the
/// launcher copies this file over My Documents\Asheron's Call\UserPreferences.ini
/// before launching this account. Empty/missing path = no swap, AC reads
/// whatever happens to be in place.
public string UserPrefsPath { get; set; } = string.Empty;
/// Which modding stack to inject when this account is launched. Defaults to
/// RynthCore. Decal mode launches AC with Decal's Inject.dll instead and
/// does not load the RynthCore engine into the process.
public InjectionMode InjectionMode { get; set; } = InjectionMode.RynthCore;
/// Per-character chat commands to dispatch after login completes. Key is
/// the character name (case-insensitive on lookup). Each list entry is one
/// command line — "/say hi", "/fellow create xyz", etc. — sent in order
/// with a small gap between commands. Empty/missing key = no commands.
public Dictionary<string, List<string>> OnLoginCommandsByCharacter { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// Milliseconds to wait after the engine observes login-complete before
/// dispatching the first OnLogin command. Matches Thwargle's default.
public int OnLoginWaitMs { get; set; } = 3000;
public string DisplayName
{
get
{
string launchLabel = !string.IsNullOrWhiteSpace(CharacterName) && CharacterName != NoneOption
? CharacterName
: Alias;
return string.IsNullOrWhiteSpace(launchLabel)
? AccountName
: $"{launchLabel} ({AccountName})";
}
}
public LaunchAccountProfile Clone()
{
return new LaunchAccountProfile
{
Id = Id,
AccountName = AccountName,
Password = Password,
CharacterName = CharacterName,
Alias = Alias,
ServerId = ServerId,
WindowX = WindowX,
WindowY = WindowY,
WindowWidth = WindowWidth,
WindowHeight = WindowHeight,
UserPrefsPath = UserPrefsPath,
InjectionMode = InjectionMode,
OnLoginCommandsByCharacter = new Dictionary<string, List<string>>(OnLoginCommandsByCharacter, StringComparer.OrdinalIgnoreCase),
OnLoginWaitMs = OnLoginWaitMs,
};
}
public void CopyFrom(LaunchAccountProfile source)
{
Id = source.Id;
AccountName = source.AccountName;
Password = source.Password;
CharacterName = source.CharacterName;
Alias = source.Alias;
ServerId = source.ServerId;
WindowX = source.WindowX;
WindowY = source.WindowY;
WindowWidth = source.WindowWidth;
WindowHeight = source.WindowHeight;
UserPrefsPath = source.UserPrefsPath;
InjectionMode = source.InjectionMode;
OnLoginCommandsByCharacter = new Dictionary<string, List<string>>(source.OnLoginCommandsByCharacter, StringComparer.OrdinalIgnoreCase);
OnLoginWaitMs = source.OnLoginWaitMs;
}
public override string ToString()
{
return DisplayName;
}
}

View file

@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.App;
internal sealed class LaunchContextRecord
{
public int ProcessId { get; set; }
public string AccountName { get; set; } = string.Empty;
public string ServerName { get; set; } = string.Empty;
public string TargetCharacter { get; set; } = string.Empty;
public bool SkipLoginLogos { get; set; }
public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;
/// Chat commands the engine should dispatch after login-complete fires
/// for this PID. Resolved by the launcher from
/// LaunchAccountProfile.OnLoginCommandsByCharacter at launch time. Null /
/// empty = nothing to dispatch.
public List<string>? OnLoginCommands { get; set; }
/// Milliseconds to wait after login-complete before sending the first
/// command. 0 (or omitted) = use the engine's default.
public int OnLoginWaitMs { get; set; }
}
internal static class LaunchContextStore
{
private const string LegacyFileName = "launch_context.json";
private const string ContextDirectoryName = "launch_contexts";
public static LaunchContextRecord CreateRecord(
string accountName,
string serverName,
string targetCharacter,
bool skipLoginLogos,
List<string>? onLoginCommands = null,
int onLoginWaitMs = 0)
{
return new LaunchContextRecord
{
AccountName = accountName ?? string.Empty,
ServerName = serverName ?? string.Empty,
TargetCharacter = targetCharacter ?? string.Empty,
SkipLoginLogos = skipLoginLogos,
CreatedAtUtc = DateTime.UtcNow,
OnLoginCommands = onLoginCommands,
OnLoginWaitMs = onLoginWaitMs
};
}
public static void WriteLegacy(LaunchContextRecord context)
{
ArgumentNullException.ThrowIfNull(context);
Directory.CreateDirectory(GetRootDirectory());
File.WriteAllText(GetLegacyPath(), JsonSerializer.Serialize(context));
}
public static void WriteForProcess(int processId, LaunchContextRecord context)
{
ArgumentNullException.ThrowIfNull(context);
Directory.CreateDirectory(GetContextDirectory());
var processContext = new LaunchContextRecord
{
ProcessId = processId,
AccountName = context.AccountName,
ServerName = context.ServerName,
TargetCharacter = context.TargetCharacter,
SkipLoginLogos = context.SkipLoginLogos,
CreatedAtUtc = DateTime.UtcNow,
OnLoginCommands = context.OnLoginCommands,
OnLoginWaitMs = context.OnLoginWaitMs
};
File.WriteAllText(GetProcessPath(processId), JsonSerializer.Serialize(processContext));
}
public static LaunchContextRecord? TryReadForProcess(int processId)
{
string path = GetProcessPath(processId);
if (!File.Exists(path))
return null;
try
{
return JsonSerializer.Deserialize<LaunchContextRecord>(File.ReadAllText(path));
}
catch
{
return null;
}
}
public static Dictionary<int, LaunchContextRecord> ReadForActiveProcesses(IEnumerable<int> activeProcessIds)
{
var result = new Dictionary<int, LaunchContextRecord>();
foreach (int processId in activeProcessIds.Distinct())
{
LaunchContextRecord? context = TryReadForProcess(processId);
if (context != null)
result[processId] = context;
}
return result;
}
public static void DeleteStaleProcessFiles(IEnumerable<int> activeProcessIds)
{
string contextDirectory = GetContextDirectory();
if (!Directory.Exists(contextDirectory))
return;
HashSet<int> active = activeProcessIds.ToHashSet();
foreach (string filePath in Directory.GetFiles(contextDirectory, "launch_context_*.json"))
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
const string prefix = "launch_context_";
if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
continue;
if (!int.TryParse(fileName[prefix.Length..], out int processId) || active.Contains(processId))
continue;
try
{
File.Delete(filePath);
}
catch
{
}
}
}
private static string GetRootDirectory() =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string GetLegacyPath() =>
Path.Combine(GetRootDirectory(), LegacyFileName);
private static string GetContextDirectory() =>
Path.Combine(GetRootDirectory(), ContextDirectoryName);
private static string GetProcessPath(int processId) =>
Path.Combine(GetContextDirectory(), $"launch_context_{processId}.json");
}

View file

@ -0,0 +1,56 @@
using System;
namespace RynthCore.App;
internal enum AcEmulatorKind
{
Ace,
Gdle
}
internal sealed class LaunchServerProfile
{
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string Name { get; set; } = string.Empty;
public string Alias { get; set; } = string.Empty;
public string Host { get; set; } = string.Empty;
public int Port { get; set; }
public AcEmulatorKind Emulator { get; set; } = AcEmulatorKind.Ace;
public bool RodatEnabled { get; set; }
public string DisplayName =>
string.IsNullOrWhiteSpace(Alias) ? Name : $"{Alias} ({Name})";
public string ConnectionString =>
string.IsNullOrWhiteSpace(Host) || Port <= 0 ? string.Empty : $"{Host}:{Port}";
public LaunchServerProfile Clone()
{
return new LaunchServerProfile
{
Id = Id,
Name = Name,
Alias = Alias,
Host = Host,
Port = Port,
Emulator = Emulator,
RodatEnabled = RodatEnabled
};
}
public void CopyFrom(LaunchServerProfile source)
{
Id = source.Id;
Name = source.Name;
Alias = source.Alias;
Host = source.Host;
Port = source.Port;
Emulator = source.Emulator;
RodatEnabled = source.RodatEnabled;
}
public override string ToString()
{
return DisplayName;
}
}

View file

@ -0,0 +1,10 @@
namespace RynthCore.App;
internal sealed class PluginDefinition
{
public required string Id { get; init; }
public required string Name { get; init; }
public required string Summary { get; init; }
public required string StatusText { get; init; }
public bool RuntimeImplemented { get; init; }
}

View file

@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
namespace RynthCore.App;
internal sealed class SessionStateRecord
{
public int ProcessId { get; set; }
public string AccountName { get; set; } = string.Empty;
public string ServerName { get; set; } = string.Empty;
public string TargetCharacter { get; set; } = string.Empty;
public string CharacterName { get; set; } = string.Empty;
public DateTime LaunchStartedAtUtc { get; set; } = DateTime.UtcNow;
public DateTime? LoginCompletedAtUtc { get; set; }
public DateTime LastUpdatedAtUtc { get; set; } = DateTime.UtcNow;
public bool IsLoggedIn { get; set; }
/// Set by the engine when LogoutLifecycleHooks observes a logout (clean
/// or server-driven disconnect). Stays set across the post-login reaper
/// window so the launcher can detect "stuck on disconnect/char-select".
public DateTime? LogoutAtUtc { get; set; }
}
internal static class SessionStateStore
{
private const string SessionDirectoryName = "sessions";
public static void WriteForProcess(int processId, SessionStateRecord record)
{
ArgumentNullException.ThrowIfNull(record);
Directory.CreateDirectory(GetSessionDirectory());
record.ProcessId = processId;
record.LastUpdatedAtUtc = DateTime.UtcNow;
// Explicit no-BOM UTF-8 — Encoding.UTF8 emits a BOM under NativeAOT which
// breaks JsonDocument.Parse on the launcher side.
File.WriteAllText(GetProcessPath(processId), BuildSessionJson(record), new System.Text.UTF8Encoding(false));
}
public static SessionStateRecord? TryReadForProcess(int processId)
{
string path = GetProcessPath(processId);
if (!File.Exists(path))
return null;
try
{
byte[] bytes = File.ReadAllBytes(path);
// Strip UTF-8 BOM if present — the engine writes with Encoding.UTF8
// which emits a BOM (EF BB BF) under NativeAOT, and JsonDocument.Parse
// on a byte span rejects the BOM as an invalid JSON start character.
ReadOnlyMemory<byte> content = bytes;
if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
content = new ReadOnlyMemory<byte>(bytes, 3, bytes.Length - 3);
using JsonDocument document = JsonDocument.Parse(content);
JsonElement root = document.RootElement;
var record = new SessionStateRecord
{
ProcessId = GetInt32(root, "ProcessId"),
AccountName = GetString(root, "AccountName"),
ServerName = GetString(root, "ServerName"),
TargetCharacter = GetString(root, "TargetCharacter"),
CharacterName = GetString(root, "CharacterName"),
LaunchStartedAtUtc = GetDateTime(root, "LaunchStartedAtUtc") ?? DateTime.UtcNow,
LoginCompletedAtUtc = GetDateTime(root, "LoginCompletedAtUtc"),
LastUpdatedAtUtc = GetDateTime(root, "LastUpdatedAtUtc") ?? DateTime.UtcNow,
IsLoggedIn = GetBoolean(root, "IsLoggedIn"),
LogoutAtUtc = GetDateTime(root, "LogoutAtUtc")
};
if (record.ProcessId == 0)
record.ProcessId = processId;
return record;
}
catch
{
return null;
}
}
public static Dictionary<int, SessionStateRecord> ReadForActiveProcesses(IEnumerable<int> activeProcessIds)
{
var result = new Dictionary<int, SessionStateRecord>();
foreach (int processId in activeProcessIds.Distinct())
{
SessionStateRecord? record = TryReadForProcess(processId);
if (record != null)
result[processId] = record;
}
return result;
}
public static void DeleteStaleProcessFiles(IEnumerable<int> activeProcessIds)
{
string directory = GetSessionDirectory();
if (!Directory.Exists(directory))
return;
HashSet<int> active = activeProcessIds.ToHashSet();
foreach (string filePath in Directory.GetFiles(directory, "session_*.json"))
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
const string prefix = "session_";
if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
continue;
if (!int.TryParse(fileName[prefix.Length..], out int processId) || active.Contains(processId))
continue;
try
{
File.Delete(filePath);
}
catch
{
}
}
}
private static string GetRootDirectory() =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string GetSessionDirectory() =>
Path.Combine(GetRootDirectory(), SessionDirectoryName);
private static string GetProcessPath(int processId) =>
Path.Combine(GetSessionDirectory(), $"session_{processId}.json");
private static string BuildSessionJson(SessionStateRecord record)
{
using var stream = new MemoryStream();
using (var writer = new Utf8JsonWriter(stream))
{
writer.WriteStartObject();
writer.WriteNumber("ProcessId", record.ProcessId);
writer.WriteString("AccountName", record.AccountName ?? string.Empty);
writer.WriteString("ServerName", record.ServerName ?? string.Empty);
writer.WriteString("TargetCharacter", record.TargetCharacter ?? string.Empty);
writer.WriteString("CharacterName", record.CharacterName ?? string.Empty);
writer.WriteString("LaunchStartedAtUtc", record.LaunchStartedAtUtc.ToString("O", CultureInfo.InvariantCulture));
if (record.LoginCompletedAtUtc.HasValue)
writer.WriteString("LoginCompletedAtUtc", record.LoginCompletedAtUtc.Value.ToString("O", CultureInfo.InvariantCulture));
else
writer.WriteNull("LoginCompletedAtUtc");
writer.WriteString("LastUpdatedAtUtc", record.LastUpdatedAtUtc.ToString("O", CultureInfo.InvariantCulture));
writer.WriteBoolean("IsLoggedIn", record.IsLoggedIn);
if (record.LogoutAtUtc.HasValue)
writer.WriteString("LogoutAtUtc", record.LogoutAtUtc.Value.ToString("O", CultureInfo.InvariantCulture));
else
writer.WriteNull("LogoutAtUtc");
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.ToArray());
}
private static string GetString(JsonElement root, string propertyName)
{
return root.TryGetProperty(propertyName, out JsonElement value) && value.ValueKind == JsonValueKind.String
? value.GetString() ?? string.Empty
: string.Empty;
}
private static int GetInt32(JsonElement root, string propertyName)
{
return root.TryGetProperty(propertyName, out JsonElement value) && value.ValueKind == JsonValueKind.Number && value.TryGetInt32(out int number)
? number
: 0;
}
private static bool GetBoolean(JsonElement root, string propertyName)
{
return root.TryGetProperty(propertyName, out JsonElement value) && value.ValueKind is JsonValueKind.True or JsonValueKind.False
? value.GetBoolean()
: false;
}
private static DateTime? GetDateTime(JsonElement root, string propertyName)
{
if (!root.TryGetProperty(propertyName, out JsonElement value))
return null;
if (value.ValueKind == JsonValueKind.Null)
return null;
if (value.ValueKind != JsonValueKind.String)
return null;
return DateTime.TryParse(
value.GetString(),
CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind,
out DateTime parsed)
? parsed
: null;
}
}