Initial
Rust validation / Windows x64 build and tests (push) Waiting to run
Rust validation / Formatting (push) Failing after 27s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s

This commit is contained in:
EonaCat committed 2026-12-04 21:03:25 +01:00
1 parent 2cff35f215
commit 1b0d534e6c
358 files changed
+253978 -74

No files matched your search

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>EonaCat.XSBOX.Launcher</AssemblyName>
<RootNamespace>EonaCat.XSBOX.Launcher</RootNamespace>
<ApplicationIcon>..\..\assets\eonacat-logo.ico</ApplicationIcon>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>false</SelfContained>
<ApplicationHighDpiMode>SystemAware</ApplicationHighDpiMode>
<InvariantGlobalization>true</InvariantGlobalization>
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
<DebugType>none</DebugType>
<TieredPGO>false</TieredPGO>
<!-- Optional: uncomment for noticeably faster startup (needs the crossgen pack from NuGet at publish time).
<PublishReadyToRun>true</PublishReadyToRun> -->
</PropertyGroup>
<ItemGroup>
<Content Include="..\..\assets\eonacat-logo.ico" Link="assets\eonacat-logo.ico" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
+196
View File
@@ -0,0 +1,196 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
namespace EonaCat.XSBOX.Launcher;
internal sealed partial class LauncherForm
{
const string PreloadPrefix = "EONACAT_PRELOAD|";
const int MaxOutputChars = 250_000;
const int KeptOutputChars = 180_000;
const int MaxLinesPerTick = 500;
// Engine output arrives on thread-pool threads. It is queued here and drained by a UI timer in
// batches, instead of posting one UI message (and one TextBox append) per line.
readonly ConcurrentQueue<(string Text, bool FromGame)> pendingLines = new();
Process? gameProcess;
bool engineBusy;
void LaunchGame()
{
SaveSettings();
if (gameProcess is { HasExited: false })
{
status.Text = "The game is already running.";
return;
}
if (!File.Exists(exe)) { MessageBox.Show(this, "eonacat-xsbox.exe was not found. Build the project first using build.bat.", "Engine not built", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
var selectedExe = selectedGame?.Executable;
if (string.IsNullOrWhiteSpace(selectedExe) || !File.Exists(selectedExe))
{
if (!string.IsNullOrWhiteSpace(gamePath.Text) && File.Exists(gamePath.Text)) selectedExe = gamePath.Text;
else { BrowseGame(); if (!File.Exists(gamePath.Text)) return; selectedExe = gamePath.Text; }
}
var p = new ProcessStartInfo(exe)
{
UseShellExecute = false, CreateNoWindow = true,
RedirectStandardOutput = true, RedirectStandardError = true,
WorkingDirectory = root
};
p.Environment["EONACAT_XS_HOME"] = home;
// Use the values chosen in the launcher (fullscreen defaults to "stretch") instead of forcing "1".
SetEngineEnvironment(p, "EONACAT_XS_FULLSCREEN", "stretch");
SetEngineEnvironment(p, "EONACAT_XS_MOUSE_CAPTURE", "1");
p.ArgumentList.Add("play"); p.ArgumentList.Add(selectedExe!);
var process = new Process { StartInfo = p, EnableRaisingEvents = true };
process.OutputDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue((e.Data, true)); };
process.ErrorDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue((e.Data, true)); };
process.Exited += (_, _) =>
{
if (IsDisposed || !IsHandleCreated) return;
try
{
BeginInvoke(new Action(() =>
{
PumpEngineOutput();
preloadDialog?.Close(); preloadDialog = null;
status.Text = "Game process exited.";
if (ReferenceEquals(gameProcess, process)) gameProcess = null;
process.Dispose();
}));
}
catch (InvalidOperationException) { } // window closed while the game was shutting down
};
try
{
if (!process.Start()) { process.Dispose(); MessageBox.Show(this, "The game engine could not be started.", "Launch failed", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
}
catch (Exception ex)
{
process.Dispose();
MessageBox.Show(this, "The game engine could not be started: " + ex.Message, "Launch failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
gameProcess = process;
process.BeginOutputReadLine(); process.BeginErrorReadLine();
status.Text = $"Launching {selectedGame?.Name ?? Path.GetFileName(Path.GetDirectoryName(selectedExe!))}…";
}
void SetEngineEnvironment(ProcessStartInfo info, string key, string fallback)
{
var value = editors.TryGetValue(key, out var editor) && editor is ComboBox combo
? combo.SelectedItem?.ToString() ?? fallback
: fallback;
if (string.IsNullOrEmpty(value)) info.Environment.Remove(key); // "Auto"/off: leave it unset
else info.Environment[key] = value;
}
/// <summary>Drains queued engine output on the UI thread: one parse pass, one TextBox append.</summary>
void PumpEngineOutput()
{
if (IsDisposed || pendingLines.IsEmpty) return;
var text = new StringBuilder();
for (var n = 0; n < MaxLinesPerTick && pendingLines.TryDequeue(out var item); n++)
{
if (item.FromGame && HandlePreloadSignal(item.Text)) continue;
if (item.FromGame) preloadDialog?.SetDetail(item.Text);
text.AppendLine(item.Text);
}
if (text.Length > 0) AppendOutput(text.ToString());
}
void AppendOutput(string text)
{
output.AppendText(text);
if (output.TextLength > MaxOutputChars)
{
output.Text = output.Text[^KeptOutputChars..];
output.SelectionStart = output.TextLength;
output.ScrollToCaret();
}
}
/// <summary>Returns true when the line was a preload control signal (and so is not shown in the log).</summary>
bool HandlePreloadSignal(string line)
{
if (!line.StartsWith(PreloadPrefix, StringComparison.Ordinal)) return false;
var signal = line[PreloadPrefix.Length..].Trim();
if (signal == "START")
{
preloadDialog?.Close();
preloadDialog = new PreloadProgressDialog();
preloadDialog.Show(this);
status.Text = "Preparing shaders and graphics pipelines…";
}
else if (signal == "SHADERS") preloadDialog?.SetStage("Compiling shaders", "Translating the game's shader library and filling the shader cache.");
else if (signal == "PIPELINES") preloadDialog?.SetStage("Building graphics pipelines", "Compiling pipeline states for your graphics adapter.");
else if (signal.StartsWith("DONE", StringComparison.Ordinal))
{
preloadDialog?.Complete(signal == "DONE");
status.Text = signal == "DONE" ? "Shader and pipeline preparation complete." : "Preload finished with warnings; starting the game.";
}
return true;
}
async Task InstallDetectedGpuRuntime()
{
string gpu = DetectGpuVendor();
if (gpu == "NVIDIA") await RunEngineCommand("get-dlss");
else if (gpu == "AMD")
{
var answer = MessageBox.Show(this, "An AMD Radeon adapter was detected. The AMD FidelityFX package supplies the FSR 3 frame-generation runtime only; it does NOT add an AMD Radeon rendering backend. Download the AMD runtime anyway?", "AMD runtime compatibility", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (answer == DialogResult.Yes) await RunEngineCommand("get-fsr");
}
else MessageBox.Show(this, "No supported NVIDIA or AMD adapter was identified automatically. Choose the appropriate vendor installer manually, or update your graphics driver.", "GPU not identified", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
static string DetectGpuVendor()
{
try
{
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}");
if (key != null)
foreach (var sub in key.GetSubKeyNames().Where(n => n.Length == 4 && int.TryParse(n, out _)))
{
using var item = key.OpenSubKey(sub);
var desc = (item?.GetValue("DriverDesc")?.ToString() ?? "") + " " + (item?.GetValue("ProviderName")?.ToString() ?? "");
if (desc.Contains("NVIDIA", StringComparison.OrdinalIgnoreCase)) return "NVIDIA";
if (desc.Contains("AMD", StringComparison.OrdinalIgnoreCase) || desc.Contains("Radeon", StringComparison.OrdinalIgnoreCase)) return "AMD";
}
}
catch { }
return "Unknown";
}
async Task RunEngineCommand(string command, string? argument = null)
{
if (!File.Exists(exe)) { MessageBox.Show(this, "Build eonacat-xsbox.exe first with build.bat.", "Engine not built", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
if (engineBusy) { status.Text = "Another engine command is still running. Please wait for it to finish."; return; }
engineBusy = true;
try
{
PumpEngineOutput();
AppendOutput($"> eonacat-xsbox.exe {command}{(argument == null ? "" : " " + argument)}{Environment.NewLine}");
tabs.SelectedTab = tabs.TabPages["Installer log"];
var psi = new ProcessStartInfo(exe) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = root, CreateNoWindow = true };
psi.Environment["EONACAT_XS_HOME"] = home;
psi.ArgumentList.Add(command);
if (!string.IsNullOrWhiteSpace(argument)) psi.ArgumentList.Add(argument);
using var proc = new Process { StartInfo = psi, EnableRaisingEvents = true };
proc.OutputDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue((e.Data, false)); };
proc.ErrorDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue(("ERROR: " + e.Data, false)); };
proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine();
await proc.WaitForExitAsync();
PumpEngineOutput();
status.Text = proc.ExitCode == 0 ? $"{command} completed." : $"{command} failed (exit {proc.ExitCode}). See Installer log.";
}
catch (Exception ex)
{
AppendOutput($"ERROR: {ex.Message}{Environment.NewLine}");
status.Text = $"{command} could not run: {ex.Message}";
}
finally { engineBusy = false; }
}
}
+305
View File
@@ -0,0 +1,305 @@
using System.Collections.Concurrent;
using System.IO.Enumeration;
using System.Text.Json;
using System.Xml.Linq;
namespace EonaCat.XSBOX.Launcher;
internal sealed partial class LauncherForm
{
const string ScarlettExe = "game_scarlett_master.exe";
const string GameConfig = "MicrosoftGame.config";
static readonly string[] CommonFolderNames = { "XboxGames", "Games", "Xbox", "GameDumps", "GTA6" };
static readonly JsonSerializerOptions LibraryJson = new() { WriteIndented = true };
// Icons are read from disk once per game, not on every redraw of the tile list.
readonly Dictionary<string, Bitmap?> tileIcons = new(StringComparer.OrdinalIgnoreCase);
string? lastLibraryJson;
bool scanning;
static EnumerationOptions ScanOptions(int depth) => new()
{
RecurseSubdirectories = true,
IgnoreInaccessible = true,
AttributesToSkip = FileAttributes.ReparsePoint | FileAttributes.System,
MaxRecursionDepth = depth
};
void BuildGamesPage()
{
var tab = new TabPage("Installed games") { Name = "Installed games", BackColor = BackColor, ForeColor = ForeColor };
tab.Controls.Add(gameTiles);
tab.Controls.Add(CreatePageHeader("Installed games", "Detected Xbox game folders · Select a tile to choose the active title"));
tabs.TabPages.Add(tab);
}
void LoadGameLibrary()
{
Directory.CreateDirectory(home);
try
{
if (File.Exists(gameListPath))
{
var json = File.ReadAllText(gameListPath);
games.AddRange(JsonSerializer.Deserialize<List<GameEntry>>(json) ?? new List<GameEntry>());
}
}
catch { games.Clear(); }
var last = File.Exists(selectedGamePath) ? File.ReadAllText(selectedGamePath).Trim() : "";
if (string.IsNullOrWhiteSpace(last))
{
var legacy = Path.Combine(home, "launcher-game.txt");
if (File.Exists(legacy)) last = File.ReadAllText(legacy).Trim();
}
selectedGame = games.FirstOrDefault(g => string.Equals(g.Executable, last, StringComparison.OrdinalIgnoreCase) && File.Exists(g.Executable));
if (selectedGame == null && File.Exists(last))
{
var dir = Path.GetDirectoryName(last)!;
selectedGame = new GameEntry(new DirectoryInfo(dir).Parent?.Name ?? new DirectoryInfo(dir).Name, last, dir);
AddOrUpdateGame(selectedGame, false);
}
if (selectedGame == null && File.Exists(Path.Combine(root, "game_scarlett_master.exe")))
{
var exePath = Path.Combine(root, "game_scarlett_master.exe");
selectedGame = new GameEntry(new DirectoryInfo(root).Name, exePath, root);
AddOrUpdateGame(selectedGame, false);
}
if (selectedGame != null) gamePath.Text = selectedGame.Executable;
RenderGameTiles();
}
void SaveGameLibrary()
{
Directory.CreateDirectory(home);
var json = JsonSerializer.Serialize(games.OrderBy(g => g.Name).ToList(), LibraryJson);
if (json != lastLibraryJson) // skip the disk write when nothing changed
{
File.WriteAllText(gameListPath + ".tmp", json);
File.Move(gameListPath + ".tmp", gameListPath, true);
lastLibraryJson = json;
}
if (selectedGame != null) File.WriteAllText(selectedGamePath, selectedGame.Executable);
}
void AddOrUpdateGame(GameEntry game, bool select)
{
var index = games.FindIndex(g => string.Equals(g.Executable, game.Executable, StringComparison.OrdinalIgnoreCase));
if (index >= 0) games[index] = game; else games.Add(game);
if (select) selectedGame = game;
SaveGameLibrary(); RenderGameTiles();
}
void SelectGame(GameEntry game)
{
if (!File.Exists(game.Executable)) { MessageBox.Show(this, "The selected game's executable no longer exists. Scan again or remove the old entry.", "Game not found", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
selectedGame = game;
gamePath.Text = game.Executable;
SaveGameLibrary(); RenderGameTiles();
status.Text = $"Selected {game.Name}. Click Launch game to start it.";
}
Bitmap? GetTileIcon(GameEntry game)
{
var key = !string.IsNullOrWhiteSpace(game.IconPath) && File.Exists(game.IconPath) ? game.IconPath : game.Executable;
if (tileIcons.TryGetValue(key, out var cached)) return cached;
Bitmap? bitmap = null;
try
{
if (key == game.IconPath)
{
using var supplied = new Icon(key, Ui.S(48), Ui.S(48));
bitmap = supplied.ToBitmap();
}
else
{
using var embedded = Icon.ExtractAssociatedIcon(key);
bitmap = embedded?.ToBitmap();
}
}
catch { }
tileIcons[key] = bitmap;
return bitmap;
}
void RenderGameTiles()
{
if (gameTiles.IsDisposed) return;
gameTiles.SuspendLayout();
var old = gameTiles.Controls.Cast<Control>().ToList();
gameTiles.Controls.Clear();
foreach (var control in old) control.Dispose(); // Controls.Clear() alone leaks the tiles
var present = games.Where(g => File.Exists(g.Executable)).OrderBy(g => g.Name, StringComparer.OrdinalIgnoreCase).ToList();
foreach (var game in present)
{
var isSelected = selectedGame != null && string.Equals(selectedGame.Executable, game.Executable, StringComparison.OrdinalIgnoreCase);
var tile = new GameTile(game, GetTileIcon(game), isSelected);
tile.GameChosen += SelectGame;
gameTiles.Controls.Add(tile);
}
if (present.Count == 0)
gameTiles.Controls.Add(new Label { Text = "No Xbox game dumps detected yet. Use Scan for Xbox games or Add game folder…", ForeColor = Color.Gainsboro, AutoSize = true, MaximumSize = new Size(Ui.S(700), 0), UseMnemonic = false, Margin = new Padding(Ui.S(12)) });
selectedGameLabel.Text = selectedGame == null ? "No game selected" : $"Selected: {selectedGame.Name}";
gameTiles.ResumeLayout();
}
async Task ScanForGamesAsync()
{
if (scanning) return;
scanning = true;
if (scanButton != null) scanButton.Enabled = false;
try
{
status.Text = "Scanning common Xbox game locations…";
var found = await Task.Run(DiscoverGames);
foreach (var game in found)
{
var index = games.FindIndex(g => string.Equals(g.Executable, game.Executable, StringComparison.OrdinalIgnoreCase));
if (index >= 0) games[index] = game; else games.Add(game);
}
if (selectedGame == null && games.Count > 0) selectedGame = games.FirstOrDefault(g => File.Exists(g.Executable));
if (selectedGame != null) gamePath.Text = selectedGame.Executable;
SaveGameLibrary(); RenderGameTiles();
status.Text = $"Game scan complete: found {found.Count} Xbox-compatible game folder(s).";
}
catch (Exception ex) { status.Text = "Game scan failed: " + ex.Message; }
finally
{
scanning = false;
if (scanButton is { IsDisposed: false }) scanButton.Enabled = true;
}
}
/// <summary>One filesystem walk per root that looks for both marker files at once.</summary>
static IEnumerable<string> EnumerateMarkers(string folder) =>
new FileSystemEnumerable<string>(folder, (ref FileSystemEntry entry) => entry.ToFullPath(), ScanOptions(8))
{
ShouldIncludePredicate = (ref FileSystemEntry entry) =>
!entry.IsDirectory &&
(MemoryExtensions.Equals(entry.FileName, ScarlettExe, StringComparison.OrdinalIgnoreCase) ||
MemoryExtensions.Equals(entry.FileName, GameConfig, StringComparison.OrdinalIgnoreCase))
};
GameEntry? GameFromConfig(string config)
{
var folder = Path.GetDirectoryName(config)!;
string title = new DirectoryInfo(folder).Name;
string? executable = null;
try
{
var doc = XDocument.Load(config);
title = doc.Descendants().FirstOrDefault(e => e.Name.LocalName.Equals("Title", StringComparison.OrdinalIgnoreCase))?.Value.Trim() ?? title;
var node = doc.Descendants().FirstOrDefault(e => e.Name.LocalName.Equals("Executable", StringComparison.OrdinalIgnoreCase));
executable = node?.Attributes().FirstOrDefault(a => new[] { "Name", "Path", "Target" }.Contains(a.Name.LocalName, StringComparer.OrdinalIgnoreCase))?.Value ?? node?.Value;
}
catch { }
var candidates = new List<string>();
if (!string.IsNullOrWhiteSpace(executable))
{
var clean = executable.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar);
candidates.Add(Path.Combine(folder, clean));
candidates.Add(Path.Combine(folder, "Content", clean));
}
candidates.Add(Path.Combine(folder, "game.exe"));
candidates.Add(Path.Combine(folder, "Content", "game.exe"));
var chosen = candidates.FirstOrDefault(f => File.Exists(f) && !Path.GetFileName(f).StartsWith("unins", StringComparison.OrdinalIgnoreCase) && !Path.GetFileName(f).Contains("crash", StringComparison.OrdinalIgnoreCase));
return chosen == null ? null : new GameEntry(title, chosen, folder);
}
List<GameEntry> DiscoverGames()
{
var candidates = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
void AddRoot(string? path) { if (!string.IsNullOrWhiteSpace(path) && Directory.Exists(path)) candidates.Add(Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar)); }
AddRoot(root);
var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
var programFilesX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
foreach (var name in CommonFolderNames)
{
AddRoot(Path.Combine(profile, name));
AddRoot(Path.Combine(documents, name));
AddRoot(Path.Combine(profile, "Downloads", name));
AddRoot(Path.Combine(programFiles, name));
AddRoot(Path.Combine(programFilesX86, name));
}
try
{
foreach (var drive in DriveInfo.GetDrives().Where(d => d.IsReady && d.DriveType == DriveType.Fixed))
foreach (var name in CommonFolderNames) AddRoot(Path.Combine(drive.RootDirectory.FullName, name));
}
catch { }
// A root that sits inside another root is already covered by the outer walk.
var all = candidates.OrderBy(r => r.Length).ToList();
var roots = all.Where(r => !all.Any(o => o.Length < r.Length && r.StartsWith(o + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))).ToList();
var result = new ConcurrentDictionary<string, GameEntry>(StringComparer.OrdinalIgnoreCase);
Parallel.ForEach(roots, new ParallelOptions { MaxDegreeOfParallelism = Math.Min(4, Math.Max(1, roots.Count)) }, searchRoot =>
{
try
{
foreach (var file in EnumerateMarkers(searchRoot))
{
if (string.Equals(Path.GetFileName(file), ScarlettExe, StringComparison.OrdinalIgnoreCase))
{
var dir = Path.GetDirectoryName(file)!;
var name = Directory.GetParent(dir)?.Name ?? new DirectoryInfo(dir).Name;
result[file] = new GameEntry(name, file, dir);
}
else if (GameFromConfig(file) is { } game) result[game.Executable] = game;
}
}
catch { }
});
return result.Values.OrderBy(g => g.Name, StringComparer.OrdinalIgnoreCase).ToList();
}
void AddGameFolder()
{
using var dialog = new FolderBrowserDialog { Description = "Select an Xbox game dump folder containing game_scarlett_master.exe or MicrosoftGame.config", UseDescriptionForTitle = true };
if (dialog.ShowDialog(this) != DialogResult.OK) return;
var found = DiscoverGamesInFolder(dialog.SelectedPath);
if (found.Count == 0) { MessageBox.Show(this, "No supported Xbox game executable or MicrosoftGame.config was found in that folder.", "No game found", MessageBoxButtons.OK, MessageBoxIcon.Information); return; }
foreach (var game in found) AddOrUpdateGame(game, false);
SelectGame(found[0]);
}
List<GameEntry> DiscoverGamesInFolder(string folder)
{
var found = new List<GameEntry>();
var configs = new List<string>();
try
{
foreach (var file in EnumerateMarkers(folder))
{
if (string.Equals(Path.GetFileName(file), ScarlettExe, StringComparison.OrdinalIgnoreCase))
found.Add(new GameEntry(new DirectoryInfo(Path.GetDirectoryName(file)!).Parent?.Name ?? new DirectoryInfo(folder).Name, file, Path.GetDirectoryName(file)!));
else configs.Add(file);
}
if (found.Count == 0)
{
foreach (var config in configs)
{
var dir = Path.GetDirectoryName(config)!;
var exeFile = Directory.EnumerateFiles(dir, "*.exe", ScanOptions(3)).FirstOrDefault();
if (exeFile != null) found.Add(new GameEntry(new DirectoryInfo(dir).Name, exeFile, dir));
}
}
}
catch { }
return found;
}
void BrowseGame()
{
using var dialog = new OpenFileDialog { Filter = "Xbox game executable|game_scarlett_master.exe;*.exe|Executable files|*.exe", Title = "Select your legally obtained Xbox game executable" };
if (dialog.ShowDialog(this) == DialogResult.OK)
{
var dir = Path.GetDirectoryName(dialog.FileName)!;
var game = new GameEntry(new DirectoryInfo(dir).Parent?.Name ?? new DirectoryInfo(dir).Name, dialog.FileName, dir);
AddOrUpdateGame(game, true);
gamePath.Text = dialog.FileName;
}
}
}
+279
View File
@@ -0,0 +1,279 @@
using System.Collections.Concurrent;
namespace EonaCat.XSBOX.Launcher;
internal static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new LauncherForm());
}
}
internal sealed record Setting(string Page, string Label, string Key, string Default, string[] Values, string Description);
internal sealed record GameEntry(string Name, string Executable, string Directory, string? IconPath = null);
internal sealed partial class LauncherForm : Form
{
static readonly Color Panel0 = Color.FromArgb(10, 10, 13);
static readonly Color Panel1 = Color.FromArgb(18, 18, 22);
static readonly Color Panel2 = Color.FromArgb(27, 23, 27);
readonly string root = FindRoot();
readonly string exe;
readonly string? logoPath = LauncherBrand.ResolveLogoPath();
readonly string settingsPath = GetSettingsPath();
readonly TextBox gamePath = new() { Width = 590 };
readonly FlowLayoutPanel gameTiles = new() { Dock = DockStyle.Fill, AutoScroll = true, WrapContents = true, BackColor = Panel1 };
readonly Label selectedGameLabel = new() { Dock = DockStyle.Fill, AutoSize = false, AutoEllipsis = true, UseMnemonic = false, TextAlign = ContentAlignment.MiddleLeft, ForeColor = Color.Gainsboro };
readonly List<GameEntry> games = new();
GameEntry? selectedGame;
readonly string home = GetHomePath();
readonly string gameListPath = Path.Combine(GetHomePath(), "launcher-games.json");
readonly string selectedGamePath = Path.Combine(GetHomePath(), "launcher-selected-game.txt");
readonly WrapLabel status = new() { AutoHeight = true, MaxLines = 3, ForeColor = Color.LightGreen };
readonly TabControl tabs = new() { Dock = DockStyle.Fill, Multiline = true, HotTrack = true };
readonly Dictionary<string, Control> editors = new(StringComparer.Ordinal);
readonly TextBox output = new() { Multiline = true, ReadOnly = true, ScrollBars = ScrollBars.Vertical, Dock = DockStyle.Fill, BackColor = Color.FromArgb(12, 12, 15), ForeColor = Color.Gainsboro, Font = Ui.Font(9, FontStyle.Regular, "Consolas"), MaxLength = int.MaxValue };
readonly System.Windows.Forms.Timer outputPump = new() { Interval = 100 };
PreloadProgressDialog? preloadDialog;
Bitmap? logoBitmap;
bool logoLoaded;
Button? scanButton;
public LauncherForm()
{
exe = Path.Combine(root, "eonacat-xsbox.exe");
Text = "EonaCat XS";
AutoScaleMode = AutoScaleMode.None; // every size below is scaled explicitly with Ui.S
StartPosition = FormStartPosition.CenterScreen;
var area = Screen.FromPoint(Cursor.Position).WorkingArea;
MinimumSize = new Size(Math.Min(Ui.S(940), area.Width), Math.Min(Ui.S(680), area.Height));
Size = new Size(Math.Min(Ui.S(1120), area.Width - Ui.S(40)), Math.Min(Ui.S(820), area.Height - Ui.S(40)));
BackColor = Panel1; ForeColor = Color.White;
Font = Ui.Font(9.5f);
Icon = LauncherBrand.CreateIcon();
gameTiles.Padding = new Padding(Ui.S(14));
selectedGameLabel.Font = Ui.Font(10);
tabs.Padding = new Point(Ui.S(14), Ui.S(6));
var header = BuildHeader();
var footerActions = BuildFooterActions();
status.Dock = DockStyle.Bottom;
status.BackColor = Panel0;
status.Padding = new Padding(Ui.S(14), Ui.S(2), Ui.S(14), Ui.S(8));
var gamePanel = BuildGamePanel();
BuildOverviewPage();
BuildGamesPage();
var pageOrder = new[] { "Graphics", "Display & Stats", "Frame Generation", "Textures & Streaming", "Memory", "Controls", "Advanced" };
foreach (var page in pageOrder.Where(page => Settings.Any(setting => setting.Page == page))) BuildPage(page);
BuildToolsPage();
var logTab = new TabPage("Installer log") { Name = "Installer log", BackColor = BackColor, ForeColor = ForeColor };
logTab.Controls.Add(output);
logTab.Controls.Add(CreatePageHeader("Installer log", "Engine output, runtime setup and diagnostic messages"));
tabs.TabPages.Add(logTab);
// Dock order: the control added first (the tabs) fills whatever the later, edge-docked controls leave.
Controls.Add(tabs); Controls.Add(gamePanel); Controls.Add(header); Controls.Add(footerActions); Controls.Add(status);
tabs.SelectedIndex = 0;
LoadSettings();
LoadGameLibrary();
outputPump.Tick += (_, _) => PumpEngineOutput();
outputPump.Start();
Shown += async (_, _) => await ScanForGamesAsync();
status.Text = "Settings, shaders, caches and game data are stored under %LOCALAPPDATA%\\EonaCat\\XS";
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
outputPump.Dispose();
preloadDialog?.Dispose();
logoBitmap?.Dispose();
foreach (var bitmap in tileIcons.Values) bitmap?.Dispose();
tileIcons.Clear();
}
base.Dispose(disposing);
}
Bitmap? CreateLogoBitmap()
{
if (logoLoaded) return logoBitmap;
logoLoaded = true;
if (logoPath == null) return null;
try
{
using var icon = new Icon(logoPath, Ui.S(64), Ui.S(64)); // picks the sharpest frame for this DPI
logoBitmap = icon.ToBitmap();
}
catch { logoBitmap = null; }
return logoBitmap;
}
Panel BuildHeader()
{
var header = new Panel { Dock = DockStyle.Top, Height = Ui.S(92), Padding = new Padding(Ui.S(18), Ui.S(10), Ui.S(18), Ui.S(10)), BackColor = Panel0 };
var titleFont = Ui.Font(22, FontStyle.Bold);
var subFont = Ui.Font(9, FontStyle.Bold);
var title = new Label { Text = "EonaCat XS", Font = titleFont, ForeColor = Color.White, Dock = DockStyle.Top, Height = titleFont.Height + Ui.S(4), AutoSize = false, AutoEllipsis = true, UseMnemonic = false };
var sub = new Label { Text = "XBOX COMPATIBILITY • DIRECT3D 12 • PERFORMANCE", Font = subFont, ForeColor = Color.FromArgb(245, 55, 65), Dock = DockStyle.Top, Height = subFont.Height + Ui.S(4), AutoSize = false, AutoEllipsis = true, UseMnemonic = false };
var textHost = new Panel { Dock = DockStyle.Fill, BackColor = Color.Transparent, Padding = new Padding(Ui.S(14), Ui.S(6), 0, 0) };
textHost.Controls.Add(sub); textHost.Controls.Add(title);
var mark = new PictureBox { Dock = DockStyle.Left, Width = Ui.S(64), SizeMode = PictureBoxSizeMode.Zoom, Image = CreateLogoBitmap(), BackColor = Color.Transparent };
header.Controls.Add(textHost); header.Controls.Add(mark);
return header;
}
FlowLayoutPanel BuildFooterActions()
{
var profile = MakeButton("RTX 4090 - UW", 120); profile.Click += (_, _) => ApplyRtx4090Profile();
var save = MakeButton("Save settings", 100); save.Click += (_, _) => SaveSettings();
var launch = MakeButton("Launch game", 100); launch.Click += (_, _) => LaunchGame();
var nvidia = MakeButton("NVIDIA runtime", 120); nvidia.Click += async (_, _) => await RunEngineCommand("get-dlss");
var amd = MakeButton("AMD FSR runtime", 120); amd.Click += async (_, _) => await RunEngineCommand("get-fsr");
var d3d = MakeButton("D3D12 runtime", 115); d3d.Click += async (_, _) => await RunEngineCommand("get-d3d12");
var browse = MakeButton("Browse game…", 100); browse.Click += (_, _) => BrowseGame();
var autoGpu = MakeButton("Auto GPU runtime", 135); autoGpu.Click += async (_, _) => await InstallDetectedGpuRuntime();
// Docked to the bottom and AutoSize: the bar grows by whole rows when the buttons need to wrap.
var footerActions = new FlowLayoutPanel
{
Dock = DockStyle.Bottom,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
FlowDirection = FlowDirection.LeftToRight,
WrapContents = true,
BackColor = Panel0,
Padding = new Padding(Ui.S(10), Ui.S(8), Ui.S(10), Ui.S(2))
};
foreach (var button in new[] { profile, save, launch, browse, autoGpu, nvidia, amd, d3d })
{
button.Margin = new Padding(Ui.S(3));
footerActions.Controls.Add(button);
}
return footerActions;
}
Panel BuildGamePanel()
{
var gamePanel = new Panel { Dock = DockStyle.Top, Height = Ui.S(60), Padding = new Padding(Ui.S(14), Ui.S(8), Ui.S(14), Ui.S(8)), BackColor = Panel2 };
var gameActions = new FlowLayoutPanel
{
Dock = DockStyle.Right,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
FlowDirection = FlowDirection.LeftToRight,
WrapContents = false,
BackColor = Color.Transparent
};
scanButton = MakeButton("Scan for Xbox games", 155); scanButton.Click += async (_, _) => await ScanForGamesAsync();
var addFolder = MakeButton("Add game folder…", 135); addFolder.Click += (_, _) => AddGameFolder();
scanButton.Margin = addFolder.Margin = new Padding(Ui.S(3));
gameActions.Controls.Add(scanButton);
gameActions.Controls.Add(addFolder);
gamePanel.Controls.Add(selectedGameLabel);
gamePanel.Controls.Add(gameActions);
return gamePanel;
}
Panel CreatePageHeader(string titleText, string subtitleText)
{
var titleFont = Ui.Font(15, FontStyle.Bold);
var subFont = Ui.Font(8.5f);
var header = new Panel
{
Dock = DockStyle.Top,
Height = Ui.S(78),
Padding = new Padding(Ui.S(18), Ui.S(10), Ui.S(18), Ui.S(8)),
BackColor = Color.FromArgb(22, 20, 25)
};
var title = new Label { Text = titleText, Font = titleFont, ForeColor = Color.White, Dock = DockStyle.Top, Height = titleFont.Height + Ui.S(4), AutoSize = false, AutoEllipsis = true, UseMnemonic = false };
var subtitle = new Label { Text = subtitleText, Font = subFont, ForeColor = Color.FromArgb(190, 184, 194), Dock = DockStyle.Top, Height = subFont.Height + Ui.S(4), AutoSize = false, AutoEllipsis = true, UseMnemonic = false };
var textHost = new Panel { Dock = DockStyle.Fill, BackColor = Color.Transparent, Padding = new Padding(Ui.S(12), Ui.S(4), 0, 0) };
textHost.Controls.Add(subtitle); textHost.Controls.Add(title);
var mark = new PictureBox { Dock = DockStyle.Left, Width = Ui.S(54), SizeMode = PictureBoxSizeMode.Zoom, Image = CreateLogoBitmap(), BackColor = Color.Transparent };
header.Controls.Add(textHost); header.Controls.Add(mark);
return header;
}
static StackPanel Card(Color back) => new()
{
AutoScroll = false,
BackColor = back,
Padding = new Padding(Ui.S(18)),
Margin = new Padding(0, 0, 0, Ui.S(14))
};
void BuildOverviewPage()
{
var page = new TabPage("EonaCat") { Name = "EonaCat", BackColor = BackColor, ForeColor = ForeColor };
var content = new StackPanel { Dock = DockStyle.Fill, BackColor = BackColor, Padding = new Padding(Ui.S(22)), MaxContentWidth = Ui.S(940) };
var welcome = Card(Color.FromArgb(30, 25, 31));
welcome.Controls.Add(new WrapLabel { Text = "Your Xbox compatibility launcher", Font = Ui.Font(17, FontStyle.Bold), ForeColor = Color.White, Margin = new Padding(0, 0, 0, Ui.S(8)) });
welcome.Controls.Add(new WrapLabel { Text = "Choose a game, tune graphics and memory, then launch with the EonaCat XS engine.", ForeColor = Color.Gainsboro, Margin = new Padding(0, 0, 0, Ui.S(8)) });
welcome.Controls.Add(new WrapLabel { Text = "GPU-FIRST • DIRECT3D 12 • CONFIGURABLE PERFORMANCE", Font = Ui.Font(8, FontStyle.Bold), ForeColor = Color.FromArgb(245, 55, 65) });
var actions = new FlowRow { Margin = new Padding(0, 0, 0, Ui.S(8)) };
var launch = MakeButton("Launch selected game", 190); launch.Click += (_, _) => LaunchGame();
var gamesButton = MakeButton("Installed games", 150); gamesButton.Click += (_, _) => tabs.SelectedTab = tabs.TabPages["Installed games"];
var graphicsButton = MakeButton("Graphics settings", 150); graphicsButton.Click += (_, _) => tabs.SelectedTab = tabs.TabPages["Graphics"];
var memoryButton = MakeButton("Memory settings", 150); memoryButton.Click += (_, _) => tabs.SelectedTab = tabs.TabPages["Memory"];
foreach (var button in new[] { launch, gamesButton, graphicsButton, memoryButton })
{
button.MinimumSize = new Size(button.MinimumSize.Width, Ui.S(40));
button.Margin = new Padding(0, 0, Ui.S(8), Ui.S(8));
actions.Controls.Add(button);
}
var profile = Card(Color.FromArgb(27, 23, 27));
profile.Controls.Add(new WrapLabel { Text = "Quick profile", Font = Ui.Font(11, FontStyle.Bold), ForeColor = Color.White, Margin = new Padding(0, 0, 0, Ui.S(6)) });
profile.Controls.Add(new WrapLabel { Text = "Apply the RTX 4090 ultrawide profile as a starting point. The runtime's CPU-submission optimisations are now active for every preset; review GPU/display settings before launching.", Font = Ui.Font(8.75f), ForeColor = Color.Gainsboro, Margin = new Padding(0, 0, 0, Ui.S(10)) });
var preset = MakeButton("Apply RTX 4090 profile", 190); preset.Click += (_, _) => ApplyRtx4090Profile();
profile.Controls.Add(preset);
content.Controls.Add(welcome); content.Controls.Add(actions); content.Controls.Add(profile);
page.Controls.Add(content);
page.Controls.Add(CreatePageHeader("EonaCat XS", "Launcher overview and quick actions"));
tabs.TabPages.Add(page);
}
static string GetHomePath()
{
var configured = Environment.GetEnvironmentVariable("EONACAT_XS_HOME");
return string.IsNullOrWhiteSpace(configured)
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "EonaCat", "XS")
: configured;
}
static string GetSettingsPath() => Path.Combine(GetHomePath(), "eonacat-xs-settings.txt");
static string FindRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
for (int i = 0; i < 6 && dir != null; i++, dir = dir.Parent!)
if (File.Exists(Path.Combine(dir.FullName, "eonacat-xsbox.exe")) || File.Exists(Path.Combine(dir.FullName, "Cargo.toml"))) return dir.FullName;
return AppContext.BaseDirectory;
}
/// <summary>Buttons size themselves to their text; <paramref name="minWidth"/> only keeps related buttons visually even.</summary>
static Button MakeButton(string text, int minWidth) => new()
{
Text = text,
UseMnemonic = false,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
MinimumSize = new Size(Ui.S(minWidth), Ui.S(34)),
Padding = new Padding(Ui.S(10), Ui.S(2), Ui.S(10), Ui.S(2)),
Font = Ui.Font(9.5f),
FlatStyle = FlatStyle.Flat,
BackColor = Color.FromArgb(48, 31, 35),
ForeColor = Color.White,
UseVisualStyleBackColor = false,
FlatAppearance = { BorderColor = Color.FromArgb(112, 45, 52) }
};
}
+32
View File
@@ -0,0 +1,32 @@
using System.Drawing;
namespace EonaCat.XSBOX.Launcher;
internal static class LauncherBrand
{
public static string? ResolveLogoPath()
{
var candidates = new List<string>
{
Path.Combine(AppContext.BaseDirectory, "assets", "eonacat-logo.ico"),
Path.Combine(AppContext.BaseDirectory, "eonacat-logo.ico")
};
var directory = new DirectoryInfo(AppContext.BaseDirectory);
for (var depth = 0; depth < 8 && directory != null; depth++, directory = directory.Parent)
{
candidates.Add(Path.Combine(directory.FullName, "assets", "eonacat-logo.ico"));
candidates.Add(Path.Combine(directory.FullName, "eonacat-logo.ico"));
}
return candidates.FirstOrDefault(File.Exists);
}
public static Icon? CreateIcon()
{
var path = ResolveLogoPath();
if (path == null) return null;
try { return new Icon(path); }
catch { return null; }
}
}
+244
View File
@@ -0,0 +1,244 @@
using System.Text;
namespace EonaCat.XSBOX.Launcher;
internal sealed partial class LauncherForm
{
static readonly Setting[] Settings =
[
new("Graphics", "Console profile", "EONACAT_XS_MENU_CONSOLE", "series-x", ["series-x", "series-s"], "Series X gives higher detail and larger textures. Series S is lighter on GPU, RAM and VRAM; useful on lower-memory cards."),
new("Graphics", "Output resolution", "EONACAT_XS_MENU_RES", "4k", ["1440", "1080to1440", "4k"], "Output target: 2560×1440, 1920×1080 rendered then upscaled to 1440p, or native 3840×2160. 4K costs substantially more GPU time."),
new("Advanced", "Experimental native ultrawide output", "EONACAT_XS_NATIVE_WIDE", "", ["", "1"], "EXPERIMENTAL ONLY. The current native-wide path is known to show a seam/ghosting beyond 2560 pixels because the title's upscaler/window remain 2560 wide. Leave OFF for stable play; a complete game-image patch is still needed for clean 3440×1440."),
new("Graphics", "Series S internal resolution", "EONACAT_XS_MENU_S_RES", "720", ["720", "626", "540", "360"], "Internal scene height for the Series S profile. Lower values improve performance but reduce detail. This is used only when Series S is selected."),
new("Graphics", "DLSS upscaling", "EONACAT_XS_MENU_DLSS", "balanced", ["off", "quality", "balanced", "performance", "ultraperformance", "dlaa"], "Quality preserves detail; Balanced and Performance trade some detail for more speed. Requires NVIDIA Streamline/DLSS runtime files."),
new("Graphics", "Ray tracing", "EONACAT_XS_MENU_RT", "off", ["off", "software", "hardware"], "OFF is fastest. Software uses shader-based ray tracing. Hardware uses RT cores but is experimental and can consume substantial VRAM."),
new("Graphics", "DLSS model override", "EONACAT_XS_DLSS_PRESET", "", ["", "auto", "k", "j", "m", "l"], "Selects the DLSS model. Blank uses the game's default; AUTO follows NVIDIA's recommendation for the selected mode. This requires the NVIDIA DLSS runtime."),
new("Graphics", "GPU adapter", "EONACAT_XS_ADAPTER", "", [""], "AUTO lets DXGI choose the adapter. To select a specific GPU, use the in-game F9 menu, which enumerates the actual adapters in this PC."),
new("Graphics", "Frame rate cap", "EONACAT_XS_MENU_FPS", "120", ["1000", "120", "60", "30"], "The default is 120 FPS to match the reported 120 Hz refresh. Set NONE for an uncapped frame rate, or choose 60 or 30 for a lower cap."),
new("Display & Stats", "Console refresh rate", "EONACAT_XS_DISPLAY_REFRESH", "120", ["60", "120", "165"], "Refresh rate exposed to the emulated game. The default is 120 Hz. This does not change the Windows monitor refresh rate."),
new("Display & Stats", "FPS line at top", "EONACAT_XS_FPS_LINE", "0", ["1", "0"], "Shows the live FPS/frame-time line at the top of the game. Negligible performance cost."),
new("Display & Stats", "FPS bottleneck advisor (F10)", "EONACAT_XS_ADVISOR", "0", ["0", "1"], "Shows whether CPU, GPU or shader compilation is limiting performance, with a suggestion. F10 toggles it in-game."),
new("Display & Stats", "In-game console / stats panel (F11)", "EONACAT_XS_PANEL", "0", ["0", "1"], "Hidden by default. Press F11 while the game is focused to show or hide the diagnostic overlay."),
new("Display & Stats", "Stats panel transparency", "EONACAT_XS_PANEL_SEE", "", ["", "25", "50", "75"], "How much of the game shows through the panel background. The text remains solid."),
new("Display & Stats", "Panel: FPS and frame time", "EONACAT_XS_PANEL_FPS", "", ["", "0"], "Shows or hides FPS, frame time and longest recent frame in the stats panel."),
new("Display & Stats", "Panel: console and build", "EONACAT_XS_PANEL_GAME", "", ["", "0"], "Shows or hides the emulated console and runtime build information."),
new("Display & Stats", "Panel: resolution / DLSS / rays", "EONACAT_XS_PANEL_PICTURE", "", ["", "0"], "Shows or hides render/output resolution, DLSS, frame generation and ray tracing information."),
new("Display & Stats", "Panel: GPU time and draws", "EONACAT_XS_PANEL_GPU", "", ["", "0"], "Shows or hides GPU time, GPU wait time, draw counts and skipped draws."),
new("Display & Stats", "Panel: game RAM and VRAM", "EONACAT_XS_PANEL_MEMORY", "", ["", "0"], "Shows or hides process RAM, dedicated VRAM and shared GPU memory."),
new("Display & Stats", "Panel: CPU and free RAM", "EONACAT_XS_PANEL_CPU", "", ["", "0"], "Shows or hides CPU utilisation, free system RAM and commit headroom."),
new("Display & Stats", "Panel: PC specifications", "EONACAT_XS_PANEL_SPECS", "", ["", "0"], "Shows or hides CPU, memory and GPU specifications for diagnostics."),
new("Display & Stats", "Panel: graphs", "EONACAT_XS_PANEL_GRAPHS", "", ["", "0"], "Shows or hides recent FPS, CPU, RAM and VRAM graphs."),
new("Display & Stats", "Panel: panel overhead", "EONACAT_XS_PANEL_COST", "", ["", "1"], "Displays the microseconds spent drawing the stats panel itself. Intended for diagnostics."),
new("Display & Stats", "Borderless fullscreen", "EONACAT_XS_FULLSCREEN", "stretch", ["", "1", "stretch"], "ON starts borderless fullscreen at the active display resolution. Turn OFF for a window; Stretch fills the display without preserving aspect ratio."),
new("Graphics", "Lighting estimate", "EONACAT_XS_AMBIENT", "0.8", ["0.8", "1", "0.5", "0"], "Approximate lighting for areas that would normally use ray-traced lighting. Higher values brighten interiors and shaded areas; 0 disables it."),
new("Graphics", "Fog brightness cap", "EONACAT_XS_AMBIENT_AIR", "1", ["1", "1.5", "2", ""], "Limits the brightest fog and haze. Lower values prevent glowing fog; blank removes the cap and leaves the game's fog brightness unchanged."),
new("Graphics", "Reflection estimate", "EONACAT_XS_AMBIENT_SPECULAR", "0", ["0", "1"], "Uses an approximation for reflections instead of showing only the sky. Enable only if the result looks correct in your scenes."),
new("Graphics", "Water lighting", "EONACAT_XS_WATER_LIGHT", "0", ["0", "1"], "Lights water according to depth. It can cause dark underwater blocks on some GPUs, so it is off by default."),
new("Graphics", "Neutral probe light", "EONACAT_XS_PROBE_NEUTRAL", "0.3", ["0.3", "0"], "Uses neutral grey light where the lighting estimate has no probe result. No effect with ray tracing on or the lighting estimate disabled."),
new("Graphics", "Decal defrag / heat haze", "EONACAT_XS_LEAVE_OUT", "", ["", "731a39171b568298", "02384a60fda6f2d0,731a39171b568298"], "Normally runs both passes. The first non-empty value leaves out heat haze; the second leaves out both decal defragmentation and heat haze. Use only if you see smearing or rendering artifacts."),
new("Graphics", "Early depth test", "EONACAT_XS_EARLY_DEPTH", "1", ["1", ""], "Enables an early depth optimisation. It can reduce pixel work; disable only if investigating missing or incorrectly occluded geometry."),
new("Graphics", "Gray shadow lift", "EONACAT_XS_SHADOW_LIFT", "0", ["0", "0.03", "0.06", "0.09", "0.12", "0.15", "0.18", "0.21", "0.24", "0.27", "0.3"], "Brightens the darkest pixels before the HUD. This is a visual adjustment and has negligible performance cost."),
new("Frame Generation", "Frame generation multiplier", "EONACAT_XS_MENU_FRAMEGEN", "0", ["0", "2", "3", "4", "5", "6"], "Generates additional displayed frames between rendered frames. Raises displayed FPS, not the game's simulation/render rate, and adds latency and VRAM use. 2x DLSS FG requires RTX 40+; higher multipliers generally require RTX 50."),
new("Frame Generation", "Frame generation provider", "EONACAT_XS_MENU_FG_TYPE", "auto", ["auto", "dlss", "fsr", "fsr4"], "AUTO selects DLSS FG on supported NVIDIA cards and FSR 3 where appropriate. FSR uses AMD FidelityFX runtime files. FSR4 is experimental."),
new("Frame Generation", "Pause frame generation in movies", "EONACAT_XS_MOVIE_GATE", "", ["", "1"], "Pauses generated frames while the title plays a movie. The game may present video very frequently, so enabling this can leave frame generation paused for long periods."),
new("Memory", "Memory range memoization", "EONACAT_XS_RANGE_MEMO", "1", ["1", "0"], "Caches recently refreshed memory ranges so unchanged ranges can skip repeated write-watch checks. Uses a small amount of extra metadata memory."),
new("Advanced", "Fast-core submission placement", "EONACAT_XS_FAST_CORES", "1", ["1", "0"], "Keeps the GPU submission thread on the faster CPU cores when Windows exposes hybrid-core information."),
new("Memory", "Card pools", "EONACAT_XS_CARD_POOLS", "185:38:47", ["185:38:47", "0"], "Reserves title memory regions as GPU-visible upload heaps. Requires supported Windows 11 24H2+, ReBAR and compatible GPU/driver. Set 0 to disable the card-pool model."),
new("Memory", "Heap write hooks", "EONACAT_XS_HEAP_HOOKS", "1", ["1", "0"], "Tracks CPU writes to selected heaps so GPU mirrors can be refreshed accurately. Disable only for diagnosing memory corruption or hook conflicts."),
new("Memory", "Card-side constant-buffer fills", "EONACAT_XS_CARD_FILLS", "1", ["1", "0"], "Copies constant-buffer data on the GPU rather than reading it back through the CPU. Intended to reduce CPU stalls."),
new("Memory", "Arena upload notifications", "EONACAT_XS_ARENA_UPLOAD", "1", ["1", "0"], "Uses tracked writer notifications to upload changed arena regions instead of refreshing broad ranges."),
new("Memory", "Land in place mode", "EONACAT_XS_LAND_IN_PLACE", "2", ["0", "1", "2"], "Controls eligible GPU writes directly into mapped title memory. Higher modes are more aggressive and depend on supported memory placement/coherence."),
new("Memory", "Pool mirror size (MiB)", "EONACAT_XS_POOL_MIRROR", "2199", ["0", "1277", "2199"], "Size of the GPU-side mirror for the title's write-combined pool. 2199 MiB is the Series X pool; 1277 MiB is Series S. 0 disables the mirror."),
new("Memory", "Video memory budget (MiB)", "EONACAT_XS_VRAM_BUDGET_MB", "", ["", "4096", "6144", "8192", "10240", "12288"], "Maximum VRAM budget the game should target. Blank is AUTO (Windows' budget). Lower values leave room for other applications but can delay texture loading."),
new("Memory", "Maximum game card-memory arena (MiB)", "EONACAT_XS_MEMORY_CARD_MB", "", ["", "1536", "2048", "3072", "4096", "6144"], "Caps the amount of the title's memory arena backed by card memory. Blank uses the engine's default (up to 4 GiB). Lower values can help cards with less VRAM but may move more data to system memory."),
new("Memory", "Keep at least this much game RAM (GiB)", "EONACAT_XS_KEEP_RAM_GB", "", ["", "8", "12", "16", "24", "32"], "Keeps a hard minimum amount of the game's memory resident in system RAM. Blank disables the minimum. Use only if paging or memory pressure is causing instability."),
new("Memory", "Soft views", "EONACAT_XS_SOFT_VIEWS", "copies", ["copies", ""], "Uses copied mappings for title memory that is mapped at multiple addresses. This avoids known cutscene freezes at the cost of some extra RAM."),
new("Memory", "Card reads title memory in place", "EONACAT_XS_INPLACE_VIEW", "", ["", "1", "2"], "Lets the GPU read eligible title memory directly instead of reading a separate copy. Can reduce host memory traffic but depends on adapter support and may be slower on some systems."),
new("Memory", "Skip large GPU-to-CPU copy-backs", "EONACAT_XS_WC_NO_BACK", "1", ["1", ""], "Keeps eligible shader-written large buffers on the GPU rather than copying them back every frame. Faster, but disable if game-visible data appears stale or missing."),
new("Memory", "Mirror texture resources", "EONACAT_XS_POOL_MIRROR_TEXTURES", "1", ["1", "0"], "Allows texture detiling and reads to use the mirrored pool. Disable only when investigating incorrect texture contents."),
new("Memory", "Pool copy-back", "EONACAT_XS_POOL_BACK", "0", ["0", "1"], "Copies GPU-written mirrored data back to CPU memory. Off is faster, but relies on the coherent-set tracking to preserve CPU-visible data."),
new("Memory", "Coherent pool tracking", "EONACAT_XS_POOL_COHERENT", "1", ["1", "0"], "Tracks 64 KiB regions where CPU and GPU writes overlap, preserving coherent data. Disabling may cause stale or frozen game data."),
new("Memory", "Coherent differential sweep", "EONACAT_XS_POOL_COHERENT_DIFF", "1", ["1", "0"], "Uses differential comparisons during coherent-pool sweeps to avoid unnecessary copies."),
new("Memory", "Narrow coherent tracking", "EONACAT_XS_POOL_COHERENT_NARROW", "1", ["1", "0"], "Only joins regions after the CPU has written them, reducing the tracked coherent set."),
new("Memory", "Coherent-set maximum (MiB)", "EONACAT_XS_POOL_COHERENT_MAX_MB", "256", ["128", "256", "512", "1024"], "Upper bound for CPU/GPU-overlapping 64 KiB regions tracked as coherent. A higher cap preserves more overlapping data but consumes more host memory."),
new("Memory", "Pull earlier CPU data when joining", "EONACAT_XS_POOL_COHERENT_PULL", "", ["", "1"], "When a region joins the coherent set, merges its earlier CPU-written data. This is a correctness-sensitive option; leave off unless testing a known stale-data issue."),
new("Memory", "Wait for in-flight writes on join", "EONACAT_XS_POOL_COHERENT_JOIN_WAIT", "", ["", "1"], "Waits for GPU work already in flight before adding a region to the coherent set. Improves ordering safety but can add stalls."),
new("Memory", "Quiet coherent blocks after (seconds)", "EONACAT_XS_POOL_COHERENT_QUIET_S", "0", ["0", "1", "2", "5", "10"], "A block not written by the CPU for this many seconds can be treated as quiet. 0 disables quieting. This is an advanced memory-traffic trade-off."),
new("Memory", "Check arena upload notifications", "EONACAT_XS_ARENA_UPLOAD_CHECK", "", ["", "1"], "Diagnostic verification that writer notifications cover changed arena data. Can add overhead; enable only when investigating missed uploads."),
new("Memory", "Disable guard regions", "EONACAT_XS_NO_GUARDS", "1", ["1", "0"], "Removes selected memory guard overhead for the memory model. Keep the default unless diagnosing address-space or memory corruption issues."),
new("Memory", "Submit overlap", "EONACAT_XS_COMING_AT_SUBMIT", "1", ["1", "0"], "Allows eligible memory work to be prepared around submission. Turning it off can reduce overlap and throughput."),
new("Memory", "Frames in flight", "EONACAT_XS_SUBMIT_FRAMES", "2", ["1", "2"], "Number of frames allowed ahead in submission. More overlap can improve GPU utilisation but can increase latency and memory pressure."),
new("Memory", "Submission queue depth", "EONACAT_XS_SUBMIT_DEPTH", "128", ["64", "128"], "Maximum queued submission depth. Lower values constrain queued work; higher values can help throughput but increase queueing."),
new("Memory", "Memory window size (KiB)", "EONACAT_XS_WINDOW_KB", "256", ["64", "128", "256", "512"], "Granularity used by the title-memory window allocator. Changing it can affect address placement and memory overhead."),
new("Memory", "Optimise window tails", "EONACAT_XS_WINDOW_TAILS", "1", ["1", "0"], "Uses smaller tail handling for memory windows to reduce wasted mapped space."),
new("Memory", "Bound streaming reads", "EONACAT_XS_STREAM_BOUND", "1", ["1", "0"], "Bounds streaming reads to avoid oversized reads and memory spikes."),
new("Textures & Streaming", "Texture no-wait", "EONACAT_XS_TEXTURE_NO_WAIT", "1", ["1", "0"], "Displays available texture data instead of blocking for a texture that is still loading. May briefly show lower-detail texture data."),
new("Textures & Streaming", "Texture catch-up", "EONACAT_XS_TEXTURE_CATCHUP", "1", ["1", "0"], "Allows late texture data to catch up after the initial non-blocking upload."),
new("Textures & Streaming", "Texture stage budget (ms)", "EONACAT_XS_TEXTURE_STAGE_MS", "24", ["8", "16", "24", "32"], "Time budget for texture staging work per scheduling window. Larger values may reduce backlog but consume more CPU time."),
new("Textures & Streaming", "Painted texture refresh interval", "EONACAT_XS_PAINTED_EVERY", "0", ["0", "1", "4"], "Checks textures redrawn without explicit notifications. 1 checks every frame and costs the most CPU; 4 checks every four frames; 0 leaves this extra polling off."),
new("Textures & Streaming", "Texture pool", "EONACAT_XS_TEXTURE_POOL", "1", ["1", "0"], "Enables pooled texture allocations to reduce repeated allocation overhead."),
new("Controls", "Controller mode", "EONACAT_XS_CONTROLS", "", ["", "keyboard", "gamepad", "dualsense"], "AUTO follows detected input. KEYBOARD forces keyboard/mouse; GAMEPAD uses controllers; DUALSENSE reads a PlayStation controller natively."),
new("Controls", "Mouse capture", "EONACAT_XS_MOUSE_CAPTURE", "1", ["", "1"], "ON by default: captures and hides the pointer while the game is focused, regardless of controller mode; releases it when focus is lost. Set OFF for a free pointer."),
new("Controls", "Mouse and keyboard", "EONACAT_XS_MNK", "", ["", "1"], "Enables the native mouse/keyboard input path. It replaces the title's controller input path; configure key bindings in the in-game menu."),
new("Controls", "Vehicle camera auto-center", "EONACAT_XS_VEHICLE_AUTO_CENTER", "", ["", "1"], "Automatically returns the camera behind the vehicle while driving. This setting can be changed live."),
new("Controls", "English keyboard layout", "EONACAT_XS_IME_ENGLISH", "", ["", "1"], "Uses an English keyboard layout in the game window to avoid other input-method layouts changing key interpretation."),
new("Advanced", "Heap sync at submit", "EONACAT_XS_HEAP_SYNC_AT_SUBMIT", "1", ["1", "0"], "Performs descriptor/heap synchronisation at submission. Disabling may expose stale descriptors or GPU races; leave enabled unless diagnosing."),
new("Advanced", "Shader exact wave64 handling", "EONACAT_XS_EXACT64", "1", ["1", "0"], "Enables exact wave64 shader handling where supported by the translator. Disabling can change shader correctness."),
];
static string PageSubtitle(string page) => page switch
{
"Graphics" => "Display quality, upscaling and rendering options",
"Display & Stats" => "Refresh rate, FPS counters and the in-game diagnostic panel",
"Frame Generation" => "Generated frames, provider selection and latency trade-offs",
"Textures & Streaming" => "Texture upload scheduling and streaming behavior",
"Memory" => "System RAM, VRAM and GPU-visible memory behavior",
"Controls" => "Input device and mouse behavior",
_ => "Advanced engine and diagnostic options"
};
void BuildPage(string page)
{
// "&" is the mnemonic marker in tab captions, so it must be doubled to be shown ("Display & Stats").
var tab = new TabPage(page.Replace("&", "&&")) { Name = page, BackColor = BackColor, ForeColor = ForeColor };
var stack = new StackPanel { Dock = DockStyle.Fill, BackColor = BackColor, Padding = new Padding(Ui.S(14), Ui.S(12), Ui.S(14), Ui.S(12)) };
stack.SuspendLayout();
foreach (var setting in Settings.Where(item => item.Page == page))
{
var card = new SettingCard(setting);
editors[setting.Key] = card.Editor;
stack.Controls.Add(card);
}
stack.ResumeLayout(false);
tab.Controls.Add(stack);
tab.Controls.Add(CreatePageHeader(page, PageSubtitle(page)));
tabs.TabPages.Add(tab);
}
void BuildToolsPage()
{
var tab = new TabPage("Tools") { Name = "Tools", BackColor = BackColor, ForeColor = ForeColor };
var stack = new StackPanel { Dock = DockStyle.Fill, BackColor = BackColor, Padding = new Padding(Ui.S(22)), MaxContentWidth = Ui.S(900) };
var preload = MakeButton("Preload shaders", 180); preload.Click += async (_, _) => { SaveSettings(); await RunEngineCommand("preload", Directory.Exists(Path.GetDirectoryName(gamePath.Text)) ? Path.GetDirectoryName(gamePath.Text) : null); };
var clear = MakeButton("Clear shader cache", 180); clear.Click += async (_, _) =>
{
if (MessageBox.Show(this, "This deletes translated shaders and cached pipelines. They must be rebuilt and the next game start may stutter. Continue?", "Clear shader cache", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
await RunEngineCommand("clear-shaders");
};
stack.Controls.Add(new WrapLabel { Text = "Shader maintenance", Font = Ui.Font(14, FontStyle.Bold), ForeColor = Color.White, Margin = new Padding(0, 0, 0, Ui.S(12)) });
stack.Controls.Add(new WrapLabel { Text = "Preload translates shaders and builds known host pipelines before gameplay. It can take several minutes, but reduces first-run shader stutter.", ForeColor = Color.Gainsboro, Margin = new Padding(0, 0, 0, Ui.S(12)) });
preload.Margin = new Padding(0, 0, 0, Ui.S(24));
stack.Controls.Add(preload);
stack.Controls.Add(new WrapLabel { Text = "Clear the shader cache only after a translator/driver change or when shader cache corruption is suspected. Game saves and settings are kept.", ForeColor = Color.Gainsboro, Margin = new Padding(0, 0, 0, Ui.S(12)) });
stack.Controls.Add(clear);
tab.Controls.Add(stack);
tab.Controls.Add(CreatePageHeader("Tools", "Shader preparation, cache maintenance and runtime utilities"));
tabs.TabPages.Add(tab);
}
void LoadSettings()
{
var values = File.Exists(settingsPath) ? File.ReadAllLines(settingsPath).Where(x => x.Contains('=')).Select(x => x.Split('=', 2)).GroupBy(x => x[0].Trim()).ToDictionary(g => g.Key, g => g.Last()[1].Trim()) : new Dictionary<string, string>();
var previousDefaults = new Dictionary<string, (string Old, string New)>(StringComparer.Ordinal)
{
["EONACAT_XS_MENU_RES"] = ("1440", "4k"),
["EONACAT_XS_MENU_DLSS"] = ("quality", "balanced"),
["EONACAT_XS_MENU_FPS"] = ("1000", "120"),
["EONACAT_XS_DISPLAY_REFRESH"] = ("60", "120"),
["EONACAT_XS_FPS_LINE"] = ("1", "0"),
["EONACAT_XS_FULLSCREEN"] = ("1", "stretch")
};
foreach (var s in Settings)
{
if (!editors.TryGetValue(s.Key, out var editor) || editor is not ComboBox c) continue;
var value = values.TryGetValue(s.Key, out var saved) ? saved : s.Default;
if (previousDefaults.TryGetValue(s.Key, out var migration) && value == migration.Old)
value = migration.New;
if (s.Values.Contains(value)) c.SelectedItem = value;
}
var savedGame = Path.Combine(Path.GetDirectoryName(settingsPath)!, "launcher-game.txt");
if (File.Exists(savedGame)) gamePath.Text = File.ReadAllText(savedGame).Trim();
}
void ApplyRtx4090Profile()
{
var profile = new Dictionary<string, string>(StringComparer.Ordinal)
{
["EONACAT_XS_MENU_CONSOLE"] = "series-x",
["EONACAT_XS_MENU_RES"] = "4k",
["EONACAT_XS_MENU_S_RES"] = "720",
["EONACAT_XS_MENU_DLSS"] = "balanced",
["EONACAT_XS_MENU_RT"] = "off",
["EONACAT_XS_MENU_FRAMEGEN"] = "0",
["EONACAT_XS_MENU_FG_TYPE"] = "auto",
["EONACAT_XS_MENU_FPS"] = "120",
["EONACAT_XS_DISPLAY_REFRESH"] = "120",
["EONACAT_XS_FULLSCREEN"] = "stretch",
["EONACAT_XS_NATIVE_WIDE"] = "",
["EONACAT_XS_ADVISOR"] = "0",
["EONACAT_XS_FPS_LINE"] = "0",
["EONACAT_XS_LAND_IN_PLACE"] = "2",
["EONACAT_XS_POOL_MIRROR"] = "2199",
["EONACAT_XS_POOL_MIRROR_TEXTURES"] = "1",
["EONACAT_XS_POOL_BACK"] = "0",
["EONACAT_XS_POOL_COHERENT"] = "1",
["EONACAT_XS_POOL_COHERENT_DIFF"] = "1",
["EONACAT_XS_POOL_COHERENT_NARROW"] = "1",
["EONACAT_XS_POOL_COHERENT_MAX_MB"] = "256",
["EONACAT_XS_SUBMIT_FRAMES"] = "2",
["EONACAT_XS_SUBMIT_DEPTH"] = "128",
["EONACAT_XS_WINDOW_KB"] = "256",
["EONACAT_XS_WINDOW_TAILS"] = "1",
["EONACAT_XS_TEXTURE_STAGE_MS"] = "24",
["EONACAT_XS_TEXTURE_NO_WAIT"] = "1",
["EONACAT_XS_TEXTURE_CATCHUP"] = "1",
["EONACAT_XS_TEXTURE_POOL"] = "1",
["EONACAT_XS_PAINTED_EVERY"] = "0",
["EONACAT_XS_CARD_POOLS"] = "185:38:47",
["EONACAT_XS_RANGE_MEMO"] = "1",
["EONACAT_XS_FAST_CORES"] = "1",
["EONACAT_XS_HEAP_HOOKS"] = "1",
["EONACAT_XS_CARD_FILLS"] = "1",
["EONACAT_XS_ARENA_UPLOAD"] = "1",
["EONACAT_XS_WC_NO_BACK"] = "1",
["EONACAT_XS_NO_GUARDS"] = "1",
["EONACAT_XS_COMING_AT_SUBMIT"] = "1",
["EONACAT_XS_STREAM_BOUND"] = "1",
};
foreach (var (key, value) in profile)
{
if (editors.TryGetValue(key, out var control) && control is ComboBox combo && combo.Items.Contains(value))
combo.SelectedItem = value;
}
SaveSettings();
status.Text = "Saved. 4K output is stretched to fill 3440x1440; native 21:9 rendering remains experimental. Install NVIDIA runtime for DLSS; restart.";
}
void SaveSettings()
{
Directory.CreateDirectory(Path.GetDirectoryName(settingsPath)!);
var existing = File.Exists(settingsPath) ? File.ReadAllLines(settingsPath).ToList() : new List<string>();
var managed = Settings.Select(s => s.Key).Concat(["EONACAT_XS_MENU_PRESET", "EONACAT_XS_MENU_ULTRA"]).ToHashSet(StringComparer.Ordinal);
existing.RemoveAll(line => line.Contains('=') && managed.Contains(line.Split('=', 2)[0].Trim()));
var sb = new StringBuilder(); sb.AppendLine("# EonaCat XS launcher settings. Generated by EonaCat XS Launcher.");
foreach (var line in existing) if (!line.StartsWith("# EonaCat XS launcher settings")) sb.AppendLine(line);
foreach (var s in Settings)
{
var value = editors.TryGetValue(s.Key, out var editor) && editor is ComboBox combo
? combo.SelectedItem?.ToString() ?? s.Default
: s.Default;
sb.AppendLine($"{s.Key}={value}");
}
var temp = settingsPath + ".tmp";
File.WriteAllText(temp, sb.ToString());
File.Move(temp, settingsPath, true);
if (selectedGame != null) gamePath.Text = selectedGame.Executable;
File.WriteAllText(Path.Combine(Path.GetDirectoryName(settingsPath)!, "launcher-game.txt"), gamePath.Text.Trim());
SaveGameLibrary();
status.Text = "Settings saved.";
}
}
@@ -0,0 +1,120 @@
using System.Text.RegularExpressions;
namespace EonaCat.XSBOX.Launcher;
internal sealed class PreloadProgressDialog : Form
{
static readonly Regex PipelineProgress = new(@"(?<done>\d+) of (?<total>\d+)");
static readonly Regex ShaderCount = new(@"(?<count>\d+) shaders so far");
static readonly Regex PipelineCount = new(@"(?<count>\d+) pipelines known");
readonly StackPanel stack = new() { Dock = DockStyle.Fill, AutoScroll = false };
readonly Panel accent = new() { Dock = DockStyle.Left, BackColor = Color.FromArgb(225, 48, 65) };
readonly WrapLabel heading = new() { Font = Ui.Font(17, FontStyle.Bold), ForeColor = Color.White };
readonly WrapLabel description = new() { ForeColor = Color.FromArgb(205, 194, 198) };
readonly WrapLabel detail = new() { Font = Ui.Font(8.5f), ForeColor = Color.FromArgb(155, 151, 158) };
readonly StretchProgressBar progress = new() { Height = Ui.S(12) };
readonly System.Windows.Forms.Timer closeTimer = new() { Interval = 1100 };
public PreloadProgressDialog()
{
Text = "EonaCat.XSBOX - Preparing game";
Icon = LauncherBrand.CreateIcon();
AutoScaleMode = AutoScaleMode.None;
ClientSize = new Size(Ui.S(540), Ui.S(230));
FormBorderStyle = FormBorderStyle.FixedDialog;
StartPosition = FormStartPosition.CenterScreen;
MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false;
BackColor = Color.FromArgb(18, 18, 22); ForeColor = Color.White;
Font = Ui.Font(9.5f);
ControlBox = false;
accent.Width = Ui.S(5);
stack.Padding = new Padding(Ui.S(26), Ui.S(20), Ui.S(26), Ui.S(18));
var brand = new WrapLabel
{
Text = "EONACAT / XS",
Font = Ui.Font(9, FontStyle.Bold),
ForeColor = Color.FromArgb(245, 65, 78),
Margin = new Padding(0, 0, 0, Ui.S(6))
};
heading.Text = "Preparing your game";
heading.Margin = new Padding(0, 0, 0, Ui.S(6));
description.Text = "The first launch can take a little while. This only needs to be done once per shader cache.";
description.Margin = new Padding(0, 0, 0, Ui.S(12));
progress.Style = ProgressBarStyle.Marquee;
progress.MarqueeAnimationSpeed = 24;
progress.Margin = new Padding(0, 0, 0, Ui.S(10));
detail.Text = "Starting shader compiler…";
stack.Controls.AddRange([brand, heading, description, progress, detail]);
Controls.Add(stack);
Controls.Add(accent);
closeTimer.Tick += (_, _) => { closeTimer.Stop(); Close(); };
FitHeight();
}
/// <summary>Grows or shrinks the dialog so wrapped text is never cut off.</summary>
void FitHeight()
{
var wanted = Math.Max(Ui.S(210), stack.Measure(ClientSize.Width - accent.Width));
if (wanted != ClientSize.Height) ClientSize = new Size(ClientSize.Width, wanted);
}
public void SetStage(string title, string explanation)
{
if (IsDisposed) return;
heading.Text = title;
description.Text = explanation;
detail.Text = "Working… your progress is saved as each item completes.";
FitHeight();
}
public void SetDetail(string line)
{
if (IsDisposed || string.IsNullOrWhiteSpace(line)) return;
string? text = null;
var match = PipelineProgress.Match(line);
if (match.Success && int.TryParse(match.Groups["done"].Value, out var done) && int.TryParse(match.Groups["total"].Value, out var total) && total > 0)
{
progress.Style = ProgressBarStyle.Continuous;
progress.MarqueeAnimationSpeed = 0;
progress.Minimum = 0; progress.Maximum = 100;
progress.Value = Math.Clamp((int)(done * 100L / total), 0, 100);
text = $"Building pipelines: {done:N0} of {total:N0}";
}
else if (line.Contains("shaders so far", StringComparison.OrdinalIgnoreCase))
{
var count = ShaderCount.Match(line);
text = count.Success ? $"Translated {count.Groups["count"].Value} shaders so far…" : "Compiling shaders…";
}
else if (line.Contains("pipelines known", StringComparison.OrdinalIgnoreCase))
{
var count = PipelineCount.Match(line);
text = count.Success ? $"Found {count.Groups["count"].Value} known pipelines; preparing build…" : "Preparing graphics pipelines…";
}
if (text != null && text != detail.Text) detail.Text = text;
}
public void Complete(bool success)
{
if (IsDisposed) return;
heading.Text = success ? "You're all set!" : "Preload finished with warnings";
description.Text = success
? "Shaders and graphics pipelines are ready. Starting your game now."
: "The game will still start. Any unfinished work can be retried on the next launch.";
detail.Text = success ? "Preparation complete" : "Continuing to game startup";
progress.Style = ProgressBarStyle.Continuous;
progress.MarqueeAnimationSpeed = 0;
progress.Value = 100;
FitHeight();
closeTimer.Start();
}
protected override void Dispose(bool disposing)
{
if (disposing) closeTimer.Dispose();
base.Dispose(disposing);
}
}
+338
View File
@@ -0,0 +1,338 @@
using System.Drawing.Drawing2D;
namespace EonaCat.XSBOX.Launcher;
/// <summary>A control that can report the height it needs for a given width.</summary>
internal interface IStackItem
{
int Measure(int width);
}
/// <summary>DPI scaling, cached fonts and text measuring shared by all launcher windows.</summary>
internal static class Ui
{
static float? scale;
static ToolTip? tip;
static readonly Dictionary<string, Font> fonts = new(StringComparer.Ordinal);
public const TextFormatFlags WrapFlags = TextFormatFlags.WordBreak | TextFormatFlags.NoPrefix | TextFormatFlags.Left | TextFormatFlags.Top;
public static ToolTip Tip => tip ??= new ToolTip { AutoPopDelay = 12000, InitialDelay = 450, ReshowDelay = 150, ShowAlways = true };
/// <summary>Scales a 96-DPI pixel value to the current display.</summary>
public static int S(int value)
{
scale ??= ReadScale();
return (int)Math.Round(value * scale.Value);
}
static float ReadScale()
{
using var g = Graphics.FromHwnd(IntPtr.Zero);
return g.DpiX / 96f;
}
/// <summary>Fonts are created once and reused for the lifetime of the app.</summary>
public static Font Font(float size, FontStyle style = FontStyle.Regular, string family = "Segoe UI")
{
var key = $"{family}|{size}|{(int)style}";
if (!fonts.TryGetValue(key, out var font)) fonts[key] = font = new Font(family, size, style);
return font;
}
public static int MeasureWrapped(string text, Font font, int width) =>
string.IsNullOrEmpty(text)
? font.Height
: TextRenderer.MeasureText(text, font, new Size(Math.Max(width, 1), int.MaxValue), WrapFlags).Height;
public static int MeasureWidth(string text, Font font) =>
TextRenderer.MeasureText(text, font, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.NoPadding).Width;
}
/// <summary>A label that always wraps and always reports the height its text needs.</summary>
internal sealed class WrapLabel : Label, IStackItem
{
int maxLines;
public WrapLabel()
{
AutoSize = false;
UseMnemonic = false; // '&' in "Display & Stats" must be drawn, not swallowed
BackColor = Color.Transparent;
Font = Ui.Font(9.5f);
}
/// <summary>When true the label resizes its own height (used for docked labels such as the status bar).</summary>
public bool AutoHeight { get; set; }
/// <summary>With AutoHeight, caps how many lines the label may grow to (0 = unlimited).</summary>
public int MaxLines { get => maxLines; set => maxLines = value; }
public int Measure(int width)
{
var h = Ui.MeasureWrapped(Text, Font, width - Padding.Horizontal - Ui.S(4)); // small slack: Label draws with slightly different padding than it measures
if (maxLines > 0) h = Math.Min(h, Font.Height * maxLines);
return h + Padding.Vertical + 2;
}
void FitHeight()
{
if (!AutoHeight || Width <= 0) return;
var h = Measure(Width);
if (h != Height) Height = h;
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (AutoHeight) FitHeight();
else Parent?.PerformLayout();
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (AutoHeight) FitHeight();
}
}
internal sealed class StretchProgressBar : ProgressBar, IStackItem
{
public int Measure(int width) => Height;
}
internal sealed class FlowRow : FlowLayoutPanel, IStackItem
{
public FlowRow()
{
WrapContents = true;
BackColor = Color.Transparent;
AutoSize = false;
}
public int Measure(int width) => GetPreferredSize(new Size(width, 0)).Height;
}
/// <summary>
/// Vertical layout where every child is as wide as the panel and as tall as its text needs.
/// Works as a scrolling page body or, with AutoScroll off, as a card inside another stack.
/// Layout is skipped while the panel is hidden, so tabs that were never opened cost nothing.
/// </summary>
internal sealed class StackPanel : Panel, IStackItem
{
bool inLayout;
public StackPanel()
{
AutoScroll = true;
DoubleBuffered = true;
ResizeRedraw = true;
}
/// <summary>Limits the content width on very wide windows (0 = no limit).</summary>
public int MaxContentWidth { get; set; }
static Size ChildSize(Control c, int width)
{
if (c is IStackItem item) return new Size(width, item.Measure(width));
return c.AutoSize ? c.GetPreferredSize(Size.Empty) : c.Size;
}
public int ContentHeight(int width)
{
var total = 0;
foreach (Control c in Controls)
{
var inner = width - c.Margin.Horizontal;
total += c.Margin.Top + ChildSize(c, inner).Height + c.Margin.Bottom;
}
return total;
}
public int Measure(int width) => Padding.Vertical + ContentHeight(width - Padding.Horizontal);
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
if (Visible) PerformLayout();
}
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
if (inLayout || !Visible) return;
inLayout = true;
try
{
for (var pass = 0; pass < 3; pass++)
{
var available = ClientSize.Width - Padding.Horizontal;
if (available <= 0) return;
var width = MaxContentWidth > 0 ? Math.Min(available, MaxContentWidth) : available;
var y = Padding.Top + (AutoScroll ? AutoScrollPosition.Y : 0);
foreach (Control c in Controls)
{
if (!c.Visible) continue;
var inner = width - c.Margin.Horizontal;
var size = ChildSize(c, inner);
c.SetBounds(Padding.Left + c.Margin.Left, y + c.Margin.Top, size.Width, size.Height);
y += c.Margin.Top + size.Height + c.Margin.Bottom;
}
if (AutoScroll) AutoScrollMinSize = new Size(0, y - AutoScrollPosition.Y + Padding.Bottom);
// A scrollbar appearing narrows the client area: lay out again with the real width.
if (ClientSize.Width - Padding.Horizontal == available) break;
}
}
finally { inLayout = false; }
}
}
/// <summary>One row of the settings pages: title, fully wrapped description and the value picker.</summary>
internal sealed class SettingCard : Panel, IStackItem
{
readonly Label name = new() { AutoSize = false, AutoEllipsis = true, UseMnemonic = false, BackColor = Color.Transparent, ForeColor = Color.White, Font = Ui.Font(10, FontStyle.Bold) };
readonly WrapLabel description = new() { ForeColor = Color.FromArgb(194, 187, 198), Font = Ui.Font(8.75f) };
readonly int comboWidth;
public ComboBox Editor { get; }
public SettingCard(Setting setting)
{
BackColor = Color.FromArgb(29, 25, 31);
Padding = new Padding(Ui.S(14), Ui.S(10), Ui.S(14), Ui.S(10));
Margin = new Padding(0, 0, 0, Ui.S(8));
name.Text = setting.Label;
description.Text = setting.Description;
Editor = new ComboBox
{
DropDownStyle = ComboBoxStyle.DropDownList,
FlatStyle = FlatStyle.Flat,
BackColor = Color.FromArgb(39, 32, 40),
ForeColor = Color.White,
Font = Ui.Font(9.5f),
FormattingEnabled = true,
Tag = setting.Key
};
Editor.Items.AddRange(setting.Values);
Editor.Format += (_, e) =>
{
if (e.ListItem is string option && option.Length == 0) e.Value = "Auto";
};
Editor.SelectedItem = setting.Default;
// Size the picker (and its drop-down) to the longest option so values are never clipped.
var widest = setting.Values.Select(v => Ui.MeasureWidth(v.Length == 0 ? "Auto" : v, Editor.Font)).DefaultIfEmpty(0).Max();
comboWidth = Math.Clamp(widest + Ui.S(48), Ui.S(200), Ui.S(360));
Editor.Width = comboWidth;
Editor.DropDownWidth = Math.Max(comboWidth, widest + Ui.S(48));
// Scrolling over a picker should scroll the page, not silently change the setting.
Editor.MouseWheel += (_, e) =>
{
if (e is HandledMouseEventArgs handled) handled.Handled = true;
if (Parent is ScrollableControl { AutoScroll: true } host)
{
var pos = host.AutoScrollPosition;
host.AutoScrollPosition = new Point(-pos.X, -pos.Y - e.Delta);
}
};
Controls.Add(name);
Controls.Add(description);
Controls.Add(Editor);
}
int NameHeight => name.Font.Height + Ui.S(2);
int TextWidth(int total) => Math.Max(Ui.S(160), total - Padding.Horizontal - comboWidth - Ui.S(20));
public int Measure(int width)
{
var text = Padding.Vertical + NameHeight + Ui.S(4) + description.Measure(TextWidth(width));
return Math.Max(text, Padding.Vertical + Ui.S(32));
}
protected override void OnLayout(LayoutEventArgs e)
{
base.OnLayout(e);
if (Editor == null) return; // Padding/Margin are set in the constructor before the picker exists
var w = ClientSize.Width;
if (w <= 0) return;
var textW = TextWidth(w);
name.SetBounds(Padding.Left, Padding.Top, textW, NameHeight);
description.SetBounds(Padding.Left, Padding.Top + NameHeight + Ui.S(4), textW, description.Measure(textW));
Editor.Location = new Point(w - Padding.Right - comboWidth, Padding.Top + Ui.S(2));
}
}
/// <summary>A custom-painted game tile: the name wraps to two lines with an ellipsis and never overflows.</summary>
internal sealed class GameTile : Control
{
static readonly Color Normal = Color.FromArgb(29, 24, 29);
static readonly Color Hover = Color.FromArgb(42, 33, 42);
static readonly Color Chosen = Color.FromArgb(78, 25, 32);
readonly GameEntry game;
readonly Bitmap? icon;
readonly bool selected;
bool hover;
public event Action<GameEntry>? GameChosen;
public GameTile(GameEntry game, Bitmap? icon, bool selected)
{
this.game = game;
this.icon = icon;
this.selected = selected;
Size = new Size(Ui.S(232), Ui.S(150));
Margin = new Padding(Ui.S(8));
Cursor = Cursors.Hand;
TabStop = true;
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true);
Ui.Tip.SetToolTip(this, $"{game.Name}\n{game.Directory}\nClick to select this game");
AccessibleName = game.Name;
}
protected override void OnMouseEnter(EventArgs e) { hover = true; Invalidate(); base.OnMouseEnter(e); }
protected override void OnMouseLeave(EventArgs e) { hover = false; Invalidate(); base.OnMouseLeave(e); }
protected override void OnGotFocus(EventArgs e) { Invalidate(); base.OnGotFocus(e); }
protected override void OnLostFocus(EventArgs e) { Invalidate(); base.OnLostFocus(e); }
protected override void OnClick(EventArgs e) { base.OnClick(e); Focus(); GameChosen?.Invoke(game); }
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode is Keys.Enter or Keys.Space) { e.Handled = true; GameChosen?.Invoke(game); }
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
using (var back = new SolidBrush(selected ? Chosen : hover ? Hover : Normal)) g.FillRectangle(back, ClientRectangle);
var borderWidth = selected ? 2 : 1;
using (var pen = new Pen(selected ? Color.FromArgb(245, 55, 65) : Color.FromArgb(93, 43, 49), borderWidth))
g.DrawRectangle(pen, borderWidth / 2, borderWidth / 2, Width - borderWidth, Height - borderWidth);
var pad = Ui.S(12);
var iconSize = Ui.S(40);
if (icon != null)
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(icon, new Rectangle((Width - iconSize) / 2, pad, iconSize, iconSize));
}
var nameFont = Ui.Font(9, FontStyle.Bold);
var fileFont = Ui.Font(8, FontStyle.Regular);
var textWidth = Width - pad * 2;
var fileRect = new Rectangle(pad, Height - pad - fileFont.Height, textWidth, fileFont.Height);
var nameTop = pad + iconSize + Ui.S(8);
var nameRect = new Rectangle(pad, nameTop, textWidth, Math.Max(nameFont.Height, fileRect.Top - Ui.S(4) - nameTop));
TextRenderer.DrawText(g, game.Name, nameFont, nameRect, Color.White,
TextFormatFlags.HorizontalCenter | TextFormatFlags.WordBreak | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.Top);
TextRenderer.DrawText(g, Path.GetFileName(game.Executable), fileFont, fileRect, Color.FromArgb(170, 164, 174),
TextFormatFlags.HorizontalCenter | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter);
if (Focused && ShowFocusCues) ControlPaint.DrawFocusRectangle(g, new Rectangle(3, 3, Width - 6, Height - 6));
}
}