Skip to content

ReStreet: FIFA Street (2012) recompiled for Windows PC, with online play, a launcher with friends, chat and rooms. Bring your own game.

Launcher source: update from 1.3 to 2.0.3

SamuelitoDaVila2034998d3864
diff --git a/Installer/FifaStreetSetupTool/ThemeKit.cs b/Installer/FifaStreetSetupTool/ThemeKit.cs
index 7722778..e7bef8c 100644
--- a/Installer/FifaStreetSetupTool/ThemeKit.cs
+++ b/Installer/FifaStreetSetupTool/ThemeKit.cs
@@ -56,8 +56,9 @@ internal static class StreetTheme
public static readonly Color YellowDark = Color.FromArgb(22, 19, 10);
public static readonly Color Ink = Color.FromArgb(242, 242, 238);
public static readonly Color Muted = Color.FromArgb(176, 178, 178);
- public static readonly Color Field = Color.FromArgb(24, 27, 31);
- public static readonly Color PanelFlat = Color.FromArgb(29, 30, 32);
+ public static readonly Color Field = Color.FromArgb(14, 16, 19);
+ public static readonly Color PanelFlat = Color.FromArgb(24, 26, 30);
+ public static readonly Color Hairline = Color.FromArgb(30, 255, 255, 255);
public const int DesignWidth = 930;
@@ -99,6 +100,14 @@ internal static class StreetTheme
public static PointF[] Slant(RectangleF r, float cut) =>
new[] { new PointF(r.X, r.Y), new PointF(r.Right, r.Y), new PointF(r.Right - cut, r.Bottom), new PointF(r.X, r.Bottom) };
+ // Wine/Proton's GDI+ lacks some brushes (path gradient focus scales, texture brushes): a missing effect is skipped
+ // instead of failing the whole paint, which WinForms shows as a red cross on every control.
+ public static void Optional(Action effect)
+ {
+ try { effect(); }
+ catch (Exception ex) when (ex is NotImplementedException or ArgumentException or ExternalException or OutOfMemoryException or InvalidOperationException) { }
+ }
+
public static Bitmap RenderBackdrop(Size size, float designWidth, float designHeight)
{
float s = size.Width / designWidth;
@@ -109,17 +118,18 @@ internal static class StreetTheme
g.ScaleTransform(s, s);
float w = designWidth, h = designHeight;
- using (var grain = new Bitmap(128, 128, PixelFormat.Format32bppPArgb))
+ Optional(() =>
{
+ using var grain = new Bitmap(128, 128, PixelFormat.Format32bppPArgb);
var rnd = new Random(7);
for (int y = 0; y < 128; y++)
for (int x = 0; x < 128; x++)
- grain.SetPixel(x, y, Color.FromArgb(rnd.Next(0, 22), 255, 255, 255));
+ grain.SetPixel(x, y, Color.FromArgb(rnd.Next(0, 14), 255, 255, 255));
using var brush = new TextureBrush(grain, WrapMode.Tile);
g.FillRectangle(brush, 0, 0, w, h + 400);
- }
+ });
- using (var fence = new Pen(Color.FromArgb(15, 255, 255, 255), 1f))
+ using (var fence = new Pen(Color.FromArgb(7, 255, 255, 255), 1f))
{
for (float i = -h; i < w + h; i += 16)
{
@@ -128,22 +138,37 @@ internal static class StreetTheme
}
}
- using (var light = new GraphicsPath())
+ Optional(() =>
{
+ using var light = new GraphicsPath();
light.AddEllipse(w * 0.2f, -h * 1.1f, w * 1.1f, h * 1.9f);
using var brush = new PathGradientBrush(light)
{
- CenterColor = Color.FromArgb(54, 255, 244, 214),
+ CenterColor = Color.FromArgb(44, 255, 244, 214),
SurroundColors = new[] { Color.FromArgb(0, 255, 244, 214) },
CenterPoint = new PointF(w * 0.78f, 0)
};
g.FillPath(brush, light);
- }
+ });
// Court markings: a centre circle and the halfway line, kept away from the text columns.
using var line = new Pen(Color.FromArgb(40, 255, 255, 255), 3f);
g.DrawEllipse(line, w * 0.24f - h * 0.5f, h * 1.1f - h * 0.5f, h, h);
g.DrawLine(line, -10, h * 0.76f, w + 10, h * 0.76f);
+
+ // Vignette: darker edges keep the eye on the content.
+ Optional(() =>
+ {
+ using var edge = new GraphicsPath();
+ edge.AddEllipse(-w * 0.25f, -h * 0.35f, w * 1.5f, h * 1.7f);
+ using var brush = new PathGradientBrush(edge)
+ {
+ CenterColor = Color.FromArgb(0, 0, 0, 0),
+ SurroundColors = new[] { Color.FromArgb(150, 0, 0, 0) },
+ FocusScales = new PointF(0.55f, 0.5f)
+ };
+ g.FillRectangle(brush, -10, -10, w + 20, h + 20);
+ });
return bmp;
}
@@ -173,18 +198,37 @@ internal static class StreetTheme
{
using var path = Round(rect, radius);
var state = g.Save();
- g.SetClip(path, CombineMode.Intersect);
- var source = new RectangleF(rect.X * scale, rect.Y * scale, rect.Width * scale, rect.Height * scale);
- g.DrawImage(blurred, rect, source, GraphicsUnit.Pixel);
- using (var veil = new SolidBrush(Color.FromArgb(34, 236, 240, 245))) g.FillPath(veil, path);
- using (var sheen = new LinearGradientBrush(new RectangleF(rect.X, rect.Y, rect.Width, 120), Color.FromArgb(44, 255, 255, 255), Color.FromArgb(0, 255, 255, 255), 90f))
- g.FillRectangle(sheen, rect.X, rect.Y, rect.Width, 120);
+ Optional(() =>
+ {
+ g.SetClip(path, CombineMode.Intersect);
+ var source = new RectangleF(rect.X * scale, rect.Y * scale, rect.Width * scale, rect.Height * scale);
+ g.DrawImage(blurred, rect, source, GraphicsUnit.Pixel);
+ });
+ using (var smoke = new SolidBrush(Color.FromArgb(214, 20, 22, 26))) g.FillPath(smoke, path);
+ Optional(() =>
+ {
+ using var sheen = new LinearGradientBrush(new RectangleF(rect.X, rect.Y, rect.Width, 96), Color.FromArgb(14, 255, 255, 255), Color.FromArgb(0, 255, 255, 255), 90f);
+ g.FillRectangle(sheen, rect.X, rect.Y, rect.Width, 96);
+ });
g.Restore(state);
- using (var edge = new Pen(Color.FromArgb(58, 255, 255, 255), 1f)) g.DrawPath(edge, path);
- using (var top = new Pen(Color.FromArgb(120, 255, 255, 255), 1f))
+ using (var edge = new Pen(Color.FromArgb(34, 255, 255, 255), 1f)) g.DrawPath(edge, path);
+ using (var top = new Pen(Color.FromArgb(56, 255, 255, 255), 1f))
g.DrawLine(top, rect.X + radius, rect.Y + 0.5f, rect.Right - radius, rect.Y + 0.5f);
}
+ // Section title on a panel: a short yellow tick, the title, and a hairline to `right`. Design coordinates.
+ public static void DrawSection(Graphics g, string title, float x, float y, float right)
+ {
+ using (var tick = new SolidBrush(Yellow)) g.FillRectangle(tick, x, y + 2, 3, 12);
+ using var font = new Font(CondensedFamily, 13, FontStyle.Bold, GraphicsUnit.Pixel);
+ using var ink = new SolidBrush(Ink);
+ DrawSpaced(g, title, font, ink, new PointF(x + 11, y), 1.6f);
+ float end = x + 11;
+ foreach (char c in title) end += g.MeasureString(c.ToString(), font, PointF.Empty, StringFormat.GenericTypographic).Width + 1.6f + (c == ' ' ? font.Size * 0.15f : 0);
+ using var line = new Pen(Hairline, 1f);
+ g.DrawLine(line, end + 10, y + 8.5f, right, y + 8.5f);
+ }
+
// Wordmark drawn as a path so it can be sheared like the game's lettering. The ink's left edge
// and top edge land exactly on `origin`.
public static void DrawWordmark(Graphics g, string text, PointF origin, float pixelSize, Color color)
@@ -342,11 +386,11 @@ internal sealed class SlantButton : Button
}
case SlantKind.Glass:
{
- int alpha = !enabled ? 18 : down ? 70 : Active ? 62 : hot ? 56 : 36;
+ int alpha = !enabled ? 8 : down ? 40 : Active ? 26 : hot ? 30 : 16;
using var brush = new SolidBrush(Color.FromArgb(alpha, 255, 255, 255));
- using var path = StreetTheme.Round(rect, 8 * k);
+ using var path = StreetTheme.Round(rect, 6 * k);
g.FillPath(brush, path);
- using var pen = new Pen(Active ? StreetTheme.Yellow : Color.FromArgb(enabled ? 70 : 30, 255, 255, 255));
+ using var pen = new Pen(Active ? StreetTheme.Yellow : Color.FromArgb(!enabled ? 20 : hot ? 80 : 44, 255, 255, 255));
g.DrawPath(pen, path);
text = !enabled ? StreetTheme.Muted : Active ? StreetTheme.Yellow : StreetTheme.Ink;
break;
@@ -357,8 +401,9 @@ internal sealed class SlantButton : Button
}
if (Focused && ShowFocusCues && Kind != SlantKind.Primary)
{
- using var pen = new Pen(Color.FromArgb(160, StreetTheme.Yellow));
- g.DrawRectangle(pen, 1, 1, Width - 3, Height - 3);
+ using var pen = new Pen(Color.FromArgb(200, StreetTheme.Yellow), Math.Max(1f, 1.5f * k));
+ using var ring = StreetTheme.Round(new RectangleF(1.5f, 1.5f, Width - 3, Height - 3), 6 * k);
+ g.DrawPath(pen, ring);
}
var format = TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine;
format |= Kind == SlantKind.Text
@@ -479,9 +524,9 @@ internal sealed class GlassToggle : CheckBox
var track = new RectangleF(0.5f, top, trackW, trackH);
using (var path = StreetTheme.Round(track, trackH / 2))
{
- using var fill = new SolidBrush(Checked ? (Enabled ? StreetTheme.Yellow : Color.FromArgb(110, StreetTheme.Yellow)) : Color.FromArgb(Enabled ? 58 : 28, 255, 255, 255));
+ using var fill = new SolidBrush(Checked ? (Enabled ? StreetTheme.Yellow : Color.FromArgb(110, StreetTheme.Yellow)) : Color.FromArgb(Enabled ? 40 : 20, 255, 255, 255));
g.FillPath(fill, path);
- using var edge = new Pen(Color.FromArgb(Checked ? 0 : 70, 255, 255, 255));
+ using var edge = new Pen(Color.FromArgb(Checked ? 0 : 56, 255, 255, 255));
g.DrawPath(edge, path);
}
float knob = 14 * k, inset = 3 * k;
@@ -535,9 +580,9 @@ internal sealed class FieldFrame : Control
StreetTheme.PaintBehind(this, g);
g.SmoothingMode = SmoothingMode.AntiAlias;
var rect = new RectangleF(0.5f, 0.5f, Width - 1, Height - 1);
- using var path = StreetTheme.Round(rect, 8 * StreetTheme.K(this));
+ using var path = StreetTheme.Round(rect, 6 * StreetTheme.K(this));
using (var fill = new SolidBrush(StreetTheme.Field)) g.FillPath(fill, path);
- using var edge = new Pen(Box.Focused ? Color.FromArgb(200, StreetTheme.Yellow) : Color.FromArgb(60, 255, 255, 255));
+ using var edge = new Pen(Box.Focused ? Color.FromArgb(220, StreetTheme.Yellow) : Color.FromArgb(40, 255, 255, 255));
g.DrawPath(edge, path);
}
}
@@ -582,7 +627,7 @@ internal sealed class GlassCombo : ComboBox
{
if (e.Index < 0) return;
bool selected = (e.State & DrawItemState.Selected) != 0 && (e.State & DrawItemState.ComboBoxEdit) == 0;
- using (var background = new SolidBrush(selected ? Color.FromArgb(52, 54, 58) : StreetTheme.Field)) e.Graphics.FillRectangle(background, e.Bounds);
+ using (var background = new SolidBrush(selected ? Color.FromArgb(38, 41, 46) : StreetTheme.Field)) e.Graphics.FillRectangle(background, e.Bounds);
if (selected)
{
using var bar = new SolidBrush(StreetTheme.Yellow);
@@ -629,10 +674,10 @@ internal sealed class GlassCombo : ComboBox
g.SmoothingMode = SmoothingMode.AntiAlias;
float k = StreetTheme.K(this);
var rect = new RectangleF(0.5f, 0.5f, Width - 1, Height - 1);
- using var path = StreetTheme.Round(rect, 8 * k);
+ using var path = StreetTheme.Round(rect, 6 * k);
using (var fill = new SolidBrush(StreetTheme.Field)) g.FillPath(fill, path);
bool active = Focused || DroppedDown;
- using (var edge = new Pen(active ? Color.FromArgb(200, StreetTheme.Yellow) : hot && Enabled ? Color.FromArgb(110, 255, 255, 255) : Color.FromArgb(60, 255, 255, 255)))
+ using (var edge = new Pen(active ? Color.FromArgb(220, StreetTheme.Yellow) : hot && Enabled ? Color.FromArgb(96, 255, 255, 255) : Color.FromArgb(40, 255, 255, 255)))
g.DrawPath(edge, path);
string text = SelectedIndex >= 0 ? GetItemText(Items[SelectedIndex]) : Text;
TextRenderer.DrawText(g, text, Font, new Rectangle((int)(12 * k), 0, Width - (int)(46 * k), Height), Enabled ? StreetTheme.Ink : StreetTheme.Muted,
@@ -671,6 +716,9 @@ internal sealed class UiScaler
public float Scale { get; private set; } = 1f;
+ // False once a window sizes itself (the launcher's resizable page): Apply then leaves the window alone.
+ public bool Enabled { get; set; } = true;
+
// Testing and support overrides: RESTREET_UI_DPI=150 (percent) and RESTREET_UI_AREA=1280x680 (work area).
static float? DpiOverride => float.TryParse(Environment.GetEnvironmentVariable("RESTREET_UI_DPI"), out float percent) && percent >= 50 ? percent / 100f : null;
static Size? AreaOverride
@@ -729,7 +777,7 @@ internal sealed class UiScaler
public void Apply()
{
- if (applying || !captured) return;
+ if (!Enabled || applying || !captured) return;
applying = true;
try
{
diff --git a/Launcher/FifaStreetLauncher/BrowserUi.cs b/Launcher/FifaStreetLauncher/BrowserUi.cs
new file mode 100644
index 0000000..2e0ba75
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/BrowserUi.cs
@@ -0,0 +1,214 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.Net;
+using System.Net.Sockets;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace FifaStreetLauncher;
+
+// The new launcher page without WebView2 (Wine/Proton, or a Windows without the runtime): the same ui/launcher.html is
+// served on 127.0.0.1 only, under a random secret path, and opened in the system browser. The page talks to the
+// launcher with POST <secret>/msg and long-polls GET <secret>/events; everything else stays as with WebView2. The
+// classic window is hidden, and the launcher exits when the page has been closed for a while and no game is running.
+public partial class LauncherForm
+{
+ private TcpListener? browserListener;
+ private string browserSecret = "";
+ private bool browserActive;
+ private DateTime browserLastSeen = DateTime.UtcNow;
+ private readonly ConcurrentQueue<string> browserOutbox = new();
+ private readonly SemaphoreSlim browserSignal = new(0);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Ansi)] private static extern IntPtr GetModuleHandleA(string name);
+ [DllImport("kernel32.dll", CharSet = CharSet.Ansi)] private static extern IntPtr GetProcAddress(IntPtr module, string name);
+
+ // Wine (and Proton) export wine_get_version from ntdll; WebView2 is not reliable there.
+ internal static bool RunningOnWine()
+ {
+ IntPtr ntdll = GetModuleHandleA("ntdll.dll");
+ return ntdll != IntPtr.Zero && GetProcAddress(ntdll, "wine_get_version") != IntPtr.Zero;
+ }
+
+ private bool PageConnected => glass?.CoreWebView2 != null || browserActive;
+
+ // Every message for the page goes through here, whichever way the page is shown.
+ private void SendToPage(string json)
+ {
+ if (browserActive)
+ {
+ browserOutbox.Enqueue(json);
+ browserSignal.Release();
+ return;
+ }
+ if (InvokeRequired) BeginInvoke(() => glass?.CoreWebView2?.PostWebMessageAsJson(json));
+ else glass?.CoreWebView2?.PostWebMessageAsJson(json);
+ }
+
+ private void StartBrowserUi()
+ {
+ if (browserActive) return;
+ string ui = Path.Combine(AppContext.BaseDirectory, "ui");
+ if (!File.Exists(Path.Combine(ui, "launcher.html"))) return; // no page: the classic window stays
+ browserSecret = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
+ browserListener = new TcpListener(IPAddress.Loopback, 0);
+ browserListener.Start();
+ browserActive = true;
+ browserLastSeen = DateTime.UtcNow;
+ int port = ((IPEndPoint)browserListener.LocalEndpoint).Port;
+ _ = Task.Run(() => AcceptBrowserClients(ui));
+ string url = $"http://127.0.0.1:{port}/{browserSecret}/launcher.html";
+ try
+ {
+ // A window of its own, the launcher's size, when a Chromium browser is there; otherwise the default browser.
+ if (!OpenAppWindow(url)) Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
+ }
+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
+ {
+ browserActive = false; // no browser to open: keep the classic window
+ browserListener.Stop();
+ return;
+ }
+ // Only the new interface is shown: hide the classic window (it keeps launching the game and restoring the display).
+ Opacity = 0;
+ ShowInTaskbar = false;
+ var watchdog = new System.Windows.Forms.Timer { Interval = 15000 };
+ watchdog.Tick += (_, _) =>
+ {
+ if (!gameRunning && !updating && DateTime.UtcNow - browserLastSeen > TimeSpan.FromSeconds(90)) Close();
+ };
+ watchdog.Start();
+ }
+
+ // Chromium-family browsers open a URL as an app window (no tabs, no address bar) with --app; a profile of its own
+ // makes it a new window of the requested size even when the browser is already open.
+ private bool OpenAppWindow(string url)
+ {
+ string size = $"--window-size={Width},{Height}";
+ if (RunningOnWine())
+ {
+ string[] unix =
+ {
+ "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome",
+ "/usr/bin/brave", "/usr/bin/brave-browser", "/usr/bin/microsoft-edge-stable", "/usr/bin/vivaldi-stable",
+ "/var/lib/flatpak/exports/bin/org.chromium.Chromium", "/var/lib/flatpak/exports/bin/com.google.Chrome",
+ "/var/lib/flatpak/exports/bin/com.brave.Browser", "/var/lib/flatpak/exports/bin/com.microsoft.Edge",
+ };
+ // Wine maps the Linux root to Z:, and start.exe /unix runs a Linux program.
+ string? found = unix.FirstOrDefault(p => File.Exists("Z:" + p.Replace('/', '\\')));
+ if (found == null) return false;
+ Process.Start(new ProcessStartInfo("start.exe")
+ {
+ ArgumentList = { "/unix", found, "--app=" + url, size, "--user-data-dir=/tmp/restreet-launcher-ui" },
+ UseShellExecute = false, CreateNoWindow = true,
+ });
+ return true;
+ }
+ string pf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
+ string pf86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
+ string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
+ string? exe = new[]
+ {
+ Path.Combine(pf86, @"Microsoft\Edge\Application\msedge.exe"), Path.Combine(pf, @"Microsoft\Edge\Application\msedge.exe"),
+ Path.Combine(pf, @"Google\Chrome\Application\chrome.exe"), Path.Combine(pf86, @"Google\Chrome\Application\chrome.exe"),
+ Path.Combine(local, @"Google\Chrome\Application\chrome.exe"),
+ Path.Combine(pf, @"BraveSoftware\Brave-Browser\Applicationrave.exe"),
+ }.FirstOrDefault(File.Exists);
+ if (exe == null) return false;
+ Process.Start(new ProcessStartInfo(exe)
+ {
+ ArgumentList = { "--app=" + url, size, "--user-data-dir=" + Path.Combine(local, "ReStreet", "LauncherWindow") },
+ UseShellExecute = false,
+ });
+ return true;
+ }
+
+ private async Task AcceptBrowserClients(string ui)
+ {
+ while (browserActive && browserListener != null)
+ {
+ TcpClient client;
+ try { client = await browserListener.AcceptTcpClientAsync(); }
+ catch (Exception ex) when (ex is SocketException or ObjectDisposedException or InvalidOperationException) { return; }
+ _ = Task.Run(() => ServeBrowserClient(client, ui));
+ }
+ }
+
+ private async Task ServeBrowserClient(TcpClient client, string ui)
+ {
+ using var _ = client;
+ try
+ {
+ var stream = client.GetStream();
+ var (method, path, body) = await ReadRequest(stream);
+ string prefix = "/" + browserSecret + "/";
+ if (!path.StartsWith(prefix, StringComparison.Ordinal)) { await Respond(stream, 404, "text/plain", Array.Empty<byte>()); return; }
+ string rest = path[prefix.Length..].Split('?')[0];
+ browserLastSeen = DateTime.UtcNow;
+ if (method == "POST" && rest == "msg")
+ {
+ string json = Encoding.UTF8.GetString(body);
+ BeginInvoke(() => OnGlassMessage(json));
+ await Respond(stream, 204, "text/plain", Array.Empty<byte>());
+ }
+ else if (method == "GET" && rest == "events")
+ {
+ // Long poll: answer at once when something is queued, otherwise after 20 s with an empty list.
+ await browserSignal.WaitAsync(TimeSpan.FromSeconds(20));
+ var items = new List<string>();
+ while (browserOutbox.TryDequeue(out var item)) items.Add(item);
+ await Respond(stream, 200, "application/json", Encoding.UTF8.GetBytes("[" + string.Join(",", items) + "]"));
+ }
+ else if (method == "GET" && rest.Length > 0 && rest.IndexOfAny(new[] { '/', '\\' }) < 0 && !rest.Contains(".."))
+ {
+ string file = Path.Combine(ui, rest);
+ string type = Path.GetExtension(file).ToLowerInvariant() switch
+ {
+ ".html" => "text/html; charset=utf-8", ".jpg" => "image/jpeg", ".png" => "image/png",
+ ".css" => "text/css", ".js" => "text/javascript", _ => "application/octet-stream",
+ };
+ if (File.Exists(file)) await Respond(stream, 200, type, await File.ReadAllBytesAsync(file));
+ else await Respond(stream, 404, "text/plain", Array.Empty<byte>());
+ }
+ else await Respond(stream, 404, "text/plain", Array.Empty<byte>());
+ }
+ catch (Exception ex) when (ex is IOException or SocketException or ObjectDisposedException or InvalidOperationException) { }
+ }
+
+ private static async Task<(string Method, string Path, byte[] Body)> ReadRequest(NetworkStream stream)
+ {
+ var head = new List<byte>();
+ var one = new byte[1];
+ while (head.Count < 16384 && await stream.ReadAsync(one) == 1)
+ {
+ head.Add(one[0]);
+ int n = head.Count;
+ if (n >= 4 && head[n - 4] == '\r' && head[n - 3] == '\n' && head[n - 2] == '\r' && head[n - 1] == '\n') break;
+ }
+ string[] lines = Encoding.ASCII.GetString(head.ToArray()).Split("\r\n");
+ string[] first = lines[0].Split(' ');
+ if (first.Length < 2) throw new IOException("bad request");
+ int length = 0;
+ foreach (string line in lines)
+ if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) int.TryParse(line[15..].Trim(), out length);
+ length = Math.Clamp(length, 0, 65536);
+ var body = new byte[length];
+ for (int read = 0; read < length;)
+ {
+ int got = await stream.ReadAsync(body.AsMemory(read));
+ if (got == 0) break;
+ read += got;
+ }
+ return (first[0], first[1], body);
+ }
+
+ private static async Task Respond(NetworkStream stream, int status, string type, byte[] body)
+ {
+ string reason = status switch { 200 => "OK", 204 => "No Content", _ => "Not Found" };
+ string header = $"HTTP/1.1 {status} {reason}\r\nContent-Type: {type}\r\nContent-Length: {body.Length}\r\n" +
+ "Cache-Control: no-store\r\nConnection: close\r\n\r\n";
+ await stream.WriteAsync(Encoding.ASCII.GetBytes(header));
+ if (body.Length > 0) await stream.WriteAsync(body);
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/Controls.cs b/Launcher/FifaStreetLauncher/Controls.cs
new file mode 100644
index 0000000..1d50ad8
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/Controls.cs
@@ -0,0 +1,104 @@
+using System.Diagnostics;
+using System.Text.Json;
+
+namespace FifaStreetLauncher;
+
+// Controls page: play with the keyboard (and mouse) instead of a controller. The runtime's keyboard mode presents the
+// keys as an Xbox controller (cvars mnk_mode, mnk_mouse, mnk_sensitivity, keybind_*), so the game needs no change.
+// Saved in controls.json beside settings.json; passed to the game as REX_* variables on PLAY.
+public partial class LauncherForm
+{
+ public sealed class ControlsSettings
+ {
+ public bool Keyboard { get; set; }
+ public bool MouseTricks { get; set; } = true; // the default layout is keyboard + mouse
+ public double MouseSensitivity { get; set; } = 1.0;
+ // Controller button (runtime cvar suffix, e.g. "a", "lstick_up") -> keys, "Space,Semicolon" style.
+ public Dictionary<string, string> Keys { get; set; } = new(DefaultKeys);
+ }
+
+ // Layouts made for FIFA Street (the game's own tips): LT held = Street Ball Control (and jockey), RT = sprint /
+ // panna, LB held = flair pass or shot, RB = juggle, R3 = stand on the ball, right stick = skill moves, Y = manual
+ // pass. The left hand always has WASD, Shift sprint, Space ball control, Q flair, E juggle; Enter / Backspace / Esc
+ // work in the menus.
+ // Keyboard + mouse: the mouse moves the right stick (skills) and its buttons pass / shoot / lob.
+ public static readonly IReadOnlyDictionary<string, string> MouseKeys = new Dictionary<string, string>
+ {
+ ["lstick_up"] = "W", ["lstick_down"] = "S", ["lstick_left"] = "A", ["lstick_right"] = "D", ["lstick_press"] = "C",
+ ["rstick_up"] = "Up", ["rstick_down"] = "Down", ["rstick_left"] = "Left", ["rstick_right"] = "Right", ["rstick_press"] = "F",
+ ["a"] = "LMB,Return", ["b"] = "RMB,Backspace", ["x"] = "MMB", ["y"] = "R",
+ ["left_trigger"] = "Space", ["right_trigger"] = "Shift", ["left_shoulder"] = "Q", ["right_shoulder"] = "E",
+ ["dpad_up"] = "1", ["dpad_down"] = "2", ["dpad_left"] = "3", ["dpad_right"] = "4",
+ ["start"] = "Escape", ["back"] = "Tab",
+ };
+ // Keyboard only: the right hand passes / shoots on J K L I and does skills on the arrows.
+ public static readonly IReadOnlyDictionary<string, string> KeyboardKeys = new Dictionary<string, string>(MouseKeys)
+ {
+ ["rstick_press"] = "O", ["a"] = "J,Return", ["b"] = "K,Backspace", ["x"] = "L", ["y"] = "I",
+ };
+ public static readonly IReadOnlyDictionary<string, string> DefaultKeys = MouseKeys;
+
+ private ControlsSettings? controls;
+ private string ControlsPath => Path.Combine(AppContext.BaseDirectory, "controls.json");
+
+ private ControlsSettings InputControls()
+ {
+ if (controls != null) return controls;
+ try
+ {
+ if (File.Exists(ControlsPath)) controls = JsonSerializer.Deserialize<ControlsSettings>(File.ReadAllText(ControlsPath));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ Debug.WriteLine(ex.Message);
+ }
+ controls ??= new ControlsSettings();
+ // Buttons added in a later launcher keep their default key.
+ foreach (var (button, keys) in DefaultKeys) controls.Keys.TryAdd(button, keys);
+ return controls;
+ }
+
+ // From the page: the whole controls object. Only known buttons are kept; the page already refuses the runtime's
+ // own overlay keys and repeated keys.
+ private void SetControls(JsonElement value)
+ {
+ var current = InputControls();
+ if (value.TryGetProperty("keyboard", out var k) && k.ValueKind is JsonValueKind.True or JsonValueKind.False) current.Keyboard = k.GetBoolean();
+ if (value.TryGetProperty("mouseTricks", out var mt) && mt.ValueKind is JsonValueKind.True or JsonValueKind.False) current.MouseTricks = mt.GetBoolean();
+ if (value.TryGetProperty("sensitivity", out var s) && s.ValueKind == JsonValueKind.Number) current.MouseSensitivity = Math.Clamp(s.GetDouble(), 0.1, 5.0);
+ if (value.TryGetProperty("keys", out var keys) && keys.ValueKind == JsonValueKind.Object)
+ foreach (var p in keys.EnumerateObject())
+ if (DefaultKeys.ContainsKey(p.Name) && p.Value.ValueKind == JsonValueKind.String)
+ current.Keys[p.Name] = p.Value.GetString()!.Length <= 64 ? p.Value.GetString()! : DefaultKeys[p.Name];
+ if (value.TryGetProperty("preset", out var pr) && pr.ValueKind == JsonValueKind.String)
+ {
+ bool mouse = pr.GetString() == "mouse";
+ current.Keys = new(mouse ? MouseKeys : KeyboardKeys);
+ current.MouseTricks = mouse;
+ }
+ try
+ {
+ File.WriteAllText(ControlsPath, JsonSerializer.Serialize(current, new JsonSerializerOptions { WriteIndented = true }));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ UpdateStatus("Could not save the controls: " + ex.Message, false);
+ }
+ }
+
+ private object ControlsState()
+ {
+ var c = InputControls();
+ return new { keyboard = c.Keyboard, mouseTricks = c.MouseTricks, sensitivity = c.MouseSensitivity, keys = c.Keys };
+ }
+
+ private void ApplyControls(ProcessStartInfo startInfo)
+ {
+ var c = InputControls();
+ startInfo.Environment["REX_MNK_MODE"] = c.Keyboard ? "true" : "false";
+ startInfo.Environment["REX_MNK_MOUSE"] = c.Keyboard && c.MouseTricks ? "true" : "false";
+ startInfo.Environment["REX_MNK_SENSITIVITY"] = c.MouseSensitivity.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ foreach (var (button, keys) in c.Keys)
+ if (DefaultKeys.ContainsKey(button)) startInfo.Environment["REX_KEYBIND_" + button.ToUpperInvariant()] = keys;
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/DeckLaunch.cs b/Launcher/FifaStreetLauncher/DeckLaunch.cs
new file mode 100644
index 0000000..aa04f72
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/DeckLaunch.cs
@@ -0,0 +1,182 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Text;
+
+namespace FifaStreetLauncher;
+
+// ReStreet 2.0 (the deck base): the graphics options live in the game's fifastreet.toml, the same file the in-game
+// menu (F5 / L3+R3) writes, so the launcher and the menu always show the same values. The launcher reads the file
+// when it opens and writes it before starting the game; it passes no REX_* graphics variables (they would beat the
+// file). The game always runs at 1280x720 inside (the runtime ignores the window size for that); the window size, the
+// internal resolution and the scaling only change how the image is drawn and shown.
+public partial class LauncherForm
+{
+ private readonly ComboBox scalingBox = new() { DropDownStyle = ComboBoxStyle.DropDownList };
+ private readonly ComboBox aspectBox = new() { DropDownStyle = ComboBoxStyle.DropDownList };
+ private readonly ComboBox fpsLimitBox = new() { DropDownStyle = ComboBoxStyle.DropDownList };
+ private readonly ComboBox anisoBox = new() { DropDownStyle = ComboBoxStyle.DropDownList };
+ private readonly ComboBox occlusionBox = new() { DropDownStyle = ComboBoxStyle.DropDownList };
+
+ // (label, present_effect, modo_fsr)
+ private static readonly (string Label, string Effect, string Mode)[] DeckScaling =
+ {
+ ("Bilinear", "bilinear", ""), ("FSR 1", "fsr", ""), ("FSR 1 Quality", "fsr", "calidad"),
+ ("FSR 1 Balanced", "fsr", "equilibrado"), ("FSR 1 Performance", "fsr", "rendimiento"),
+ ("FSR 1 Ultra Performance", "fsr", "ultra_rendimiento"),
+ };
+ private static readonly (string Label, double Hz)[] DeckFpsLimits =
+ {
+ ("Screen refresh rate", -1), ("No limit", 0), ("30", 30), ("60", 60), ("90", 90), ("120", 120), ("144", 144),
+ ("165", 165), ("240", 240),
+ };
+ private static readonly (string Label, int Value)[] DeckAniso =
+ {
+ ("Game default", -1), ("Off", 0), ("1x", 1), ("2x", 2), ("4x", 3), ("8x", 4), ("16x", 5),
+ };
+ private static readonly (string Label, string Value)[] DeckOcclusion = { ("Off", ""), ("SSAO", "ssao"), ("HBAO", "hbao"), ("GTAO", "gtao") };
+
+ private bool deckBase;
+
+ private static bool IsDeckBase(string exeDirectory) => File.Exists(Path.Combine(exeDirectory, "ajustes-del-port.txt"));
+
+ private string ExeDirectory()
+ {
+ try { return Path.GetDirectoryName(Path.GetFullPath(exePathBox.Text.Trim())) ?? AppContext.BaseDirectory; }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) { return AppContext.BaseDirectory; }
+ }
+
+ // Called after LoadSettings: fills the deck lists and takes the current values from fifastreet.toml.
+ private void InitDeckOptions()
+ {
+ deckBase = IsDeckBase(ExeDirectory());
+ if (!deckBase) return;
+ scalingBox.Items.AddRange(DeckScaling.Select(s => (object)s.Label).ToArray());
+ aspectBox.Items.AddRange(new object[] { "Match screen", "16:9 (console)" });
+ fpsLimitBox.Items.AddRange(DeckFpsLimits.Select(s => (object)s.Label).ToArray());
+ anisoBox.Items.AddRange(DeckAniso.Select(s => (object)s.Label).ToArray());
+ occlusionBox.Items.AddRange(DeckOcclusion.Select(s => (object)s.Label).ToArray());
+ scalingBox.SelectedIndex = 1; aspectBox.SelectedIndex = 0; fpsLimitBox.SelectedIndex = 0; anisoBox.SelectedIndex = 6; occlusionBox.SelectedIndex = 0;
+
+ var toml = ReadToml(TomlPath());
+ string Str(string key) => toml.TryGetValue(key, out var v) ? v.Trim('"') : "";
+ bool? Bool(string key) => toml.TryGetValue(key, out var v) ? v == "true" : null;
+ double? Num(string key) => toml.TryGetValue(key, out var v) && double.TryParse(v.Trim('"'), NumberStyles.Float, CultureInfo.InvariantCulture, out double d) ? d : null;
+
+ string effect = Str("present_effect"), mode = Str("modo_fsr");
+ int scale = Array.FindIndex(DeckScaling, s => s.Effect == effect && (effect != "fsr" || s.Mode == mode));
+ if (scale >= 0) scalingBox.SelectedIndex = scale;
+ if (Bool("proporcion_de_la_pantalla") is { } aspect) aspectBox.SelectedIndex = aspect ? 0 : 1;
+ if (Num("ritmo_contra_pantalla_hz") is { } hz) { int i = Array.FindIndex(DeckFpsLimits, f => Math.Abs(f.Hz - hz) < 0.5); if (i >= 0) fpsLimitBox.SelectedIndex = i; }
+ if (Num("anisotropic_override") is { } an) { int i = Array.FindIndex(DeckAniso, a => a.Value == (int)an); if (i >= 0) anisoBox.SelectedIndex = i; }
+ string ao = Str("modo_oclusion"); { int i = Array.FindIndex(DeckOcclusion, o => o.Value == ao); if (i >= 0) occlusionBox.SelectedIndex = i; }
+ if (Bool("sincronia_vertical") is { } vs) vsyncBox.Checked = vs;
+ if (Bool("multimuestreo_del_juego") is { } ms) msaaBox.Checked = ms;
+ if (Bool("fullscreen") is { } fs) displayModeBox.SelectedIndex = fs ? 0 : 1;
+ int post = Str("swap_post_effect") switch { "none" => 0, "fxaa" => 1, "fxaa_extreme" => 2, _ => -1 };
+ if (post >= 0) postEffectBox.SelectedIndex = post;
+ string res = Str("resolucion_interna");
+ if (int.TryParse(res, out int ri) && ri >= 1 && ri <= internalResolutionBox.Items.Count) internalResolutionBox.SelectedIndex = ri - 1;
+ if (Num("window_width") is { } ww && Num("window_height") is { } wh)
+ {
+ int i = resolutionBox.Items.IndexOf($"{(int)ww}x{(int)wh}");
+ if (i >= 0) resolutionBox.SelectedIndex = i;
+ }
+ }
+
+ private string TomlPath() => Path.Combine(ExeDirectory(), "fifastreet.toml");
+
+ private void ApplyDeckLaunch(ProcessStartInfo startInfo, string exeDirectory, string graphicsApi, int adapter)
+ {
+ // The deck port's own start-up switches (native renderer, its shader folders...), as its launcher sets them.
+ foreach (string line in File.ReadAllLines(Path.Combine(exeDirectory, "ajustes-del-port.txt")))
+ {
+ int eq = line.IndexOf('=');
+ if (eq <= 0 || line.StartsWith('?') || line.StartsWith('#')) continue;
+ startInfo.Environment[line[..eq].Trim()] = line[(eq + 1)..].Trim();
+ }
+ startInfo.Environment["REX_GPU_BACKEND"] = graphicsApi == "Vulkan" ? "vulkan" : "d3d12";
+ if (graphicsApi == "Vulkan") startInfo.Environment["REX_VULKAN_DEVICE"] = "-1";
+ else if (adapter >= 0) startInfo.Environment["REX_D3D12_ADAPTER"] = adapter.ToString(CultureInfo.InvariantCulture);
+
+ SaveDeckToml();
+ }
+
+ // The launcher's current choices into fifastreet.toml (on every change, and before each start).
+ private void SaveDeckToml()
+ {
+ if (!deckBase) return;
+ var size = resolutionBox.Text.Split('x');
+ var scaling = DeckScaling[Math.Max(0, scalingBox.SelectedIndex)];
+ var values = new Dictionary<string, string>
+ {
+ ["fullscreen"] = displayModeBox.SelectedIndex == 0 ? "true" : "false",
+ ["gpu_backend"] = graphicsApiBox.SelectedIndex == 1 ? "\"vulkan\"" : "\"d3d12\"",
+ ["resolucion_interna"] = "\"" + Math.Max(1, internalResolutionBox.SelectedIndex + 1).ToString(CultureInfo.InvariantCulture) + "\"",
+ ["present_effect"] = "\"" + scaling.Effect + "\"",
+ ["modo_fsr"] = "\"" + scaling.Mode + "\"",
+ ["proporcion_de_la_pantalla"] = aspectBox.SelectedIndex == 1 ? "false" : "true",
+ ["ritmo_contra_pantalla_hz"] = DeckFpsLimits[Math.Max(0, fpsLimitBox.SelectedIndex)].Hz.ToString("0.000000", CultureInfo.InvariantCulture),
+ ["sincronia_vertical"] = vsyncBox.Checked ? "true" : "false",
+ ["anisotropic_override"] = DeckAniso[Math.Max(0, anisoBox.SelectedIndex)].Value.ToString(CultureInfo.InvariantCulture),
+ ["swap_post_effect"] = "\"" + (postEffectBox.SelectedIndex switch { 1 => "fxaa", 2 => "fxaa_extreme", _ => "none" }) + "\"",
+ ["multimuestreo_del_juego"] = msaaBox.Checked ? "true" : "false",
+ ["modo_oclusion"] = "\"" + DeckOcclusion[Math.Max(0, occlusionBox.SelectedIndex)].Value + "\"",
+ };
+ if (size.Length == 2 && int.TryParse(size[0], out int w) && int.TryParse(size[1], out int h) && w > 0 && h > 0)
+ {
+ // A window larger than its monitor shows only part of the game: in a window, take the largest usual 16:9 size
+ // that fits the work area with its title bar.
+ var screens = Screen.AllScreens;
+ var area = screens[Math.Clamp(monitorBox.SelectedIndex, 0, screens.Length - 1)].WorkingArea;
+ if (displayModeBox.SelectedIndex != 0 && (w > area.Width - 16 || h > area.Height - 48))
+ {
+ (w, h) = new[] { (3840, 2160), (2560, 1440), (1920, 1080), (1600, 900), (1280, 720) }
+ .FirstOrDefault(s => s.Item1 <= area.Width - 16 && s.Item2 <= area.Height - 48, (1280, 720));
+ int shown = resolutionBox.Items.IndexOf($"{w}x{h}"); // the launcher shows the size the game gets
+ if (shown >= 0) resolutionBox.SelectedIndex = shown;
+ }
+ values["window_width"] = w.ToString(CultureInfo.InvariantCulture);
+ values["window_height"] = h.ToString(CultureInfo.InvariantCulture);
+ }
+ try { WriteToml(TomlPath(), values); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+ }
+
+ // fifastreet.toml as the runtime writes it: "key = value" lines, plus comments and [sections] that are kept as they are.
+ private static Dictionary<string, string> ReadToml(string path)
+ {
+ var map = new Dictionary<string, string>(StringComparer.Ordinal);
+ try
+ {
+ if (!File.Exists(path)) return map;
+ foreach (string line in File.ReadAllLines(path))
+ {
+ int eq = line.IndexOf('=');
+ if (eq <= 0 || line.TrimStart().StartsWith('#') || line.TrimStart().StartsWith('[')) continue;
+ map[line[..eq].Trim()] = line[(eq + 1)..].Trim();
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+ return map;
+ }
+
+ private static void WriteToml(string path, IReadOnlyDictionary<string, string> values)
+ {
+ var lines = File.Exists(path) ? File.ReadAllLines(path).ToList() : new List<string> { "# Auto-generated cvar configuration" };
+ var left = new HashSet<string>(values.Keys);
+ for (int i = 0; i < lines.Count; i++)
+ {
+ int eq = lines[i].IndexOf('=');
+ if (eq <= 0 || lines[i].TrimStart().StartsWith('#')) continue;
+ string key = lines[i][..eq].Trim();
+ if (!values.TryGetValue(key, out var v)) continue;
+ lines[i] = key + " = " + v;
+ left.Remove(key);
+ }
+ // New keys go before the first [section], where the runtime keeps the plain ones.
+ int at = lines.FindIndex(l => l.TrimStart().StartsWith('['));
+ if (at < 0) at = lines.Count;
+ lines.InsertRange(at, left.Select(k => k + " = " + values[k]));
+ File.WriteAllLines(path, lines, new UTF8Encoding(false));
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/DiscordPresence.cs b/Launcher/FifaStreetLauncher/DiscordPresence.cs
new file mode 100644
index 0000000..ab54aa3
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/DiscordPresence.cs
@@ -0,0 +1,381 @@
+using System;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.IO;
+using System.IO.Pipes;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace FifaStreetLauncher;
+
+/// <summary>
+/// What the Discord card shows. Every field is optional; the ones left null are
+/// omitted from the payload, which is what Discord expects.
+/// </summary>
+public sealed class DiscordActivity
+{
+ /// <summary>First line under the application name.</summary>
+ public string? Details { get; set; }
+
+ /// <summary>Second line, used here for the renderer and video mode.</summary>
+ public string? State { get; set; }
+
+ /// <summary>When the session started; Discord counts up from it.</summary>
+ public DateTimeOffset? Start { get; set; }
+
+ /// <summary>Art asset key uploaded in the Discord developer portal.</summary>
+ public string? LargeImage { get; set; }
+ public string? LargeText { get; set; }
+ public string? SmallImage { get; set; }
+ public string? SmallText { get; set; }
+
+ /// <summary>At most two; Discord drops the rest.</summary>
+ public List<DiscordButton>? Buttons { get; set; }
+
+ public bool SameAs(DiscordActivity? other) =>
+ other is not null &&
+ Details == other.Details && State == other.State &&
+ Start == other.Start &&
+ LargeImage == other.LargeImage && LargeText == other.LargeText &&
+ SmallImage == other.SmallImage && SmallText == other.SmallText;
+}
+
+public sealed class DiscordButton
+{
+ public string Label { get; set; } = "";
+ public string Url { get; set; } = "";
+}
+
+/// <summary>
+/// Minimal Discord Rich Presence client: it speaks the local IPC protocol over
+/// the named pipe Discord opens on the same PC, so it needs no NuGet package and
+/// no network access of its own.
+///
+/// Everything here is best-effort. If Discord is not installed, not running, or
+/// closes mid-game, the client keeps quiet and retries in the background. It
+/// never throws into the launcher and never blocks the game from starting.
+/// </summary>
+public sealed class DiscordPresence : IDisposable
+{
+ private const int OpHandshake = 0;
+ private const int OpFrame = 1;
+ private const int OpClose = 2;
+ private const int OpPing = 3;
+ private const int OpPong = 4;
+
+ // Discord allows 5 presence updates per 20 seconds. One per 15 is well inside it.
+ private static readonly TimeSpan MinUpdateInterval = TimeSpan.FromSeconds(15);
+ private static readonly TimeSpan ReconnectInterval = TimeSpan.FromSeconds(10);
+
+ private readonly string clientId;
+ private readonly int gamePid;
+ private readonly CancellationTokenSource cancel = new();
+ private readonly SemaphoreSlim writeGate = new(1, 1);
+
+ private NamedPipeClientStream? pipe;
+ private Task? worker;
+ private Task? reader;
+
+ private DiscordActivity? wanted; // what we would like Discord to show
+ private DiscordActivity? shown; // what Discord has been told
+ private DateTime lastSend = DateTime.MinValue;
+ private DateTime lastConnectAttempt = DateTime.MinValue;
+ private int disposed;
+
+ public DiscordPresence(string clientId, int gamePid)
+ {
+ this.clientId = clientId;
+ this.gamePid = gamePid;
+ }
+
+ /// <summary>True once the handshake has gone through.</summary>
+ public bool Connected => pipe is { IsConnected: true };
+
+ /// <summary>Set or replace the activity. Safe to call from the UI thread.</summary>
+ public void Set(DiscordActivity activity)
+ {
+ Volatile.Write(ref wanted, activity);
+ if (worker is null && Volatile.Read(ref disposed) == 0)
+ worker = Task.Run(() => WorkerAsync(cancel.Token));
+ }
+
+ private async Task WorkerAsync(CancellationToken token)
+ {
+ try
+ {
+ while (!token.IsCancellationRequested)
+ {
+ if (!Connected)
+ {
+ if (DateTime.UtcNow - lastConnectAttempt >= ReconnectInterval)
+ {
+ lastConnectAttempt = DateTime.UtcNow;
+ if (await TryConnectAsync(token).ConfigureAwait(false))
+ {
+ // A fresh connection knows nothing, so resend.
+ shown = null;
+ lastSend = DateTime.MinValue;
+ }
+ }
+ }
+ else
+ {
+ var target = Volatile.Read(ref wanted);
+ if (target is not null && !target.SameAs(shown) &&
+ DateTime.UtcNow - lastSend >= MinUpdateInterval)
+ {
+ if (await TrySendActivityAsync(target, token).ConfigureAwait(false))
+ {
+ shown = target;
+ lastSend = DateTime.UtcNow;
+ }
+ else
+ {
+ Drop();
+ }
+ }
+ }
+
+ await Task.Delay(1000, token).ConfigureAwait(false);
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // Shutting down.
+ }
+ catch
+ {
+ // Presence is cosmetic; never surface a failure.
+ }
+ }
+
+ private async Task<bool> TryConnectAsync(CancellationToken token)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ NamedPipeClientStream? candidate = null;
+ try
+ {
+ candidate = new NamedPipeClientStream(
+ ".", "discord-ipc-" + i, PipeDirection.InOut, PipeOptions.Asynchronous);
+
+ await candidate.ConnectAsync(500, token).ConfigureAwait(false);
+
+ pipe = candidate;
+ candidate = null;
+
+ var handshake = JsonSerializer.Serialize(new Dictionary<string, object?>
+ {
+ ["v"] = 1,
+ ["client_id"] = clientId
+ });
+
+ if (!await WriteFrameAsync(OpHandshake, handshake, token).ConfigureAwait(false))
+ {
+ Drop();
+ continue;
+ }
+
+ reader = Task.Run(() => ReadLoopAsync(pipe!, token));
+ return true;
+ }
+ catch (OperationCanceledException) when (token.IsCancellationRequested)
+ {
+ candidate?.Dispose();
+ throw;
+ }
+ catch
+ {
+ // That slot is not Discord, or Discord is busy. Try the next one.
+ candidate?.Dispose();
+ Drop();
+ }
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// Every command gets a reply frame, and Discord sends the occasional PING.
+ /// Without draining them the pipe buffer eventually fills and our writes
+ /// would block, so one task reads and discards continuously.
+ /// </summary>
+ private async Task ReadLoopAsync(NamedPipeClientStream stream, CancellationToken token)
+ {
+ var header = new byte[8];
+ try
+ {
+ while (!token.IsCancellationRequested && stream.IsConnected)
+ {
+ if (!await ReadExactAsync(stream, header, 8, token).ConfigureAwait(false))
+ break;
+
+ int op = BinaryPrimitives.ReadInt32LittleEndian(header.AsSpan(0, 4));
+ int length = BinaryPrimitives.ReadInt32LittleEndian(header.AsSpan(4, 4));
+ if (length < 0 || length > 1 << 20) break;
+
+ var body = length > 0 ? new byte[length] : Array.Empty<byte>();
+ if (length > 0 && !await ReadExactAsync(stream, body, length, token).ConfigureAwait(false))
+ break;
+
+ if (op == OpPing)
+ {
+ await WriteFrameAsync(OpPong, Encoding.UTF8.GetString(body), token).ConfigureAwait(false);
+ }
+ else if (op == OpClose)
+ {
+ break;
+ }
+ // Everything else (READY, command replies, events) is of no use here.
+ }
+ }
+ catch
+ {
+ // Fall through: the worker notices the pipe is gone and reconnects.
+ }
+ finally
+ {
+ if (ReferenceEquals(stream, pipe) && Volatile.Read(ref disposed) == 0) Drop();
+ }
+ }
+
+ private static async Task<bool> ReadExactAsync(
+ Stream stream, byte[] buffer, int count, CancellationToken token)
+ {
+ int read = 0;
+ while (read < count)
+ {
+ int got = await stream.ReadAsync(buffer.AsMemory(read, count - read), token).ConfigureAwait(false);
+ if (got <= 0) return false;
+ read += got;
+ }
+ return true;
+ }
+
+ private async Task<bool> TrySendActivityAsync(DiscordActivity? activity, CancellationToken token)
+ {
+ var args = new Dictionary<string, object?>
+ {
+ ["pid"] = gamePid,
+ ["activity"] = activity is null ? null : BuildActivity(activity)
+ };
+
+ var command = new Dictionary<string, object?>
+ {
+ ["cmd"] = "SET_ACTIVITY",
+ ["nonce"] = Guid.NewGuid().ToString(),
+ ["args"] = args
+ };
+
+ return await WriteFrameAsync(OpFrame, JsonSerializer.Serialize(command), token).ConfigureAwait(false);
+ }
+
+ private static Dictionary<string, object?> BuildActivity(DiscordActivity a)
+ {
+ var payload = new Dictionary<string, object?> { ["instance"] = false };
+
+ if (!string.IsNullOrWhiteSpace(a.Details)) payload["details"] = Trim(a.Details!, 128);
+ if (!string.IsNullOrWhiteSpace(a.State)) payload["state"] = Trim(a.State!, 128);
+
+ if (a.Start is { } start)
+ {
+ payload["timestamps"] = new Dictionary<string, object?>
+ {
+ ["start"] = start.ToUnixTimeSeconds()
+ };
+ }
+
+ var assets = new Dictionary<string, object?>();
+ if (!string.IsNullOrWhiteSpace(a.LargeImage)) assets["large_image"] = a.LargeImage;
+ if (!string.IsNullOrWhiteSpace(a.LargeText)) assets["large_text"] = Trim(a.LargeText!, 128);
+ if (!string.IsNullOrWhiteSpace(a.SmallImage)) assets["small_image"] = a.SmallImage;
+ if (!string.IsNullOrWhiteSpace(a.SmallText)) assets["small_text"] = Trim(a.SmallText!, 128);
+ if (assets.Count > 0) payload["assets"] = assets;
+
+ if (a.Buttons is { Count: > 0 })
+ {
+ var buttons = new List<Dictionary<string, object?>>();
+ foreach (var b in a.Buttons)
+ {
+ if (string.IsNullOrWhiteSpace(b.Label) || string.IsNullOrWhiteSpace(b.Url)) continue;
+ buttons.Add(new Dictionary<string, object?>
+ {
+ ["label"] = Trim(b.Label, 32),
+ ["url"] = b.Url
+ });
+ if (buttons.Count == 2) break;
+ }
+ if (buttons.Count > 0) payload["buttons"] = buttons;
+ }
+
+ return payload;
+ }
+
+ private static string Trim(string text, int max) =>
+ text.Length <= max ? text : text.Substring(0, max);
+
+ private async Task<bool> WriteFrameAsync(int op, string json, CancellationToken token)
+ {
+ var stream = pipe;
+ if (stream is null || !stream.IsConnected) return false;
+
+ var payload = Encoding.UTF8.GetBytes(json);
+ var frame = new byte[8 + payload.Length];
+ BinaryPrimitives.WriteInt32LittleEndian(frame.AsSpan(0, 4), op);
+ BinaryPrimitives.WriteInt32LittleEndian(frame.AsSpan(4, 4), payload.Length);
+ payload.CopyTo(frame, 8);
+
+ await writeGate.WaitAsync(token).ConfigureAwait(false);
+ try
+ {
+ await stream.WriteAsync(frame.AsMemory(0, frame.Length), token).ConfigureAwait(false);
+ await stream.FlushAsync(token).ConfigureAwait(false);
+ return true;
+ }
+ catch (OperationCanceledException) when (token.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch
+ {
+ return false;
+ }
+ finally
+ {
+ writeGate.Release();
+ }
+ }
+
+ private void Drop()
+ {
+ var stream = pipe;
+ pipe = null;
+ shown = null;
+ try { stream?.Dispose(); } catch { }
+ }
+
+ /// <summary>
+ /// Clears the card and closes the pipe. Discord also clears the activity by
+ /// itself when the pipe drops, so this is a courtesy with a short budget.
+ /// </summary>
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref disposed, 1) != 0) return;
+
+ try
+ {
+ if (Connected)
+ {
+ using var quick = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
+ TrySendActivityAsync(null, quick.Token).GetAwaiter().GetResult();
+ }
+ }
+ catch { }
+
+ try { cancel.Cancel(); } catch { }
+ Drop();
+ try { cancel.Dispose(); } catch { }
+ try { writeGate.Dispose(); } catch { }
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/FifaStreetLauncher.csproj b/Launcher/FifaStreetLauncher/FifaStreetLauncher.csproj
index 3ef4564..180dacc 100644
--- a/Launcher/FifaStreetLauncher/FifaStreetLauncher.csproj
+++ b/Launcher/FifaStreetLauncher/FifaStreetLauncher.csproj
@@ -1,19 +1,21 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <OutputType>WinExe</OutputType>
- <TargetFramework>net8.0-windows</TargetFramework>
- <Nullable>enable</Nullable>
- <UseWindowsForms>true</UseWindowsForms>
- <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
- <Version>1.3.0</Version>
- <ApplicationIcon>fifastreet.ico</ApplicationIcon>
- <ImplicitUsings>enable</ImplicitUsings>
- </PropertyGroup>
- <ItemGroup>
- <EmbeddedResource Include="cover.jpg" LogicalName="cover.jpg" />
- <EmbeddedResource Include="fifastreet.ico" LogicalName="fifastreet.ico" />
- <Compile Include="..\..\Installer\FifaStreetSetupTool\ThemeKit.cs" Link="ThemeKit.cs" />
- </ItemGroup>
-
-</Project>
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>WinExe</OutputType>
+ <TargetFramework>net8.0-windows</TargetFramework>
+ <Nullable>enable</Nullable>
+ <UseWindowsForms>true</UseWindowsForms>
+ <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
+ <Version>2.0.3</Version>
+ <ApplicationIcon>fifastreet.ico</ApplicationIcon>
+ <ImplicitUsings>enable</ImplicitUsings>
+ </PropertyGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="cover.jpg" LogicalName="cover.jpg" />
+ <EmbeddedResource Include="fifastreet.ico" LogicalName="fifastreet.ico" />
+ <Compile Include="..\..\Installer\FifaStreetSetupTool\ThemeKit.cs" Link="ThemeKit.cs" />
+ <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
+ <None Include="ui\**" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
+ </ItemGroup>
+
+</Project>
diff --git a/Launcher/FifaStreetLauncher/FriendsForm.cs b/Launcher/FifaStreetLauncher/FriendsForm.cs
new file mode 100644
index 0000000..48f8be5
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/FriendsForm.cs
@@ -0,0 +1,509 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Net.Http;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+using ReStreet.Ui;
+
+namespace FifaStreetLauncher;
+
+// One row of the people list.
+internal enum PersonKind { Header, Request, Friend, Online, Pending }
+
+internal sealed record PersonRow(PersonKind Kind, string Name, bool IsOnline = false);
+
+// The people list is drawn by hand so it matches the rest of the launcher.
+internal sealed class PeopleList : Control
+{
+ const int RowH = 44, HeaderH = 32;
+ readonly List<PersonRow> rows = new();
+ int scroll, hover = -1;
+
+ public event Action<string, string>? ActionClicked; // action, name
+ public string EmptyText { get; set; } = "";
+
+ public PeopleList()
+ {
+ SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
+ BackColor = StreetTheme.Field;
+ }
+
+ public void SetRows(IEnumerable<PersonRow> items)
+ {
+ rows.Clear();
+ rows.AddRange(items);
+ ClampScroll();
+ Invalidate();
+ }
+
+ float K => StreetTheme.K(this);
+ int RowHeight(PersonRow row) => (int)((row.Kind == PersonKind.Header ? HeaderH : RowH) * K);
+ int TotalHeight() { int sum = 0; foreach (var row in rows) sum += RowHeight(row); return sum; }
+
+ void ClampScroll() => scroll = Math.Max(0, Math.Min(scroll, Math.Max(0, TotalHeight() - Height)));
+
+ protected override void OnMouseWheel(MouseEventArgs e)
+ {
+ scroll -= Math.Sign(e.Delta) * (int)(RowH * K);
+ ClampScroll();
+ Invalidate();
+ }
+
+ // Rectangles of the action words on a row, right to left.
+ IEnumerable<(string Action, string Text, Rectangle Rect, bool Primary)> Actions(PersonRow row, Rectangle bounds)
+ {
+ using var font = new Font("Segoe UI", 12.67f * K, GraphicsUnit.Pixel);
+ int right = bounds.Right - (int)(14 * K);
+ (string, string, bool)[] items = row.Kind switch
+ {
+ PersonKind.Request => new[] { ("decline", "Decline", false), ("accept", "Accept", true) },
+ PersonKind.Friend => new[] { ("remove", "Remove", false) },
+ PersonKind.Online => new[] { ("add", "Add friend", true) },
+ PersonKind.Pending => new[] { ("remove", "Cancel", false) },
+ _ => Array.Empty<(string, string, bool)>()
+ };
+ foreach (var (action, text, primary) in items)
+ {
+ int width = TextRenderer.MeasureText(text, font, Size.Empty, TextFormatFlags.NoPadding).Width + (int)(16 * K);
+ var rect = new Rectangle(right - width, bounds.Y + (int)(8 * K), width, bounds.Height - (int)(16 * K));
+ yield return (action, text, rect, primary);
+ right = rect.X - (int)(6 * K);
+ }
+ }
+
+ (int Index, Rectangle Bounds) RowAt(Point point)
+ {
+ int y = -scroll;
+ for (int i = 0; i < rows.Count; i++)
+ {
+ int h = RowHeight(rows[i]);
+ if (point.Y >= y && point.Y < y + h) return (i, new Rectangle(0, y, Width, h));
+ y += h;
+ }
+ return (-1, Rectangle.Empty);
+ }
+
+ protected override void OnMouseMove(MouseEventArgs e)
+ {
+ var (index, bounds) = RowAt(e.Location);
+ bool overAction = false;
+ if (index >= 0)
+ foreach (var action in Actions(rows[index], bounds))
+ if (action.Rect.Contains(e.Location)) overAction = true;
+ Cursor = overAction ? Cursors.Hand : Cursors.Default;
+ if (index != hover) { hover = index; Invalidate(); }
+ }
+
+ protected override void OnMouseLeave(EventArgs e) { hover = -1; Invalidate(); }
+
+ protected override void OnMouseClick(MouseEventArgs e)
+ {
+ var (index, bounds) = RowAt(e.Location);
+ if (index < 0) return;
+ foreach (var action in Actions(rows[index], bounds))
+ if (action.Rect.Contains(e.Location)) { ActionClicked?.Invoke(action.Action, rows[index].Name); return; }
+ }
+
+ protected override void OnPaintBackground(PaintEventArgs e) { }
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ var g = e.Graphics;
+ StreetTheme.PaintBehind(this, g);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ float k = K;
+ var frame = new RectangleF(0.5f, 0.5f, Width - 1, Height - 1);
+ using var path = StreetTheme.Round(frame, 8 * k);
+ using (var fill = new SolidBrush(StreetTheme.Field)) g.FillPath(fill, path);
+ var state = g.Save();
+ g.SetClip(path, CombineMode.Intersect);
+
+ using var nameFont = new Font("Segoe UI", 14f * k, GraphicsUnit.Pixel);
+ using var headerFont = new Font(StreetTheme.CondensedFamily, 11 * k, FontStyle.Bold, GraphicsUnit.Pixel);
+ using var actionFont = new Font("Segoe UI", 12.67f * k, GraphicsUnit.Pixel);
+
+ if (rows.Count == 0)
+ TextRenderer.DrawText(g, EmptyText, nameFont, new Rectangle((int)(16 * k), (int)(14 * k), Width - (int)(32 * k), Height), StreetTheme.Muted,
+ TextFormatFlags.WordBreak | TextFormatFlags.NoPadding);
+
+ int y = -scroll;
+ for (int i = 0; i < rows.Count; i++)
+ {
+ var row = rows[i];
+ int h = RowHeight(row);
+ var bounds = new Rectangle(0, y, Width, h);
+ y += h;
+ if (bounds.Bottom < 0 || bounds.Top > Height) continue;
+
+ if (row.Kind == PersonKind.Header)
+ {
+ using var yellow = new SolidBrush(StreetTheme.Yellow);
+ StreetTheme.DrawSpaced(g, row.Name, headerFont, yellow, new PointF(16 * k, bounds.Y + 12 * k), 2.2f * k);
+ continue;
+ }
+
+ if (i == hover)
+ using (var lit = new SolidBrush(Color.FromArgb(18, 255, 255, 255))) g.FillRectangle(lit, bounds);
+
+ float dot = 10 * k;
+ var dotRect = new RectangleF(16 * k, bounds.Y + (h - dot) / 2, dot, dot);
+ bool lit2 = row.Kind == PersonKind.Online || row.IsOnline;
+ using (var dotBrush = new SolidBrush(lit2 ? Color.FromArgb(86, 214, 120) : Color.FromArgb(96, 100, 104)))
+ g.FillEllipse(dotBrush, dotRect);
+
+ string suffix = row.Kind == PersonKind.Pending ? " · request sent" : "";
+ TextRenderer.DrawText(g, row.Name + suffix, nameFont, new Rectangle((int)(36 * k), bounds.Y, Width - (int)(220 * k), h),
+ row.Kind == PersonKind.Pending || (row.Kind == PersonKind.Friend && !row.IsOnline) ? StreetTheme.Muted : StreetTheme.Ink,
+ TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
+
+ foreach (var action in Actions(row, bounds))
+ {
+ var rect = action.Rect;
+ using var chip = StreetTheme.Round(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height), 6 * k);
+ using (var back = new SolidBrush(action.Primary ? StreetTheme.Yellow : Color.FromArgb(34, 255, 255, 255))) g.FillPath(back, chip);
+ TextRenderer.DrawText(g, action.Text, actionFont, rect, action.Primary ? StreetTheme.YellowDark : StreetTheme.Ink,
+ TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding);
+ }
+ }
+ g.Restore(state);
+ using var edge = new Pen(Color.FromArgb(60, 255, 255, 255));
+ g.DrawPath(edge, path);
+ }
+}
+
+// Friends, requests and who is online. Same frame, fonts and colours as the setup and the online patch.
+internal sealed class FriendsForm : Form, ISceneHost, IUiScaled
+{
+ readonly UiScaler scaler;
+ public float UiScale => scaler.Scale;
+
+ const float DesignHeight = 610f;
+ new const int Left = 48;
+ const int SheetX = 480, SheetY = 32, SheetW = 422, SheetH = 546, Pad = 24;
+ const int ContentX = SheetX + Pad, ContentW = SheetW - 2 * Pad;
+
+ static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(5) };
+
+ readonly string server, me, key;
+ readonly TextBox addBox = new();
+ readonly SlantButton addButton = new();
+ readonly SlantButton copyButton = new();
+ readonly SlantButton closeButton = new();
+ readonly PeopleList list = new();
+ readonly ThemedLabel meLabel = new();
+ readonly ThemedLabel connection = new();
+ readonly ThemedLabel message = new();
+ readonly System.Windows.Forms.Timer poll = new() { Interval = 4000 };
+
+ Bitmap? scene;
+ Size sceneSize;
+ bool busy;
+ int pingMs = -1;
+ string lastError = "";
+ JsonElement? lastSnapshot;
+
+ public Bitmap SceneBitmap { get { BuildScene(); return scene!; } }
+
+ internal FriendsForm(string server, string me, string key)
+ {
+ this.server = server;
+ this.me = me;
+ this.key = key;
+ Text = "ReStreet - Friends";
+ using (var icon = typeof(FriendsForm).Assembly.GetManifestResourceStream("fifastreet.ico")!)
+ Icon = new Icon(icon);
+ ClientSize = new Size(930, 610);
+ scaler = new UiScaler(this, 930, 610);
+ StartPosition = FormStartPosition.CenterParent;
+ FormBorderStyle = FormBorderStyle.FixedSingle;
+ MaximizeBox = false;
+ MinimizeBox = false;
+ DoubleBuffered = true;
+ ResizeRedraw = true;
+ BackColor = StreetTheme.Asphalt;
+ ForeColor = StreetTheme.Ink;
+ Font = StreetTheme.Body(10);
+ HandleCreated += (_, _) => StreetTheme.ApplyDarkTitleBar(Handle);
+
+ meLabel.SetBounds(Left, 264, 384, 28);
+ meLabel.Font = StreetTheme.Body(13f, FontStyle.Bold);
+ meLabel.ForeColor = StreetTheme.Ink;
+ meLabel.Text = "Playing as " + me;
+ Controls.Add(meLabel);
+ connection.SetBounds(Left, 296, 384, 24);
+ connection.Font = StreetTheme.Body(10);
+ connection.ForeColor = StreetTheme.Muted;
+ connection.Text = "Connecting…";
+ Controls.Add(connection);
+ Controls.Add(new ThemedLabel
+ {
+ Text = "Add a friend by name, or pick someone who is online. To invite a friend to a match, open the friends menu inside the game.",
+ Bounds = new Rectangle(Left, 336, 384, 80),
+ Font = StreetTheme.Body(10),
+ ForeColor = StreetTheme.Muted
+ });
+
+ Controls.Add(new ThemedLabel
+ {
+ Text = "Friends", Bounds = new Rectangle(ContentX, SheetY + Pad, ContentW, 32),
+ Font = StreetTheme.Condensed(20f, FontStyle.Bold), ForeColor = StreetTheme.Ink
+ });
+
+ const int addW = 96, gap = 8;
+ addBox.Font = StreetTheme.Body(10);
+ addBox.MaxLength = 16;
+ addBox.PlaceholderText = "Friend's online name";
+ addBox.AccessibleName = "Friend's online name";
+ Controls.Add(new FieldFrame(addBox) { Bounds = new Rectangle(ContentX, 96, ContentW - addW - gap, 40) });
+ addButton.Kind = SlantKind.Glass;
+ addButton.Text = "Add";
+ addButton.Font = StreetTheme.Body(10);
+ addButton.Bounds = new Rectangle(ContentX + ContentW - addW, 96, addW, 40);
+ addButton.Click += async (_, _) => await AddTyped();
+ AcceptButton = addButton;
+ Controls.Add(addButton);
+
+ message.SetBounds(ContentX, 144, ContentW, 20);
+ message.Font = StreetTheme.Body(9f);
+ message.ForeColor = StreetTheme.Muted;
+ Controls.Add(message);
+
+ list.Bounds = new Rectangle(ContentX, 172, ContentW, 304);
+ list.EmptyText = "Nobody here yet. Add a friend by name, or wait for other players to come online.";
+ list.ActionClicked += async (action, name) => await Act(action, name);
+ Controls.Add(list);
+
+ copyButton.Kind = SlantKind.Text;
+ copyButton.Align = StringAlignment.Near;
+ copyButton.Text = "Copy connection report";
+ copyButton.Font = StreetTheme.Body(10);
+ copyButton.Bounds = new Rectangle(ContentX, 522, 210, 32);
+ copyButton.Click += async (_, _) => await CopyReport();
+ Controls.Add(copyButton);
+ closeButton.Kind = SlantKind.Text;
+ closeButton.Align = StringAlignment.Far;
+ closeButton.Text = "Close";
+ closeButton.Font = StreetTheme.Body(10);
+ closeButton.Bounds = new Rectangle(ContentX + ContentW - 150, 522, 150, 32);
+ closeButton.Click += (_, _) => Close();
+ Controls.Add(closeButton);
+ CancelButton = closeButton;
+
+ poll.Tick += async (_, _) => await Refresh();
+ Shown += async (_, _) => { poll.Start(); await Refresh(); };
+ FormClosed += (_, _) => poll.Dispose();
+ scaler.Capture();
+ }
+
+ protected override void OnPaintBackground(PaintEventArgs e)
+ {
+ BuildScene();
+ using (var floor = new SolidBrush(StreetTheme.Asphalt)) e.Graphics.FillRectangle(floor, ClientRectangle);
+ e.Graphics.DrawImageUnscaled(scene!, 0, 0);
+ }
+
+ void BuildScene()
+ {
+ float s = ClientSize.Width / (float)StreetTheme.DesignWidth;
+ var size = new Size(ClientSize.Width, (int)Math.Ceiling(DesignHeight * s));
+ if (scene != null && sceneSize == size) return;
+ scene?.Dispose();
+ sceneSize = size;
+ using var backdrop = StreetTheme.RenderBackdrop(size, StreetTheme.DesignWidth, DesignHeight);
+ using var blurred = StreetTheme.Blur(backdrop, 10);
+ scene = new Bitmap(backdrop);
+ using var g = Graphics.FromImage(scene);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
+ g.ScaleTransform(s, s);
+
+ StreetTheme.DrawGlass(g, blurred, s, new RectangleF(SheetX, SheetY, SheetW, SheetH), 16);
+
+ using (var small = new Font(StreetTheme.CondensedFamily, 16, FontStyle.Bold, GraphicsUnit.Pixel))
+ using (var yellow = new SolidBrush(StreetTheme.Yellow))
+ StreetTheme.DrawSpaced(g, "FIFA STREET 2012 RECOMPILED", small, yellow, new PointF(Left, 56), 3.2f);
+ StreetTheme.DrawWordmark(g, "ReStreet", new PointF(Left, 88), 118, StreetTheme.Ink);
+ var tag = new RectangleF(Left, 192, 236, 32);
+ using (var bar = new SolidBrush(StreetTheme.Yellow)) g.FillPolygon(bar, StreetTheme.Slant(tag, 10));
+ using (var tagFont = new Font(StreetTheme.CondensedFamily, 16, FontStyle.Bold, GraphicsUnit.Pixel))
+ using (var dark = new SolidBrush(StreetTheme.YellowDark))
+ StreetTheme.DrawSpaced(g, "FRIENDS · ONLINE BETA", tagFont, dark, new PointF(Left + 12, 198), 2.6f);
+
+ using var name = new Font("Segoe UI", 15, FontStyle.Regular, GraphicsUnit.Pixel);
+ StreetTheme.DrawLabelValue(g, "Ported by:", "SamuelitoDaVila", name, StreetTheme.Ink, StreetTheme.Ink, Left, 534);
+ StreetTheme.DrawLabelValue(g, "Contributions:", "Emran_Ahm3d", name, StreetTheme.Muted, StreetTheme.Muted, Left, 557);
+ }
+
+ // Sample rows for the --preview-friends screenshot.
+ internal void PreviewRows()
+ {
+ poll.Stop();
+ connection.ForeColor = StreetTheme.Muted;
+ connection.Text = "Connected · 42 ms to the server";
+ list.SetRows(new[]
+ {
+ new PersonRow(PersonKind.Header, "FRIEND REQUESTS"),
+ new PersonRow(PersonKind.Request, "vicente"),
+ new PersonRow(PersonKind.Header, "FRIENDS · 1 ONLINE"),
+ new PersonRow(PersonKind.Friend, "Nelly", true),
+ new PersonRow(PersonKind.Friend, "Baco", false),
+ new PersonRow(PersonKind.Pending, "Darix"),
+ new PersonRow(PersonKind.Header, "ONLINE NOW"),
+ new PersonRow(PersonKind.Online, "Cabura"),
+ });
+ }
+
+ string Url(string path) => "http://" + server + ":29812" + path;
+
+ async Task<JsonElement?> Post(string action, string other)
+ {
+ var body = JsonSerializer.Serialize(new { me, key, action, other, xuid = "0", xsinfo = "" });
+ try
+ {
+ var watch = Stopwatch.StartNew();
+ using var response = await Http.PostAsync(Url("/v1/friends"), new StringContent(body, Encoding.UTF8, "application/json"));
+ string text = await response.Content.ReadAsStringAsync();
+ pingMs = (int)watch.ElapsedMilliseconds;
+ using var doc = JsonDocument.Parse(text);
+ if (!response.IsSuccessStatusCode)
+ {
+ string error = doc.RootElement.TryGetProperty("error", out var e) ? e.GetString() ?? "" : "";
+ lastError = error is "bad_key" or "missing_key"
+ ? "This name belongs to another player. Run the online patch and choose a different name."
+ : "The server refused the request (" + (int)response.StatusCode + ").";
+ return null;
+ }
+ lastError = "";
+ return doc.RootElement.Clone();
+ }
+ catch (Exception error) when (error is HttpRequestException or TaskCanceledException or JsonException)
+ {
+ lastError = "Cannot reach the server. Check your internet connection.";
+ return null;
+ }
+ }
+
+ static IEnumerable<string> Names(JsonElement root, string property)
+ {
+ if (root.TryGetProperty(property, out var array) && array.ValueKind == JsonValueKind.Array)
+ foreach (var item in array.EnumerateArray())
+ if (item.ValueKind == JsonValueKind.String) yield return item.GetString() ?? "";
+ }
+
+ async Task Refresh(string action = "list", string other = "")
+ {
+ if (busy) return;
+ busy = true;
+ try
+ {
+ var snapshot = await Post(action, other);
+ if (snapshot == null)
+ {
+ connection.ForeColor = Color.FromArgb(255, 120, 110);
+ connection.Text = lastError;
+ return;
+ }
+ lastSnapshot = snapshot;
+ var root = snapshot.Value;
+ connection.ForeColor = StreetTheme.Muted;
+ connection.Text = "Connected · " + pingMs + " ms to the server";
+
+ var rows = new List<PersonRow>();
+ var requests = Names(root, "requests").ToList();
+ if (requests.Count > 0)
+ {
+ rows.Add(new PersonRow(PersonKind.Header, "FRIEND REQUESTS"));
+ rows.AddRange(requests.Select(n => new PersonRow(PersonKind.Request, n)));
+ }
+ var friends = new List<(string Name, bool Online)>();
+ if (root.TryGetProperty("friends", out var friendArray) && friendArray.ValueKind == JsonValueKind.Array)
+ foreach (var f in friendArray.EnumerateArray())
+ friends.Add((f.GetProperty("name").GetString() ?? "", f.TryGetProperty("online", out var o) && o.ValueKind == JsonValueKind.True));
+ var pending = Names(root, "pending").ToList();
+ if (friends.Count > 0 || pending.Count > 0)
+ {
+ int online = friends.Count(f => f.Online);
+ rows.Add(new PersonRow(PersonKind.Header, "FRIENDS · " + online + " ONLINE"));
+ rows.AddRange(friends.OrderByDescending(f => f.Online).ThenBy(f => f.Name, StringComparer.OrdinalIgnoreCase)
+ .Select(f => new PersonRow(PersonKind.Friend, f.Name, f.Online)));
+ rows.AddRange(pending.Select(n => new PersonRow(PersonKind.Pending, n)));
+ }
+ var players = Names(root, "players").ToList();
+ if (players.Count > 0)
+ {
+ rows.Add(new PersonRow(PersonKind.Header, "ONLINE NOW"));
+ rows.AddRange(players.Select(n => new PersonRow(PersonKind.Online, n)));
+ }
+ list.SetRows(rows);
+ }
+ finally { busy = false; }
+ }
+
+ async Task Act(string action, string name)
+ {
+ while (busy) await Task.Delay(50);
+ message.ForeColor = StreetTheme.Muted;
+ message.Text = "";
+ await Refresh(action, name);
+ if (lastSnapshot?.TryGetProperty("result", out var result) == true && result.ValueKind == JsonValueKind.String)
+ message.Text = result.GetString() switch
+ {
+ "requested" => "Request sent to " + name + ".",
+ "friends" => "You and " + name + " are now friends.",
+ "already" => name + " is already your friend.",
+ "self" => "That is your own name.",
+ "expired" => "That invite is no longer valid.",
+ "unknown" => "No player called " + name + " has the online patch yet.",
+ _ => ""
+ };
+ }
+
+ async Task AddTyped()
+ {
+ string name = addBox.Text.Trim();
+ if (name.Length < 3) { message.ForeColor = Color.FromArgb(255, 120, 110); message.Text = "Type the friend's online name first."; return; }
+ await Act("add", name);
+ addBox.Clear();
+ }
+
+ async Task CopyReport()
+ {
+ copyButton.Enabled = false;
+ var report = new StringBuilder();
+ report.AppendLine("ReStreet online report");
+ report.AppendLine("Name: " + me);
+ report.AppendLine("Server: " + server);
+ report.AppendLine("Time (UTC): " + DateTime.UtcNow.ToString("u"));
+ report.AppendLine("Windows: " + Environment.OSVersion.VersionString);
+ try
+ {
+ var watch = Stopwatch.StartNew();
+ using var health = await Http.GetAsync(Url("/v1/health"));
+ report.AppendLine("HTTP /v1/health: " + (int)health.StatusCode + " in " + watch.ElapsedMilliseconds + " ms");
+ }
+ catch (Exception error) { report.AppendLine("HTTP /v1/health: failed (" + error.GetType().Name + ")"); }
+ foreach (int port in new[] { 29812, 29813 })
+ {
+ try
+ {
+ var watch = Stopwatch.StartNew();
+ using var client = new TcpClient();
+ using var timeout = new CancellationTokenSource(3000);
+ await client.ConnectAsync(server, port, timeout.Token);
+ report.AppendLine("TCP " + port + ": open in " + watch.ElapsedMilliseconds + " ms");
+ }
+ catch (Exception) { report.AppendLine("TCP " + port + ": blocked or unreachable"); }
+ }
+ report.AppendLine("Friends request: " + (lastError.Length == 0 ? "ok" : lastError));
+ try { Clipboard.SetText(report.ToString()); message.ForeColor = StreetTheme.Muted; message.Text = "Report copied. Paste it in the Discord beta-feedback channel."; }
+ catch (System.Runtime.InteropServices.ExternalException) { message.Text = "Could not copy to the clipboard."; }
+ copyButton.Enabled = true;
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/GlassUi.cs b/Launcher/FifaStreetLauncher/GlassUi.cs
new file mode 100644
index 0000000..42a35d4
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/GlassUi.cs
@@ -0,0 +1,508 @@
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+using System.Net.Sockets;
+using System.Text.Json;
+using Microsoft.Web.WebView2.Core;
+using Microsoft.Web.WebView2.WinForms;
+using ReStreet.Ui;
+
+namespace FifaStreetLauncher;
+
+// Liquid glass interface (ui/launcher.html in a WebView2) on top of the classic launcher form. The classic controls stay
+// alive underneath and keep doing all the work (settings, PLAY, display restore, online, Discord); the page only reads
+// them (state messages) and changes them (set / toggle / command messages). Without the WebView2 runtime the classic
+// interface simply stays visible.
+public partial class LauncherForm
+{
+ // Regions the online patch offers (keep in sync with build_online_patch.py --region).
+ private static readonly (string Name, string Address)[] Regions =
+ {
+ ("Europe", "57.129.180.15"), ("South America", "216.238.113.7"),
+ };
+
+ private WebView2? glass;
+
+ [DllImport("user32.dll")] private static extern bool ReleaseCapture();
+ [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
+ [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int value, int size);
+ [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
+ [DllImport("user32.dll")] private static extern int GetSystemMetricsForDpi(int index, uint dpi);
+
+ private bool glassFrame;
+
+ protected override void WndProc(ref Message m)
+ {
+ // WM_NCCALCSIZE: the client area also takes the caption; the side and bottom sizing borders stay (they are
+ // invisible on Windows 10/11). Maximized, the frame hangs off the screen, so the top keeps one frame width.
+ if (glassFrame && m.Msg == 0x83 && m.WParam != IntPtr.Zero)
+ {
+ int top = Marshal.ReadInt32(m.LParam, 4);
+ base.WndProc(ref m);
+ uint dpi = (uint)DeviceDpi;
+ int frame = WindowState == FormWindowState.Maximized
+ ? GetSystemMetricsForDpi(33 /* SM_CYSIZEFRAME */, dpi) + GetSystemMetricsForDpi(92 /* SM_CXPADDEDBORDER */, dpi) : 0;
+ Marshal.WriteInt32(m.LParam, 4, top + frame);
+ return;
+ }
+ base.WndProc(ref m);
+ }
+ private readonly System.Windows.Forms.Timer glassTimer = new() { Interval = 1000 };
+ private readonly Dictionary<string, (int Ping, int Online)> serverInfo = new();
+ private string lastState = "";
+
+ private Dictionary<string, ComboBox> GlassFields() => new()
+ {
+ ["resolution"] = resolutionBox, ["refresh"] = refreshBox, ["displayMode"] = displayModeBox, ["monitor"] = monitorBox,
+ ["language"] = gameLanguageBox, ["profile"] = profileBox, ["api"] = graphicsApiBox, ["gpu"] = gpuBox,
+ ["post"] = postEffectBox, ["internal"] = internalResolutionBox, ["readback"] = readbackResolveBox,
+ ["scaling"] = scalingBox, ["aspect"] = aspectBox, ["fpsLimit"] = fpsLimitBox, ["aniso"] = anisoBox, ["occlusion"] = occlusionBox,
+ };
+
+ private Dictionary<string, CheckBox> GlassToggles() => new()
+ {
+ ["vsync"] = vsyncBox, ["vrr"] = vrrBox, ["msaa"] = msaaBox, ["memexport"] = readbackMemexportBox,
+ ["memexportFast"] = readbackMemexportFastBox, ["pageState"] = clearMemoryPageStateBox, ["occlusion"] = occlusionQueryBox,
+ ["asyncShaders"] = asyncShadersBox, ["frameStats"] = logFrameStatsBox, ["onlineMode"] = onlineModeBox,
+ };
+
+ // Online on/off (page toggle, saved in settings.json): off starts the game without the online patch, so it plays
+ // offline, and the launcher stops its social, presence and room calls.
+ private readonly CheckBox onlineModeBox = new() { Checked = true };
+
+ // Shows the window: when the new page has loaded, or when the classic interface is the one that stays.
+ private void RevealWindow()
+ {
+ if (!browserActive) Opacity = 1;
+ }
+
+ private async void InitGlassUi()
+ {
+ // Never leave the window invisible: whatever happens below, show it after a few seconds.
+ var safety = new System.Windows.Forms.Timer { Interval = 6000 };
+ safety.Tick += (_, _) => { safety.Stop(); RevealWindow(); };
+ safety.Start();
+ if (Environment.GetEnvironmentVariable("RESTREET_CLASSIC_UI") == "1") return;
+ // Wine/Proton: WebView2 is not reliable there, so the same page opens in the system browser.
+ if (RunningOnWine() || Environment.GetEnvironmentVariable("RESTREET_BROWSER_UI") == "1")
+ {
+ StartBrowserUi();
+ if (browserActive) StartPageServices();
+ RevealWindow();
+ return;
+ }
+ try
+ {
+ string ui = Path.Combine(AppContext.BaseDirectory, "ui");
+ if (!File.Exists(Path.Combine(ui, "launcher.html"))) { RevealWindow(); return; }
+ string data = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ReStreet", "WebView2");
+ var env = await CoreWebView2Environment.CreateAsync(null, data);
+ var view = new WebView2 { Dock = DockStyle.Fill, DefaultBackgroundColor = Color.FromArgb(11, 12, 18) };
+ Controls.Add(view);
+ view.BringToFront();
+ await view.EnsureCoreWebView2Async(env);
+ var core = view.CoreWebView2;
+ core.Settings.AreDevToolsEnabled = false;
+ core.Settings.AreDefaultContextMenusEnabled = false;
+ core.Settings.IsStatusBarEnabled = false;
+ core.Settings.IsZoomControlEnabled = false;
+ core.SetVirtualHostNameToFolderMapping("restreet.ui", ui, CoreWebView2HostResourceAccessKind.DenyCors);
+ // Stadium pictures for the Matches picker: made from the player's own game files on the first PLAY.
+ try
+ {
+ string thumbs = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(exePathBox.Text.Trim()))!, "stadium-thumbs");
+ Directory.CreateDirectory(thumbs);
+ core.SetVirtualHostNameToFolderMapping("restreet.thumbs", thumbs, CoreWebView2HostResourceAccessKind.Allow);
+ }
+ catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException or NotSupportedException)
+ {
+ Debug.WriteLine(ex.Message); // no pictures: the picker shows names only
+ }
+ // The page may only talk to the launcher; it never navigates anywhere else.
+ core.NavigationStarting += (_, e) => { if (!e.Uri.StartsWith("https://restreet.ui/", StringComparison.Ordinal)) e.Cancel = true; };
+ core.NewWindowRequested += (_, e) => e.Handled = true;
+ core.WebMessageReceived += (_, e) => OnGlassMessage(e.WebMessageAsJson);
+ core.NavigationCompleted += (_, _) => RevealWindow();
+ core.Navigate("https://restreet.ui/launcher.html");
+ glass = view;
+ // The page draws its own title bar: a sizable frame without the Windows caption (WM_NCCALCSIZE in WndProc),
+ // so the window resizes from its sides and bottom, snaps and maximizes, with rounded corners and the shadow.
+ // The scaler already gave the window its first size; from now on the user sizes it.
+ scaler.Enabled = false;
+ MinimumSize = MaximumSize = Size.Empty;
+ glassFrame = true;
+ FormBorderStyle = FormBorderStyle.Sizable;
+ MaximizeBox = true;
+ MinimumSize = new Size(Math.Min(Width, LogicalToDeviceUnits(1000)), Math.Min(Height, LogicalToDeviceUnits(620)));
+ SetWindowPos(Handle, IntPtr.Zero, 0, 0, 0, 0, 0x27 /* NOSIZE|NOMOVE|NOZORDER|FRAMECHANGED */);
+ int round = 2; // DWMWCP_ROUND
+ DwmSetWindowAttribute(Handle, 33 /* DWMWA_WINDOW_CORNER_PREFERENCE */, ref round, sizeof(int));
+ StartPageServices();
+ }
+ catch (Exception ex) when (ex is WebView2RuntimeNotFoundException or COMException or IOException or UnauthorizedAccessException)
+ {
+ // No WebView2 runtime (or no writable profile folder): keep the classic interface.
+ if (glass != null) { Controls.Remove(glass); glass.Dispose(); glass = null; }
+ StartBrowserUi();
+ if (browserActive) StartPageServices();
+ RevealWindow();
+ }
+ }
+
+ private bool pageServicesStarted;
+ private void StartPageServices()
+ {
+ if (pageServicesStarted) return;
+ pageServicesStarted = true;
+ glassTimer.Tick += (_, _) => PushGlassState(false);
+ glassTimer.Start();
+ _ = Task.Run(PollServers);
+ }
+
+ private void OnGlassMessage(string json)
+ {
+ using var doc = JsonDocument.Parse(json);
+ var m = doc.RootElement;
+ string cmd = m.TryGetProperty("cmd", out var c) ? c.GetString() ?? "" : "";
+ string id = m.TryGetProperty("id", out var i) ? i.GetString() ?? "" : "";
+ switch (cmd)
+ {
+ case "set":
+ if (GlassFields().TryGetValue(id, out var box) && box.Enabled && m.TryGetProperty("index", out var ix))
+ {
+ int index = ix.GetInt32();
+ if (index >= 0 && index < box.Items.Count) box.SelectedIndex = index;
+ }
+ break;
+ case "toggle":
+ if (GlassToggles().TryGetValue(id, out var t) && t.Enabled && m.TryGetProperty("value", out var v))
+ t.Checked = v.GetBoolean();
+ break;
+ case "play": if (!gameRunning) LaunchGame(); break;
+ case "drag" when browserActive: return;
+ case "minimize" when browserActive: return;
+ case "drag": ReleaseCapture(); SendMessage(Handle, 0xA1 /* WM_NCLBUTTONDOWN */, (IntPtr)2 /* HTCAPTION */, IntPtr.Zero); return;
+ case "minimize": WindowState = FormWindowState.Minimized; return;
+ case "maximize" when browserActive: return;
+ case "maximize": WindowState = WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized; return;
+ case "close": Close(); return;
+ case "browseExe": BrowseExe(); break;
+ case "browseData": BrowseGame(); break;
+ case "logs": OpenLogs(); break;
+ case "folder": OpenGameFolder(); break;
+ case "shortcut": CreateDesktopShortcut(); break;
+ case "state": if (pendingUpdate is { } pu) PostToPage(new { type = "update", version = pu.Version, notes = pu.Notes }); PushPerfHistory(); break;
+ case "perfHistory": PushPerfHistory(); return;
+ case "updateGo": _ = InstallUpdateAsync(); return;
+ case "perfShare": if (m.TryGetProperty("value", out var ps)) SetPerfSharing(ps.GetBoolean()); return;
+ case "controls": if (m.TryGetProperty("value", out var cv) && cv.ValueKind == JsonValueKind.Object) SetControls(cv); break;
+ case "lobby":
+ {
+ var online = LoadOnlineConfig();
+ if (online != null) { using var lobby = new LobbyForm(online.Value.Server, online.Value.Name); lobby.ShowDialog(this); }
+ break;
+ }
+ case "friends":
+ {
+ var online = LoadOnlineConfig();
+ if (online != null) { using var friends = new FriendsForm(online.Value.Server, online.Value.Name, online.Value.Key); friends.ShowDialog(this); }
+ break;
+ }
+ case "server":
+ if (m.TryGetProperty("address", out var a)) SwitchServer(a.GetString() ?? "");
+ break;
+ case "social":
+ case "chatSend":
+ case "chatAction":
+ case "friend":
+ case "room":
+ _ = SocialAsync(cmd, m.Clone());
+ return;
+ }
+ if (cmd is "set" or "toggle") SaveDeckToml();
+ PushGlassState(true);
+ }
+
+ // Moves this install to another region: the same name and key, another server (online.json in both places).
+ private void SwitchServer(string address)
+ {
+ if (gameRunning || !Regions.Any(r => r.Address == address)) return;
+ // The second copy sits beside the game executable (Binaries\, or Game\ in installs before 1.5.5).
+ string exeFolder;
+ try { exeFolder = Path.GetDirectoryName(Path.GetFullPath(exePathBox.Text.Trim())) ?? AppContext.BaseDirectory; }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) { exeFolder = AppContext.BaseDirectory; }
+ foreach (string path in new[] { Path.Combine(AppContext.BaseDirectory, "online.json"), Path.Combine(exeFolder, "online.json") })
+ {
+ try
+ {
+ if (!File.Exists(path)) continue;
+ var node = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(path))!;
+ node["server"] = address;
+ File.WriteAllText(path, node.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ UpdateStatus("Could not change the server: " + ex.Message, false);
+ }
+ }
+ }
+
+ private async Task PollServers()
+ {
+ using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(4) };
+ while (!IsDisposed)
+ {
+ foreach (var (_, address) in Regions)
+ {
+ int ping = -1, online = -1;
+ try
+ {
+ var watch = Stopwatch.StartNew();
+ using (var tcp = new TcpClient()) { await tcp.ConnectAsync(address, 29812).WaitAsync(TimeSpan.FromSeconds(3)); }
+ ping = (int)watch.ElapsedMilliseconds;
+ using var doc = JsonDocument.Parse(await http.GetStringAsync($"http://{address}:29812/v1/online"));
+ online = doc.RootElement.GetProperty("online").GetInt32();
+ }
+ catch (Exception) { /* offline or unreachable: shown as offline */ }
+ lock (serverInfo) serverInfo[address] = (ping, online);
+ }
+ await Task.Delay(15000);
+ }
+ }
+
+ private void PushGlassState(bool force)
+ {
+ if (!PageConnected) return;
+ var fields = GlassFields().ToDictionary(f => f.Key, f => (object)new
+ {
+ items = f.Value.Items.Cast<object>().Select(x => x?.ToString() ?? "").ToArray(),
+ index = f.Value.SelectedIndex,
+ enabled = f.Value.Enabled,
+ });
+ var toggles = GlassToggles().ToDictionary(t => t.Key, t => (object)new { on = t.Value.Checked, enabled = t.Value.Enabled });
+ toggles["perfShare"] = new { on = perfShareCached, enabled = true };
+ var online = LoadOnlineConfig();
+ object? onlineState = null;
+ if (online != null)
+ {
+ Dictionary<string, (int Ping, int Online)> info;
+ lock (serverInfo) info = new(serverInfo);
+ onlineState = new
+ {
+ name = online.Value.Name,
+ server = online.Value.Server,
+ status = gameRunning ? "Playing" : onlineModeBox.Checked ? "Ready to play online" : "Online is off",
+ servers = Regions.Select(r => new
+ {
+ name = r.Name, address = r.Address,
+ ping = info.TryGetValue(r.Address, out var s) ? s.Ping : -1,
+ online = info.TryGetValue(r.Address, out var s2) ? s2.Online : -1,
+ }).ToArray(),
+ };
+ }
+ string json = JsonSerializer.Serialize(new
+ {
+ fields, toggles, online = onlineState, controls = ControlsState(),
+ exe = exePathBox.Text, data = gamePathBox.Text,
+ summary = hardwareLabel.Text, status = statusLabel.Text, statusOk = statusLabel.ForeColor != Color.FromArgb(255, 120, 120),
+ running = gameRunning, deck = deckBase,
+ api = graphicsApiBox.SelectedItem?.ToString(), profile = profileBox.SelectedItem?.ToString(),
+ version = "V" + LauncherVersion + " · ONLINE BETA",
+ });
+ if (!force && json == lastState) return;
+ lastState = json;
+ SendToPage(json);
+ }
+
+ // ---------- Social (players, friends, chat): HTTP to the player's own server with their name and key ----------
+ private static readonly HttpClient SocialHttp = new() { Timeout = TimeSpan.FromSeconds(6) };
+ private DateTime lastBackgroundSocial = DateTime.MinValue;
+
+ // One retry: a single dropped connection (a busy moment on the server, Wi-Fi) must not look like an outage.
+ private static async Task<string> SendWithRetry(Func<Task<string>> send)
+ {
+ try { return await send(); }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
+ {
+ await Task.Delay(400);
+ return await send();
+ }
+ }
+
+ private static async Task<JsonDocument?> PostJson(string server, string path, object body)
+ {
+ string json = JsonSerializer.Serialize(body);
+ string text = await SendWithRetry(async () =>
+ {
+ using var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
+ using var response = await SocialHttp.PostAsync($"http://{server}:29812{path}", content);
+ return await response.Content.ReadAsStringAsync();
+ });
+ return text.StartsWith("{") ? JsonDocument.Parse(text) : null;
+ }
+
+ private static async Task<JsonDocument> GetJson(string server, string path) =>
+ JsonDocument.Parse(await SendWithRetry(() => SocialHttp.GetStringAsync($"http://{server}:29812{path}")));
+
+ private int socialFailures;
+
+ private async Task SocialAsync(string cmd, JsonElement m)
+ {
+ var online = LoadOnlineConfig();
+ if (online == null || !onlineModeBox.Checked || !PageConnected) return;
+ var (server, name, key) = online.Value;
+ string Str(string p) => m.TryGetProperty(p, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
+ string channel = Str("channel");
+ string? error = null;
+ try
+ {
+ if (cmd == "social" && channel == "")
+ {
+ // Social page closed: refresh the badge only every 15 s.
+ if (DateTime.UtcNow - lastBackgroundSocial < TimeSpan.FromSeconds(15)) return;
+ lastBackgroundSocial = DateTime.UtcNow;
+ }
+ if (cmd == "chatSend")
+ {
+ using var r = await PostJson(server, "/v1/textchat", new { me = name, key, action = "send", channel, text = Str("text") });
+ if (r != null && r.RootElement.TryGetProperty("error", out var e)) error = ChatError(e.GetString());
+ }
+ else if (cmd == "chatAction")
+ {
+ long id = m.TryGetProperty("id", out var idv) && idv.ValueKind == JsonValueKind.Number ? idv.GetInt64() : 0;
+ using var r = await PostJson(server, "/v1/textchat", new { me = name, key, action = Str("action"), other = Str("other"), id });
+ if (Str("action") == "report") error = "Thanks, the message was reported";
+ }
+ else if (cmd == "friend")
+ {
+ using var r = await PostJson(server, "/v1/friends", new { me = name, key, action = Str("action"), other = Str("other") });
+ if (r != null && r.RootElement.TryGetProperty("result", out var fr) && fr.ValueKind == JsonValueKind.String)
+ error = fr.GetString() switch { "unknown" => $"No player called {Str("other")}", "self" => "You can't add yourself", _ => null };
+ }
+ else if (cmd == "room")
+ {
+ // Game rooms (rooms.py): when a room is full the game takes both players to the match set-up by itself.
+ string action = Str("action");
+ long roomId = m.TryGetProperty("room", out var rv) && rv.ValueKind == JsonValueKind.Number ? rv.GetInt64() : 0;
+ int stadium = m.TryGetProperty("stadium", out var sv2) && sv2.ValueKind == JsonValueKind.Number ? sv2.GetInt32() : 1047;
+ using var r = action switch
+ {
+ "create" => await PostJson(server, "/v1/rooms", new { me = name, key, action, name = Str("title").Trim().Length > 0 ? Str("title").Trim() : name + "'s game", mode = Str("mode"), stadium }),
+ "join" => await PostJson(server, "/v1/rooms", new { me = name, key, action, room = roomId }),
+ _ => await PostJson(server, "/v1/rooms", new { me = name, key, action = "leave" }),
+ };
+ if (r != null && r.RootElement.TryGetProperty("error", out var re)) error = RoomError(re.GetString());
+ else if (action == "create" && r != null && r.RootElement.TryGetProperty("room", out var made))
+ {
+ // Tell the server channel, so anyone can join from the Open games list.
+ string text = $"🎮 I opened a {RoomModeName(Str("mode"))} game at {made.GetProperty("stadium_name").GetString()}. Join it from the Matches tab!";
+ using var _ = await PostJson(server, "/v1/textchat", new { me = name, key, action = "send", channel = "general", text });
+ }
+ }
+
+ // Fresh snapshot for the page.
+ using var friends = await PostJson(server, "/v1/friends", new { me = name, key, action = "list" });
+ using var players = await GetJson(server, "/v1/online");
+ JsonDocument? convos = null, msgs = null;
+ bool chatOff = false;
+ try
+ {
+ convos = await PostJson(server, "/v1/textchat", new { me = name, key, action = "conversations" });
+ if (channel != "")
+ {
+ long since = m.TryGetProperty("since", out var sv) && sv.ValueKind == JsonValueKind.Number ? sv.GetInt64() : 0;
+ if (cmd != "social") since = 0; // after sending, reload the channel from the page's last id
+ msgs = await PostJson(server, "/v1/textchat", new { me = name, key, action = "read", channel, since = m.TryGetProperty("since", out var s2) && s2.ValueKind == JsonValueKind.Number ? s2.GetInt64() : 0 });
+ }
+ chatOff = convos == null && msgs == null; // either answer means the chat is there
+ }
+ catch (HttpRequestException) { chatOff = true; }
+
+ using var rooms = await PostJson(server, "/v1/rooms", new { me = name, key, action = "list" });
+ using var myRoom = await PostJson(server, "/v1/rooms", new { me = name, key, action = "current" });
+ var waited = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
+ if (players.RootElement.TryGetProperty("searching_list", out var sl) && sl.ValueKind == JsonValueKind.Array)
+ foreach (var it in sl.EnumerateArray())
+ if (it.TryGetProperty("name", out var wn) && it.TryGetProperty("waited_s", out var ws) && ws.ValueKind == JsonValueKind.Number)
+ waited[wn.GetString() ?? ""] = ws.GetInt32();
+ string regionName = Regions.FirstOrDefault(r => r.Address == server).Name ?? server;
+ var payload = new Dictionary<string, object?>
+ {
+ ["type"] = "social",
+ ["me"] = name,
+ ["server"] = regionName,
+ ["channel"] = channel,
+ ["error"] = error,
+ ["chatOff"] = chatOff,
+ ["players"] = players.RootElement.TryGetProperty("players", out var pl)
+ ? pl.EnumerateArray().Select(p => new
+ {
+ name = p.GetProperty("name").GetString(),
+ state = p.GetProperty("state").GetString(),
+ note = p.GetProperty("state").GetString() switch
+ {
+ "in_game" => "Playing " + (p.TryGetProperty("mode", out var md) ? md.GetString() : ""),
+ "searching" => "Searching · " + (p.TryGetProperty("mode", out var md2) ? md2.GetString() : "") +
+ (waited.TryGetValue(p.GetProperty("name").GetString() ?? "", out int w) ? $" · {w / 60}:{w % 60:00}" : ""),
+ _ => "In the menus",
+ },
+ }).ToArray()
+ : Array.Empty<object>(),
+ };
+ if (players.RootElement.TryGetProperty("searching_modes", out var smodes))
+ payload["searchingModes"] = JsonSerializer.Deserialize<object>(smodes.GetRawText());
+ if (rooms != null && rooms.RootElement.TryGetProperty("rooms", out var rl))
+ payload["rooms"] = JsonSerializer.Deserialize<object>(rl.GetRawText());
+ if (myRoom != null && myRoom.RootElement.TryGetProperty("room", out var mr))
+ payload["myRoom"] = JsonSerializer.Deserialize<object>(mr.GetRawText());
+ OnRoomState(myRoom != null && myRoom.RootElement.TryGetProperty("room", out var mr2) ? mr2.Clone() : null);
+ if (friends != null)
+ {
+ var f = friends.RootElement;
+ payload["friends"] = f.TryGetProperty("friends", out var fl) ? JsonSerializer.Deserialize<object>(fl.GetRawText()) : null;
+ payload["requests"] = f.TryGetProperty("requests", out var rq) ? JsonSerializer.Deserialize<object>(rq.GetRawText()) : null;
+ payload["pending"] = f.TryGetProperty("pending", out var pd) ? JsonSerializer.Deserialize<object>(pd.GetRawText()) : null;
+ }
+ if (convos != null && convos.RootElement.TryGetProperty("conversations", out var cv))
+ payload["convos"] = JsonSerializer.Deserialize<object>(cv.GetRawText());
+ if (msgs != null && msgs.RootElement.TryGetProperty("messages", out var ms))
+ payload["messages"] = JsonSerializer.Deserialize<object>(ms.GetRawText());
+ convos?.Dispose(); msgs?.Dispose();
+ socialFailures = 0;
+ string json = JsonSerializer.Serialize(payload);
+ SendToPage(json);
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
+ {
+ // Background refreshes keep the last data; only say so after three failures in a row (or when the
+ // player's own action failed).
+ if (cmd == "social" && ++socialFailures < 3) return;
+ string json = JsonSerializer.Serialize(new { type = "social", error = "Server not reachable" });
+ SendToPage(json);
+ }
+ }
+
+ private static string RoomModeName(string mode) => mode switch
+ {
+ "fives" => "5-a-side", "sixes" => "6-a-side", "futsal" => "Futsal", _ => mode,
+ };
+
+ private static string RoomError(string? code) => code switch
+ {
+ "full" => "That game is already full",
+ "already_in_room" => "Leave your current game first",
+ "too_fast" => "Wait a few seconds before opening another game",
+ "no_such_room" or "unknown_room" => "That game is closed",
+ _ => "Could not do that: " + code,
+ };
+
+ private static string ChatError(string? code) => code switch
+ {
+ "too_fast" => "Slow down a little",
+ "no_links" => "Links are not allowed in chat",
+ "too_long" => "Message too long (300 characters max)",
+ "muted" => "You are muted for a while",
+ "banned" => "You can't use the chat",
+ "not_friends" => "You can only message friends",
+ _ => "Message not sent",
+ };
+}
diff --git a/Launcher/FifaStreetLauncher/LauncherForm.cs b/Launcher/FifaStreetLauncher/LauncherForm.cs
index 47b2eaa..f9bbe54 100644
--- a/Launcher/FifaStreetLauncher/LauncherForm.cs
+++ b/Launcher/FifaStreetLauncher/LauncherForm.cs
@@ -1,1831 +1,2122 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Drawing;
-using System.Drawing.Drawing2D;
-using System.IO;
-using System.Linq;
-using System.Runtime.InteropServices;
-using System.Text.Json;
-using System.Windows.Forms;
-using ReStreet.Ui;
-
-namespace FifaStreetLauncher;
-
-public class LauncherForm : Form, ISceneHost, IUiScaled
-{
- private readonly UiScaler scaler;
- public float UiScale => scaler.Scale;
-
- private readonly Color Bg = StreetTheme.Asphalt;
- private readonly Color Surface = Color.FromArgb(28, 31, 36);
- private readonly Color SurfaceAlt = StreetTheme.Field;
- private readonly Color Border = Color.FromArgb(62, 66, 72);
- private readonly Color Accent = StreetTheme.Yellow;
- private readonly Color AccentHover = Color.FromArgb(255, 212, 48);
- private readonly Color TextPrimary = StreetTheme.Ink;
- private readonly Color TextSecondary = StreetTheme.Muted;
-
- private readonly GlassCombo resolutionBox = new();
- private readonly GlassCombo refreshBox = new();
- private readonly GlassCombo displayModeBox = new();
- private readonly GlassCombo monitorBox = new();
- private readonly GlassCombo graphicsApiBox = new();
- private readonly GlassCombo gpuBox = new();
- private readonly List<int> gpuAdapterIndices = new();
- private readonly GlassCombo postEffectBox = new();
- private readonly GlassCombo internalResolutionBox = new();
- private readonly GlassCombo gameLanguageBox = new();
- private readonly GlassCombo readbackResolveBox = new();
- private readonly GlassCombo profileBox = new();
- private bool applyingProfile;
- private static readonly string[] ProfileNames =
- {
- "Balanced (default)",
- "Quality (strong PCs)",
- "Performance (weak PCs)",
- "Custom"
- };
- private static readonly string[] ReadbackResolveModes = { "full", "some", "fast", "none" };
- private static readonly int[] GameLanguageIds = { 1, 5, 4, 3, 6 };
-
- private readonly GlassToggle vsyncBox = new();
- private readonly GlassToggle vrrBox = new();
- private readonly GlassToggle msaaBox = new();
- private readonly GlassToggle readbackMemexportBox = new();
- private readonly GlassToggle readbackMemexportFastBox = new();
- private readonly GlassToggle clearMemoryPageStateBox = new();
- private readonly GlassToggle occlusionQueryBox = new();
- private readonly GlassToggle asyncShadersBox = new();
- private readonly GlassToggle logFrameStatsBox = new();
-
- private readonly TextBox gamePathBox = new();
- private readonly TextBox exePathBox = new();
-
- private readonly ThemedLabel statusLabel = new();
- private readonly ThemedLabel hardwareLabel = new();
- private readonly Label advancedChevron = new();
-
- private readonly RoundedPanel advancedPanel = new();
- private readonly SlantButton advancedButton = new();
- private readonly RoundedPanel compatibilityPanel = new();
- private readonly SlantButton compatibilityButton = new();
-
- private bool gameRunning;
- private bool closeAfterGame;
- private string? changedDisplay;
- private DEVMODE previousDisplayMode;
- private bool advancedVisible;
- private bool compatibilityVisible;
-
- private string SettingsPath =>
- Path.Combine(AppContext.BaseDirectory, "settings.json");
-
- public LauncherForm()
- {
- Text = "ReStreet Launcher";
- using (var icon = typeof(LauncherForm).Assembly.GetManifestResourceStream("fifastreet.ico")!)
- Icon = new Icon(icon);
- ClientSize = new Size(1250, 720);
- scaler = new UiScaler(this, 1250, 720);
- DoubleBuffered = true;
- ResizeRedraw = true;
- HandleCreated += (_, _) => StreetTheme.ApplyDarkTitleBar(Handle);
- StartPosition = FormStartPosition.CenterScreen;
- FormBorderStyle = FormBorderStyle.FixedSingle;
- MaximizeBox = false;
- BackColor = Bg;
- ForeColor = TextPrimary;
- Font = new Font("Segoe UI", 10F);
-
- BuildInterface();
- WireEvents();
- applyingProfile = true; // loading values must not flip the profile to Custom
- LoadDefaults();
- profileBox.SelectedIndex = 0;
- LoadSettings();
- applyingProfile = false;
- UpdateGraphicsApiState();
- UpdateRefreshRates();
- UpdateSummary();
- UpdateStatus("Ready to play", true);
- scaler.Capture();
- }
-
- // Layout on an 8 px grid (design pixels, window 1250 x 720): left column margin 48; glass sheet
- // 620..1202 x 32..688 (margin 48 / 32) with 24 px padding, so content spans x 644..1178 as two
- // 259 px columns with a 16 px gap. Captions are 16 high, fields 36, buttons 40.
- private const float DesignW = 1250f, DesignH = 720f;
- private const int Left = 48;
- private const int SheetX = 620, SheetY = 32, SheetW = 582, SheetH = 656, Pad = 24;
- private const int ContentX = SheetX + Pad, ContentW = SheetW - 2 * Pad;
- private const int ColW = 259, Col1 = ContentX, Col2 = ContentX + ColW + 16;
- private const int PanelY = 720, PanelX = Left, PanelW = 1154;
- private Bitmap? scene;
- private Size sceneSize;
-
- public Bitmap SceneBitmap { get { BuildScene(); return scene!; } }
-
- protected override void OnPaintBackground(PaintEventArgs e)
- {
- BuildScene();
- using (var floor = new SolidBrush(StreetTheme.Asphalt)) e.Graphics.FillRectangle(floor, ClientRectangle);
- e.Graphics.DrawImageUnscaled(scene!, 0, 0);
- }
-
- // Court backdrop, glass sheet, wordmark and credit, painted once per window size.
- private void BuildScene()
- {
- float s = ClientSize.Width / DesignW;
- var size = new Size(ClientSize.Width, (int)Math.Ceiling(DesignH * s));
- if (scene != null && sceneSize == size) return;
- scene?.Dispose();
- sceneSize = size;
- using var backdrop = StreetTheme.RenderBackdrop(size, DesignW, DesignH);
- using var blurred = StreetTheme.Blur(backdrop, 10);
- scene = new Bitmap(backdrop);
- using var g = Graphics.FromImage(scene);
- g.SmoothingMode = SmoothingMode.AntiAlias;
- g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
- g.ScaleTransform(s, s);
-
- StreetTheme.DrawGlass(g, blurred, s, new RectangleF(SheetX, SheetY, SheetW, SheetH), 16);
-
- using (var small = new Font(StreetTheme.CondensedFamily, 17, FontStyle.Bold, GraphicsUnit.Pixel))
- using (var yellow = new SolidBrush(StreetTheme.Yellow))
- StreetTheme.DrawSpaced(g, "FIFA STREET 2012 RECOMPILED", small, yellow, new PointF(Left, 56), 3.6f);
- StreetTheme.DrawWordmark(g, "ReStreet", new PointF(Left, 88), 178, StreetTheme.Ink);
- var tag = new RectangleF(Left, 240, 184, 36);
- using (var bar = new SolidBrush(StreetTheme.Yellow)) g.FillPolygon(bar, StreetTheme.Slant(tag, 12));
- using (var tagFont = new Font(StreetTheme.CondensedFamily, 18, FontStyle.Bold, GraphicsUnit.Pixel))
- using (var dark = new SolidBrush(StreetTheme.YellowDark))
- StreetTheme.DrawSpaced(g, "V1.3 · OFFLINE", tagFont, dark, new PointF(Left + 14, 246), 2.8f);
-
- using var name = new Font("Segoe UI", 15, FontStyle.Regular, GraphicsUnit.Pixel);
- StreetTheme.DrawLabelValue(g, "Ported by:", "SamuelitoDaVila", name, StreetTheme.Ink, StreetTheme.Ink, Left, 642);
- StreetTheme.DrawLabelValue(g, "Contributions:", "Emran_Ahm3d", name, StreetTheme.Muted, StreetTheme.Muted, Left, 665);
- }
-
- private void BuildInterface()
- {
- SuspendLayout();
-
- // Row 0: profile and game language. Rows 1-4: two columns. Each block is 16 + 8 + 36 = 60 high.
- const int row0 = 56, pitch = 84;
- void Field(string label, ComboBox box, int x, int row)
- {
- int y = row0 + row * pitch;
- AddFieldLabel(this, label, x, y);
- ConfigureCombo(box, x, y + 24, ColW);
- Controls.Add(box);
- }
- Field("Profile", profileBox, Col1, 0);
- profileBox.AccessibleName = "Performance profile";
- profileBox.Items.AddRange(ProfileNames);
- profileBox.SelectedIndex = 0;
- profileBox.SelectedIndexChanged += (_, _) => ApplyProfile();
- postEffectBox.SelectedIndexChanged += (_, _) => MarkCustomProfile();
- internalResolutionBox.SelectedIndexChanged += (_, _) => MarkCustomProfile();
- readbackResolveBox.SelectedIndexChanged += (_, _) => MarkCustomProfile();
- msaaBox.CheckedChanged += (_, _) => MarkCustomProfile();
- occlusionQueryBox.CheckedChanged += (_, _) => MarkCustomProfile();
-
- Field("Game language", gameLanguageBox, Col2, 0);
- gameLanguageBox.AccessibleName = "Game language";
- Field("Resolution", resolutionBox, Col1, 1);
- Field("Refresh rate", refreshBox, Col2, 1);
- Field("Display mode", displayModeBox, Col1, 2);
- Field("Monitor", monitorBox, Col2, 2);
- Field("Graphics API", graphicsApiBox, Col1, 3);
- Field("GPU", gpuBox, Col2, 3);
- Field("Post-processing", postEffectBox, Col1, 4);
- Field("Internal resolution", internalResolutionBox, Col2, 4);
-
- // Switches in one row, 24 px apart.
- vsyncBox.CheckedChanged += (_, _) => UpdateGraphicsApiState();
- readbackMemexportBox.CheckedChanged += (_, _) => UpdateGraphicsApiState();
- int switchX = Col1;
- foreach (var (box, text) in new (GlassToggle, string)[] { (vsyncBox, "VSync"), (vrrBox, "VRR / Tearing (D3D12)"), (msaaBox, "Native 2x MSAA") })
- {
- ConfigureCheck(box, text, switchX, 488);
- Controls.Add(box);
- switchX += box.GetPreferredSize(Size.Empty).Width + 24;
- }
-
- var tip = new ThemedLabel
- {
- Text = "Weaker PC? Pick the Performance profile.",
- ForeColor = TextSecondary,
- Font = StreetTheme.Body(10F),
- Bounds = new Rectangle(ContentX, 536, ContentW, 40)
- };
- Controls.Add(tip);
-
- // Bottom row: five equal buttons, 100 wide with 8 px gaps (5 x 100 + 4 x 8 = 532).
- void Chip(SlantButton button, string text, int index)
- {
- button.Kind = SlantKind.Glass;
- button.Text = text;
- button.Font = StreetTheme.Body(10F);
- button.Bounds = new Rectangle(ContentX + index * 108, 624, 100, 40);
- Controls.Add(button);
- }
- Chip(advancedButton, "Advanced", 0);
- Chip(compatibilityButton, "Compatibility", 1);
- var logsButton = new SlantButton();
- logsButton.Click += (_, _) => OpenLogs();
- Chip(logsButton, "Open logs", 2);
- var folderButton = new SlantButton();
- folderButton.Click += (_, _) => OpenGameFolder();
- Chip(folderButton, "Open folder", 3);
- var shortcutButton = new SlantButton();
- shortcutButton.Click += (_, _) => CreateDesktopShortcut();
- Chip(shortcutButton, "Shortcut", 4);
-
- ConfigureAdvancedPanel();
- Controls.Add(advancedPanel);
-
- ConfigureCompatibilityPanel();
- Controls.Add(compatibilityPanel);
-
- hardwareLabel.Text = "Detecting hardware...";
- hardwareLabel.ForeColor = TextSecondary;
- hardwareLabel.Font = StreetTheme.Body(11F);
- hardwareLabel.AutoEllipsis = true;
- hardwareLabel.TextAlign = ContentAlignment.MiddleLeft;
- hardwareLabel.Bounds = new Rectangle(Left, 312, 512, 24);
- Controls.Add(hardwareLabel);
-
- statusLabel.Font = StreetTheme.Body(11F, FontStyle.Bold);
- statusLabel.ForeColor = TextSecondary;
- statusLabel.TextAlign = ContentAlignment.MiddleLeft;
- statusLabel.Bounds = new Rectangle(Left, 344, 512, 24);
- Controls.Add(statusLabel);
-
- var playButton = new SlantButton
- {
- Kind = SlantKind.Primary,
- Text = "PLAY",
- Font = StreetTheme.Condensed(36, FontStyle.Bold),
- Bounds = new Rectangle(Left, 520, 480, 88)
- };
- playButton.Click += (_, _) => LaunchGame();
- Controls.Add(playButton);
- AcceptButton = playButton;
- ActiveControl = playButton;
-
- ResumeLayout(false);
- PerformLayout();
- }
-
- private void ConfigureAdvancedPanel()
- {
- advancedPanel.Bounds = new Rectangle(PanelX, PanelY, PanelW, 192);
- advancedPanel.FillColor = StreetTheme.PanelFlat;
- advancedPanel.BorderColor = Color.FromArgb(70, 72, 76);
- advancedPanel.Radius = 16;
- advancedPanel.Visible = false;
-
- const int browseW = 96, gap = 8, innerW = PanelW - 2 * Pad;
- void PathRow(string label, TextBox box, int y, Action browse)
- {
- AddFieldLabel(advancedPanel, label, Pad, y);
- advancedPanel.Controls.Add(new FieldFrame(box) { Bounds = new Rectangle(Pad, y + 24, innerW - browseW - gap, 40) });
- box.Font = StreetTheme.Body(10F);
- var button = new SlantButton { Kind = SlantKind.Glass, Text = "Browse", Font = StreetTheme.Body(10F), Bounds = new Rectangle(Pad + innerW - browseW, y + 24, browseW, 40) };
- button.Click += (_, _) => browse();
- advancedPanel.Controls.Add(button);
- }
- PathRow("Game executable", exePathBox, Pad, BrowseExe);
- PathRow("Game data folder", gamePathBox, Pad + 80, BrowseGame);
- }
-
- private void ConfigureCompatibilityPanel()
- {
- compatibilityPanel.Bounds = new Rectangle(PanelX, PanelY, PanelW, 248);
- compatibilityPanel.FillColor = StreetTheme.PanelFlat;
- compatibilityPanel.BorderColor = Color.FromArgb(70, 72, 76);
- compatibilityPanel.Radius = 16;
- compatibilityPanel.Visible = false;
-
- compatibilityPanel.Controls.Add(new ThemedLabel
- {
- Text = "COMPATIBILITY", Font = StreetTheme.Condensed(14F, FontStyle.Bold), ForeColor = StreetTheme.Ink,
- Bounds = new Rectangle(Pad, Pad, 400, 24)
- });
- compatibilityPanel.Controls.Add(new ThemedLabel
- {
- Text = "Renderer options for textures, lighting, black screens and stutter.", Font = StreetTheme.Body(10F), ForeColor = TextSecondary,
- Bounds = new Rectangle(Pad, Pad + 28, 800, 20)
- });
-
- AddFieldLabel(compatibilityPanel, "Readback Resolve", Pad, 92);
- ConfigureCombo(readbackResolveBox, Pad, 116, ColW);
- readbackResolveBox.AccessibleName = "Readback Resolve";
- compatibilityPanel.Controls.Add(readbackResolveBox);
-
- // Switches on the same 275 px column pitch as the main sheet (x = 299, 574, 849).
- int[] cols = { Pad + 275, Pad + 550, Pad + 825 };
- ConfigureCheck(readbackMemexportBox, "Memory Export", cols[0], 120);
- ConfigureCheck(readbackMemexportFastBox, "Fast MemExport", cols[1], 120);
- ConfigureCheck(clearMemoryPageStateBox, "Memory Page State", cols[2], 120);
- ConfigureCheck(occlusionQueryBox, "Occlusion Queries", cols[0], 162);
- ConfigureCheck(asyncShadersBox, "Async Shaders", cols[1], 162);
- ConfigureCheck(logFrameStatsBox, "Frame stats log", cols[2], 162);
- foreach (var box in new[] { readbackMemexportBox, readbackMemexportFastBox, clearMemoryPageStateBox, occlusionQueryBox, asyncShadersBox, logFrameStatsBox })
- compatibilityPanel.Controls.Add(box);
-
- compatibilityPanel.Controls.Add(new ThemedLabel
- {
- Text = "Readback Resolve: Some is the recommended mode (more FPS with the validated fixes). Full is the most compatible; Fast gives more FPS but may cause graphical corruption.",
- Font = StreetTheme.Body(10F), ForeColor = TextSecondary,
- Bounds = new Rectangle(Pad, 204, PanelW - 2 * Pad, 20)
- });
- }
-
- private void WireEvents()
- {
- advancedButton.Click += (_, _) => ToggleAdvanced();
- advancedChevron.Click += (_, _) => ToggleAdvanced();
- compatibilityButton.Click += (_, _) => ToggleCompatibility();
-
- monitorBox.SelectedIndexChanged += (_, _) =>
- {
- DetectDisplayModes();
- UpdateSummary();
- };
-
- graphicsApiBox.SelectedIndexChanged += (_, _) =>
- {
- UpdateGraphicsApiState();
- UpdateSummary();
- };
-
- resolutionBox.SelectedIndexChanged += (_, _) => { UpdateRefreshRates(); UpdateSummary(); };
-internalResolutionBox.SelectedIndexChanged += (_, _) =>
-{
- UpdateSummary();
- if (!gameRunning)
- UpdateStatus(internalResolutionBox.SelectedIndex >= 2
- ? "High internal resolution may reduce FPS"
- : "Ready to play", true);
-};
-refreshBox.SelectedIndexChanged += (_, _) => UpdateSummary();
-gpuBox.SelectedIndexChanged += (_, _) => UpdateSummary();
-
-gpuBox.DropDown += (_, _) =>
-{
- int width = gpuBox.Width;
-
- using Graphics graphics = gpuBox.CreateGraphics();
-
- foreach (var item in gpuBox.Items)
- {
- int itemWidth = (int)Math.Ceiling(
- graphics.MeasureString(
- item?.ToString() ?? string.Empty,
- gpuBox.Font).Width);
-
- width = Math.Max(width, itemWidth + 40);
- }
-
- gpuBox.DropDownWidth = Math.Min(width, 500);
-};
-displayModeBox.SelectedIndexChanged += (_, _) => { UpdateRefreshRates(); UpdateSummary(); };
- }
-
- private void ToggleAdvanced()
- {
- if (compatibilityVisible)
- {
- compatibilityVisible = false;
- compatibilityPanel.Visible = false;
- }
-
- advancedVisible = !advancedVisible;
- advancedPanel.Visible = advancedVisible;
- advancedChevron.Text = advancedVisible ? "⌃" : "⌄";
- advancedButton.Active = advancedVisible;
- compatibilityButton.Active = compatibilityVisible;
-
- if (advancedVisible)
- {
- scaler.DesignHeight = 944;
- }
- else
- {
- scaler.DesignHeight = 720;
- }
- }
-
- private void ToggleCompatibility()
- {
- if (advancedVisible)
- {
- advancedVisible = false;
- advancedPanel.Visible = false;
- advancedChevron.Text = "⌄";
- }
-
- compatibilityVisible = !compatibilityVisible;
- compatibilityPanel.Visible = compatibilityVisible;
- compatibilityButton.Active = compatibilityVisible;
- advancedButton.Active = advancedVisible;
-
- if (compatibilityVisible)
- {
- scaler.DesignHeight = 1000;
- }
- else
- {
- scaler.DesignHeight = 720;
- }
- }
-
- private void MoveBottomControls(int secondaryY, int playY, int footerY)
- {
- foreach (Control control in Controls)
- {
- if (control is ModernButton button)
- {
- if (button.Text == "OPEN LOGS" || button.Text == "OPEN FOLDER")
- button.Top = secondaryY;
- else if (button.Text == "PLAY")
- button.Top = playY;
- }
- else if (control is Label label &&
- (label.Text.StartsWith("ReStreet •", StringComparison.Ordinal) || label.Tag as string == "credit"))
- {
- label.Top = footerY;
- }
- }
- }
-
- private RoundedPanel CreateCard(Point location, Size size)
- {
- return new RoundedPanel
- {
- Location = location,
- Size = size,
- FillColor = Surface,
- BorderColor = Border,
- Radius = 16
- };
- }
-
- private void AddSectionHeader(Control parent, string title, string subtitle, int x, int y)
- {
- var titleLabel = new Label
- {
- Text = title,
- ForeColor = TextPrimary,
- Font = new Font("Segoe UI Semibold", 11F, FontStyle.Bold),
- AutoSize = true,
- Location = new Point(x, y)
- };
- parent.Controls.Add(titleLabel);
-
- var subtitleLabel = new Label
- {
- Text = subtitle,
- ForeColor = TextSecondary,
- Font = new Font("Segoe UI", 8.8F),
- AutoSize = true,
- Location = new Point(x, y + 26)
- };
- parent.Controls.Add(subtitleLabel);
- }
-
- private void AddFieldLabel(Control parent, string text, int x, int y)
- {
- parent.Controls.Add(new ThemedLabel
- {
- Text = text.ToUpperInvariant(),
- ForeColor = TextSecondary,
- Font = StreetTheme.Condensed(9F, FontStyle.Bold),
- Bounds = new Rectangle(x, y, ColW, 16)
- });
- }
-
- private void ConfigureCombo(ComboBox box, int x, int y, int width)
- {
- box.Bounds = new Rectangle(x, y, width, 36);
- box.DropDownHeight = 240;
- }
-
- private void ConfigureCheck(CheckBox box, string text, int x, int y)
- {
- box.Text = text;
- box.Location = new Point(x, y);
- box.AutoSize = true;
- box.ForeColor = TextPrimary;
- box.BackColor = Color.Transparent;
- box.Font = StreetTheme.Body(10F);
- box.Cursor = Cursors.Hand;
- }
-
- private void StyleTextBox(TextBox box)
- {
- box.BackColor = SurfaceAlt;
- box.ForeColor = TextPrimary;
- box.BorderStyle = BorderStyle.FixedSingle;
- box.Font = new Font("Segoe UI", 9F);
- }
-
- private void LoadDefaults()
- {
- exePathBox.Text =
- Path.Combine(AppContext.BaseDirectory, "Game", "fifastreet.exe");
-
- gamePathBox.Text =
- Path.Combine(AppContext.BaseDirectory, "GameData");
-
- displayModeBox.Items.AddRange(new object[]
- {
- "Fullscreen",
- "Windowed"
- });
- displayModeBox.SelectedIndex = 0;
-
- graphicsApiBox.Items.AddRange(new object[]
- {
- "Direct3D 12",
- "Vulkan"
- });
- graphicsApiBox.SelectedIndex = 0;
- gameLanguageBox.Items.AddRange(new object[] { "English", "Español", "Français", "Deutsch", "Italiano" });
- gameLanguageBox.SelectedIndex = 0;
-
- readbackResolveBox.Items.AddRange(new object[]
- {
- "Full (compatible)",
- "Some (recommended)",
- "Fast (more FPS, may glitch)",
- "None (experimental)"
- });
- readbackResolveBox.SelectedIndex = 1;
-
- monitorBox.Items.Clear();
- foreach (var screen in Screen.AllScreens)
- {
- string primary = screen.Primary ? " • Primary" : "";
- monitorBox.Items.Add(
- $"{monitorBox.Items.Count}: {screen.DeviceName}{primary}"
- );
- }
-
- if (monitorBox.Items.Count > 0)
- monitorBox.SelectedIndex = Math.Max(0, Array.FindIndex(Screen.AllScreens, screen => screen.Primary));
-
- DetectDisplayModes();
- DetectGpus();
-
- postEffectBox.Items.AddRange(new object[]
-{
- "None",
- "FXAA",
- "FXAA Extreme"
-});
- postEffectBox.SelectedIndex = 1;
-
- internalResolutionBox.Items.AddRange(new object[]
-{
- "1x - Native (1280 x 720)",
- "2x - 2560 x 1440",
- "3x - 3840 x 2160",
- "4x - 5120 x 2880"
-});
- internalResolutionBox.SelectedIndex = 0;
-
-
- readbackMemexportBox.Checked = true;
- readbackMemexportFastBox.Checked = true;
- clearMemoryPageStateBox.Checked = false;
- logFrameStatsBox.Checked = false;
- occlusionQueryBox.Checked = false;
- asyncShadersBox.Checked = true;
-
- vsyncBox.Checked = false;
- vrrBox.Checked = true;
- msaaBox.Checked = false;
- }
-
- private void DetectGpus()
- {
- gpuBox.Items.Clear();
- gpuAdapterIndices.Clear();
- gpuBox.Items.Add("Automatic");
- gpuAdapterIndices.Add(-1);
-
- try
- {
- foreach (var gpu in DxgiAdapters.Enumerate())
- {
- gpuBox.Items.Add(
- $"Adapter {gpu.Index}: {gpu.Name}"
- );
- gpuAdapterIndices.Add(checked((int)gpu.Index));
- }
- }
- catch
- {
- // Automatic selection remains available when DXGI enumeration fails.
- }
-
- gpuBox.Items.Add("WARP (Software)");
- gpuAdapterIndices.Add(-2);
- gpuBox.SelectedIndex = 0;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
- private struct DEVMODE
- {
- private const int CCHDEVICENAME = 32;
- private const int CCHFORMNAME = 32;
-
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
- public string dmDeviceName;
-
- public short dmSpecVersion;
- public short dmDriverVersion;
- public short dmSize;
- public short dmDriverExtra;
- public int dmFields;
-
- public int dmPositionX;
- public int dmPositionY;
- public int dmDisplayOrientation;
- public int dmDisplayFixedOutput;
-
- public short dmColor;
- public short dmDuplex;
- public short dmYResolution;
- public short dmTTOption;
- public short dmCollate;
-
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]
- public string dmFormName;
-
- public short dmLogPixels;
- public int dmBitsPerPel;
- public int dmPelsWidth;
- public int dmPelsHeight;
- public int dmDisplayFlags;
- public int dmDisplayFrequency;
-
- public int dmICMMethod;
- public int dmICMIntent;
- public int dmMediaType;
- public int dmDitherType;
- public int dmReserved1;
- public int dmReserved2;
- public int dmPanningWidth;
- public int dmPanningHeight;
- }
-
- [DllImport("user32.dll", CharSet = CharSet.Ansi)]
- private static extern bool EnumDisplaySettings(
- string deviceName,
- int modeNum,
- ref DEVMODE devMode
- );
-
- private const int ENUM_CURRENT_SETTINGS = -1;
-
- private void DetectDisplayModes()
- {
- string? oldResolution = resolutionBox.SelectedItem?.ToString();
- string? oldRefresh = refreshBox.SelectedItem?.ToString();
-
- resolutionBox.Items.Clear();
- refreshBox.Items.Clear();
-
- var resolutions = new HashSet<string>();
- var refreshRates = new SortedSet<int>();
-
- Screen screen =
- monitorBox.SelectedIndex >= 0 &&
- monitorBox.SelectedIndex < Screen.AllScreens.Length
- ? Screen.AllScreens[monitorBox.SelectedIndex]
- : Screen.PrimaryScreen!;
-
- int modeNum = 0;
-
- while (true)
- {
- DEVMODE mode = CreateDevMode();
-
- if (!EnumDisplaySettings(
- screen.DeviceName,
- modeNum,
- ref mode))
- {
- break;
- }
-
- if (mode.dmPelsWidth >= 1280 &&
- mode.dmPelsHeight >= 720 &&
- mode.dmBitsPerPel >= 32)
- {
- resolutions.Add(
- $"{mode.dmPelsWidth}x{mode.dmPelsHeight}"
- );
-
- if (mode.dmDisplayFrequency > 20 &&
- mode.dmDisplayFrequency < 1000)
- {
- refreshRates.Add(mode.dmDisplayFrequency);
- }
- }
-
- modeNum++;
- }
-
- // Always expose common output resolutions up to 4K,
- // even when the current monitor does not advertise them.
- resolutions.Add("1280x720");
- resolutions.Add("1920x1080");
- resolutions.Add("2560x1440");
- resolutions.Add("3200x1800");
- resolutions.Add("3840x2160");
-
- foreach (string resolution in resolutions
- .OrderBy(x =>
- {
- var p = x.Split('x');
- return int.Parse(p[0]) * int.Parse(p[1]);
- }))
- {
- resolutionBox.Items.Add(resolution);
- }
-
- foreach (int hz in refreshRates)
- {
- refreshBox.Items.Add(hz.ToString());
- }
-
- if (resolutionBox.Items.Count == 0)
- {
- resolutionBox.Items.AddRange(new object[]
- {
- "1280x720",
- "1600x900",
- "1920x1080",
- "2560x1440",
- "3200x1800",
- "3840x2160"
- });
- }
-
- if (refreshBox.Items.Count == 0)
- {
- refreshBox.Items.AddRange(new object[]
- {
- "30", "50", "60", "75", "100",
- "120", "144", "165", "180", "200", "240"
- });
- }
-
- if (!string.IsNullOrWhiteSpace(oldResolution) &&
- resolutionBox.Items.Contains(oldResolution))
- {
- resolutionBox.SelectedItem = oldResolution;
- }
- else
- {
- string currentResolution =
- $"{screen.Bounds.Width}x{screen.Bounds.Height}";
-
- if (resolutionBox.Items.Contains(currentResolution))
- resolutionBox.SelectedItem = currentResolution;
- else if (resolutionBox.Items.Count > 0)
- resolutionBox.SelectedIndex = resolutionBox.Items.Count - 1;
- }
-
- if (!string.IsNullOrWhiteSpace(oldRefresh) &&
- refreshBox.Items.Contains(oldRefresh))
- {
- refreshBox.SelectedItem = oldRefresh;
- }
- else
- {
- DEVMODE currentMode = CreateDevMode();
-
- if (EnumDisplaySettings(
- screen.DeviceName,
- ENUM_CURRENT_SETTINGS,
- ref currentMode))
- {
- string currentHz =
- currentMode.dmDisplayFrequency.ToString();
-
- if (refreshBox.Items.Contains(currentHz))
- refreshBox.SelectedItem = currentHz;
- }
-
- if (refreshBox.SelectedIndex < 0 &&
- refreshBox.Items.Count > 0)
- {
- refreshBox.SelectedIndex = 0;
- }
- }
- }
-
- private void UpdateRefreshRates()
- {
- if (monitorBox.SelectedIndex < 0 || resolutionBox.SelectedIndex < 0) return;
- string previous = refreshBox.Text;
- Screen screen = Screen.AllScreens[monitorBox.SelectedIndex];
- DEVMODE desktop = CreateDevMode();
- if (!EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref desktop)) return;
- string[] size = resolutionBox.Text.Split('x');
- if (size.Length != 2 || !int.TryParse(size[0], out int width) ||
- !int.TryParse(size[1], out int height)) return;
- if (displayModeBox.SelectedIndex != 0) {
- width = desktop.dmPelsWidth;
- height = desktop.dmPelsHeight;
- }
- var rates = new SortedSet<int>();
- for (int i = 0; ; i++) {
- DEVMODE mode = CreateDevMode();
- if (!EnumDisplaySettings(screen.DeviceName, i, ref mode)) break;
- if (mode.dmPelsWidth == width && mode.dmPelsHeight == height &&
- mode.dmBitsPerPel >= 32 && mode.dmDisplayFrequency > 20)
- rates.Add(mode.dmDisplayFrequency);
- }
- refreshBox.Items.Clear();
- foreach (int rate in rates) refreshBox.Items.Add(rate.ToString());
- if (refreshBox.Items.Contains(previous)) refreshBox.SelectedItem = previous;
- else if (refreshBox.Items.Contains(desktop.dmDisplayFrequency.ToString()))
- refreshBox.SelectedItem = desktop.dmDisplayFrequency.ToString();
- else if (refreshBox.Items.Count > 0) refreshBox.SelectedIndex = 0;
- }
-
- private static DEVMODE CreateDevMode()
- {
- return new DEVMODE
- {
- dmDeviceName = new string('\0', 32),
- dmFormName = new string('\0', 32),
- dmSize = (short)Marshal.SizeOf<DEVMODE>()
- };
- }
-
- private void UpdateGraphicsApiState()
- {
- bool isD3D12 = graphicsApiBox.SelectedIndex != 1;
-
- // GPU adapter selection is currently specific to the D3D12 backend.
- // Vulkan uses automatic device selection (REX_VULKAN_DEVICE=-1).
- gpuBox.Enabled = isD3D12;
- vrrBox.Enabled = isD3D12 && !vsyncBox.Checked;
- vrrBox.Text = "VRR / Tearing (D3D12)";
- readbackMemexportFastBox.Enabled = readbackMemexportBox.Checked;
-
- if (!isD3D12)
- {
- gpuBox.BackColor = Color.FromArgb(34, 38, 43);
- }
- else
- {
- gpuBox.BackColor = Color.FromArgb(24, 28, 32);
- }
- }
- private void UpdateSummary()
- {
- string gpu;
-
- if (graphicsApiBox.SelectedIndex == 1)
- {
- gpu = "Automatic GPU (Vulkan)";
- }
- else
- {
- gpu = gpuBox.SelectedItem?.ToString() ?? "Automatic GPU";
- if (gpu == "Automatic") gpu = "Automatic GPU";
-
- if (gpu.StartsWith("Adapter ", StringComparison.Ordinal))
- {
- int colon = gpu.IndexOf(':');
- if (colon >= 0 && colon + 1 < gpu.Length)
- gpu = gpu[(colon + 1)..].Trim();
- }
- }
-
- string resolution = resolutionBox.SelectedItem?.ToString() ?? "Resolution";
- string hz = refreshBox.SelectedItem?.ToString() ?? "--";
-
- hardwareLabel.Text =
- $"{gpu} · {resolution} · {hz} Hz";
- }
-
- private void UpdateStatus(string text, bool ok)
- {
- statusLabel.Text = text;
- statusLabel.ForeColor = ok ? TextSecondary : Color.FromArgb(255, 120, 120);
- }
-
- // Direct play (--play): the window stays invisible, the game starts with the saved settings and the
- // launcher closes by itself after the game exits (it still restores the display mode first).
- public void StartDirect()
- {
- closeAfterGame = true;
- ShowInTaskbar = false;
- Opacity = 0;
- StartPosition = FormStartPosition.Manual;
- Location = new Point(-32000, -32000);
- Shown += (_, _) => LaunchGame();
- }
-
- private void CreateDesktopShortcut()
- {
- try
- {
- SaveSettings();
- string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
- string target = Environment.ProcessPath ?? Application.ExecutablePath;
- string path = Path.Combine(desktop, "ReStreet (direct play).lnk");
- Type? shellType = Type.GetTypeFromProgID("WScript.Shell");
- if (shellType == null) throw new InvalidOperationException("Windows Script Host is not available.");
- dynamic shell = Activator.CreateInstance(shellType)!;
- dynamic link = shell.CreateShortcut(path);
- link.TargetPath = target;
- link.Arguments = "--play";
- link.WorkingDirectory = Path.GetDirectoryName(target);
- link.IconLocation = target + ",0";
- link.Description = "Start ReStreet directly with the settings saved in the launcher";
- link.Save();
- MessageBox.Show(
- "A shortcut was created on your desktop: ReStreet (direct play)." + Environment.NewLine + Environment.NewLine +
- "It starts the game straight away with the settings you have now. " +
- "To change settings later, open the launcher normally and click Shortcut again to refresh it.",
- "ReStreet Launcher", MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "Could not create the shortcut", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
-
- private async void LaunchGame()
- {
- if (gameRunning) {
- ShowError("ReStreet is already running.");
- return;
- }
- try
- {
- string exe = exePathBox.Text.Trim();
- string gameRoot = gamePathBox.Text.Trim();
-
- if (!File.Exists(exe))
- {
- ShowError("fifastreet.exe was not found.");
- return;
- }
-
- if (!Directory.Exists(gameRoot))
- {
- ShowError("The game data folder does not exist.");
- return;
- }
-
- if (!File.Exists(Path.Combine(gameRoot, "default.xex")))
- {
- MessageBox.Show(
- "The selected folder does not contain default.xex.",
- "Invalid folder",
- MessageBoxButtons.OK,
- MessageBoxIcon.Warning
- );
- return;
- }
-
- // Select the validated ReXGlue graphics backend.
- string graphicsApi = graphicsApiBox.SelectedIndex == 1
- ? "Vulkan"
- : "D3D12";
-
- string backendDirectory = Path.Combine(
- Path.GetDirectoryName(exe)!,
- "Backends",
- graphicsApi);
-
- string backendRuntime = Path.Combine(
- backendDirectory,
- "rexruntime.dll");
-
- string backendGpu = Path.Combine(
- backendDirectory,
- "rexgpu-xenos.dll");
-
- if (!File.Exists(backendRuntime) || !File.Exists(backendGpu))
- {
- MessageBox.Show(
- $"The {graphicsApi} graphics backend is missing.\n\n" +
- $"Expected files in:\n{backendDirectory}",
- "ReStreet Launcher",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- return;
- }
-
- string executableDirectory = Path.GetDirectoryName(exe)!;
-
- File.Copy(
- backendRuntime,
- Path.Combine(executableDirectory, "rexruntime.dll"),
- true);
-
- File.Copy(
- backendGpu,
- Path.Combine(executableDirectory, "rexgpu-xenos.dll"),
- true);
-
- var resolution = resolutionBox.Text.Split('x');
- if (resolution.Length != 2 ||
- !int.TryParse(resolution[0], out int width) ||
- !int.TryParse(resolution[1], out int height) ||
- width <= 0 || height <= 0)
- {
- ShowError("Select a valid resolution.");
- return;
- }
- string refresh = refreshBox.Text;
-
- bool fullscreen =
- displayModeBox.SelectedItem?.ToString() == "Fullscreen";
-
- int monitor = Math.Clamp(monitorBox.SelectedIndex, 0, Screen.AllScreens.Length - 1);
-
- int adapter = gpuBox.SelectedIndex >= 0
- ? gpuAdapterIndices[gpuBox.SelectedIndex] : -1;
-
- string postEffect = postEffectBox.SelectedIndex switch
- {
- 1 => "fxaa",
- 2 => "fxaa_extreme",
- _ => "none"
- };
-
-
- string logsDir = Path.Combine(
- Path.GetDirectoryName(exe)!,
- "Logs"
- );
-
- Directory.CreateDirectory(logsDir);
-
- string logFile =
- Path.Combine(logsDir, "fifastreet.log");
-
- var startInfo = new ProcessStartInfo
- {
- FileName = exe,
- WorkingDirectory = Path.GetDirectoryName(exe)!,
- UseShellExecute = false
- };
-
- // ReXGlue aplica a configuração por esta ordem:
- // argumentos CLI -> ficheiro TOML -> variáveis de ambiente.
- // Portanto, usar REX_* aqui garante que as escolhas do launcher
- // têm prioridade sobre qualquer configuração guardada no jogo.
-
- startInfo.Environment["REX_GAME_DATA_ROOT"] = gameRoot;
- startInfo.Environment["REX_VIDEO_MODE_WIDTH"] = width.ToString();
- startInfo.Environment["REX_VIDEO_MODE_HEIGHT"] = height.ToString();
- // The display size does not change the Xbox 360 render targets.
- int internalResolutionScale = Math.Max(1, internalResolutionBox.SelectedIndex + 1);
-
-startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_X"] =
- internalResolutionScale.ToString();
-
-startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_Y"] =
- internalResolutionScale.ToString();
- startInfo.Environment["REX_WINDOW_WIDTH"] = width.ToString();
- startInfo.Environment["REX_WINDOW_HEIGHT"] = height.ToString();
- // Apply the selected rate to both the monitor and Xbox video timing.
- startInfo.Environment["REX_VIDEO_MODE_REFRESH_RATE"] = refresh;
- // VSync on: lift the game's own 40 FPS replay/cutscene cap up to the chosen rate.
- // VSync off: no frame limit at all (the game's own limiter is raised out of the way).
- startInfo.Environment["REX_FRAME_LIMITER_MIN_HZ"] = vsyncBox.Checked ? "auto" : "1000";
- // Keep the one synchronous readback that keeps stadium floors clean (default 1282B000), drop the
- // other small-range ones that held goals, replays and match setup below the chosen rate.
- startInfo.Environment.Remove("REX_READBACK_SOME_SYNC_ADDRS");
- startInfo.Environment["REX_READBACK_SOME_SYNC_BELOW"] = "0";
- ApplyGameLanguage(startInfo);
- // The game keeps its own clock in both modes (True VSync shows its newest frame at each refresh).
- startInfo.Environment["REX_GUEST_VBLANK_UNLOCKED"] = "true";
- startInfo.Environment["REX_FULLSCREEN"] =
- fullscreen ? "true" : "false";
- startInfo.Environment["REX_MONITOR"] = (monitor + 1).ToString();
- startInfo.Environment["REX_LAUNCHER_MONITOR_DEVICE"] = Screen.AllScreens[monitor].DeviceName;
- // "VSync" = True VSync: no tearing, the display shows the game's newest frame at every refresh of the
- // chosen rate (any rate), and the FPS counter shows displayed frames like GPU overlays do. The old
- // blocking host VSync (REX_VSYNC) stays off: it made every GPU wait cost two refreshes.
- startInfo.Environment["REX_VSYNC"] = "false";
- startInfo.Environment["REX_TRUE_VSYNC"] = vsyncBox.Checked ? "1" : "0";
- startInfo.Environment["REX_NATIVE_2X_MSAA"] =
- msaaBox.Checked ? "true" : "false";
- startInfo.Environment["REX_SWAP_POST_EFFECT"] = postEffect;
-
- if (graphicsApi == "D3D12")
- {
- // Validated D3D12 configuration.
- startInfo.Environment["REX_D3D12_ALLOW_VARIABLE_REFRESH_RATE_AND_TEARING"] =
- !vsyncBox.Checked && vrrBox.Checked ? "true" : "false";
- startInfo.Environment["REX_D3D12_ADAPTER"] = adapter.ToString();
-
- // Do not force ROV/RTV. The validated D3D12 build uses
- // ReXGlue's automatic render target path selection.
- startInfo.Environment["REX_RENDER_TARGET_PATH_D3D12"] = "";
- }
- else
- {
- // Validated Vulkan configuration.
- // Vulkan device stays automatic; DXGI adapter indices are
- // not interchangeable with Vulkan device indices.
- startInfo.Environment["REX_VULKAN_DEVICE"] = "-1";
- startInfo.Environment["REX_RENDER_TARGET_PATH_VULKAN"] = "fbo";
- // Vulkan-only image settings that remove the goal-replay blur
- // (user-tested together on AMD; not bisected to a single one).
- startInfo.Environment["REX_DRAW_RESOLUTION_SCALED_TEXTURE_OFFSETS"] = "false";
- startInfo.Environment["REX_DEPTH_FLOAT24_CONVERT_IN_PIXEL_SHADER"] = "true";
- startInfo.Environment["REX_GAMMA_RENDER_TARGET_AS_UNORM16"] = "false";
- startInfo.Environment["REX_SNORM16_RENDER_TARGET_FULL_RANGE"] = "false";
- startInfo.Environment["REX_VULKAN_DYNAMIC_RENDERING"] = "false";
- startInfo.Environment["REX_HALF_PIXEL_OFFSET"] = "false";
- startInfo.Environment["REX_ANISOTROPIC_OVERRIDE"] = "-1";
- startInfo.Environment["REX_DIRECT_HOST_RESOLVE"] = "false";
- // Override legacy TOML values: checked means FIFO, unchecked
- // requests immediate presentation without display synchronization.
- // With VSync on, prefer MAILBOX (latest frame wins, no tearing, never blocks the queue).
- startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_IMMEDIATE"] =
- vsyncBox.Checked ? "false" : "true";
- startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_MAILBOX"] =
- vsyncBox.Checked ? "true" : "false";
- startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_FIFO_RELAXED"] =
- vsyncBox.Checked ? "false" : "true";
- }
-
- // Compatibilidade / coerência GPU.
- string readbackResolve = ReadbackResolveModes[Math.Clamp(readbackResolveBox.SelectedIndex, 0, ReadbackResolveModes.Length - 1)];
- startInfo.Environment["REX_READBACK_RESOLVE"] = readbackResolve;
- // Keep synchronous Full Readback; reduce scheduler round trips for
- // short GPU work without reading before its fence is signalled.
- startInfo.Environment["REX_D3D12_READBACK_SHORT_WAIT"] = "true";
- startInfo.Environment["REX_D3D12_READBACK_SPIN_US"] = "500";
- startInfo.Environment["REX_VULKAN_READBACK_SHORT_WAIT"] = "true";
- startInfo.Environment["REX_VULKAN_READBACK_SPIN_US"] = "500";
- startInfo.Environment["REX_READBACK_MEMEXPORT"] =
- readbackMemexportBox.Checked ? "true" : "false";
- startInfo.Environment[graphicsApi == "Vulkan"
- ? "REX_VULKAN_READBACK_MEMEXPORT" : "REX_D3D12_READBACK_MEMEXPORT"] =
- readbackMemexportBox.Checked ? "true" : "false";
- startInfo.Environment["REX_READBACK_MEMEXPORT_FAST"] =
- readbackMemexportBox.Checked && readbackMemexportFastBox.Checked ? "true" : "false";
- startInfo.Environment["REX_CLEAR_MEMORY_PAGE_STATE"] =
- clearMemoryPageStateBox.Checked ? "true" : "false";
- startInfo.Environment["REX_OCCLUSION_QUERY_ENABLE"] =
- occlusionQueryBox.Checked ? "true" : "false";
- startInfo.Environment["REX_ASYNC_SHADER_COMPILATION"] =
- asyncShadersBox.Checked ? "true" : "false";
-
- startInfo.Environment["REX_LOG_VERBOSE"] = "false";
- startInfo.Environment["REX_LOG_LEVEL"] = "info";
- startInfo.Environment["REX_LOG_FRAME_STATS"] = logFrameStatsBox.Checked ? "true" : "false";
- startInfo.Environment["REX_BIND_DEBUG_OVERLAY"] = "Home";
- startInfo.Environment["REX_LOG_FILE"] = logFile;
-
- // Mantemos game_data_root também como argumento porque esta
- // aplicação já confirmou que o aceita diretamente.
- startInfo.ArgumentList.Add($"--game_data_root={gameRoot}");
-
- SaveSettings();
-
- string launcherDebug = Path.Combine(
- logsDir,
- "launcher_settings.txt"
- );
-
- File.WriteAllText(
- launcherDebug,
- $"Resolution={width}x{height}{Environment.NewLine}" +
- $"InternalResolution={1280 * internalResolutionScale}x{720 * internalResolutionScale} ({internalResolutionScale}x){Environment.NewLine}" +
- $"MonitorRefreshRate={refresh}{Environment.NewLine}" +
- $"GuestRefreshRate={refresh}{Environment.NewLine}" +
- $"GuestVblankUnlocked={!vsyncBox.Checked}{Environment.NewLine}" +
- $"GraphicsApi={graphicsApi}{Environment.NewLine}" +
- $"Fullscreen={fullscreen}{Environment.NewLine}" +
- $"Monitor={monitor}{Environment.NewLine}" +
- $"VSync={vsyncBox.Checked}{Environment.NewLine}" +
- $"VRRRequested={vrrBox.Checked}; VRREffective={graphicsApi == "D3D12" && !vsyncBox.Checked && vrrBox.Checked}{Environment.NewLine}" +
- $"MSAA={msaaBox.Checked}{Environment.NewLine}" +
- $"PostEffect={postEffect}{Environment.NewLine}" +
- $"Adapter={adapter}{Environment.NewLine}" +
- $"ReadbackResolve={readbackResolve}{Environment.NewLine}" +
- $"ReadbackMemexport={readbackMemexportBox.Checked}{Environment.NewLine}" +
- $"ReadbackMemexportFast={readbackMemexportBox.Checked && readbackMemexportFastBox.Checked}{Environment.NewLine}" +
- $"ClearMemoryPageState={clearMemoryPageStateBox.Checked}{Environment.NewLine}" +
- $"OcclusionQueries={occlusionQueryBox.Checked}{Environment.NewLine}" +
- $"AsyncShaders={asyncShadersBox.Checked}{Environment.NewLine}"
- );
-
- UpdateStatus("Starting ReStreet...", true);
-
- ApplyMonitorRefresh(monitor, refresh, fullscreen ? width : 0, fullscreen ? height : 0);
- using var process = Process.Start(startInfo);
- gameRunning = process != null;
-
- UpdateStatus(
- process != null
- ? $"Running • PID {process.Id}"
- : "Could not start the game",
- process != null
- );
- if (process != null) {
- await process.WaitForExitAsync();
- UpdateStatus("Ready to play", true);
- }
- }
- catch (Exception ex)
- {
- UpdateStatus("Launch failed", false);
-
- MessageBox.Show(
- ex.Message,
- "Error starting ReStreet",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error
- );
- }
- finally {
- RestoreMonitorRefresh();
- gameRunning = false;
- if (closeAfterGame) Close();
- }
- }
-
- protected override void OnFormClosing(FormClosingEventArgs e)
- {
- if (gameRunning && e.CloseReason == CloseReason.UserClosing) {
- // Keep the launcher alive to restore the display after the game exits.
- closeAfterGame = true;
- e.Cancel = true;
- Hide();
- }
- base.OnFormClosing(e);
- }
-
- [DllImport("user32.dll", CharSet = CharSet.Ansi)]
- private static extern int ChangeDisplaySettingsEx(
- string deviceName, ref DEVMODE mode, IntPtr window, uint flags, IntPtr parameter);
-
- [DllImport("user32.dll", CharSet = CharSet.Ansi, EntryPoint = "ChangeDisplaySettingsEx")]
- private static extern int ChangeDisplaySettingsExToRegistry(
- string deviceName, IntPtr mode, IntPtr window, uint flags, IntPtr parameter);
-
- private void ApplyMonitorRefresh(int monitor, string refresh, int width, int height)
- {
- const uint CDS_TEST = 2;
- const int DM_DISPLAYFREQUENCY = 0x00400000;
- if (monitor < 0 || monitor >= Screen.AllScreens.Length ||
- !int.TryParse(refresh, out int hz) || hz <= 1) {
- throw new InvalidOperationException("Select a valid monitor and refresh rate.");
- }
- string device = Screen.AllScreens[monitor].DeviceName;
- DEVMODE original = CreateDevMode();
- if (!EnumDisplaySettings(device, ENUM_CURRENT_SETTINGS, ref original)) {
- throw new InvalidOperationException("Could not read the monitor's current display mode.");
- }
- bool changeResolution = width > 0 && height > 0;
- if (original.dmDisplayFrequency == hz &&
- (!changeResolution || (original.dmPelsWidth == width && original.dmPelsHeight == height))) return;
- DEVMODE requested = original;
- requested.dmDisplayFrequency = hz;
- requested.dmFields = DM_DISPLAYFREQUENCY;
- if (changeResolution) {
- requested.dmPelsWidth = width;
- requested.dmPelsHeight = height;
- requested.dmFields |= 0x00080000 | 0x00100000; // DM_PELSWIDTH | DM_PELSHEIGHT
- }
- int result = ChangeDisplaySettingsEx(device, ref requested, IntPtr.Zero, CDS_TEST, IntPtr.Zero);
- if (result != 0) {
- throw new InvalidOperationException(
- $"The selected resolution and {hz} Hz are not available on this monitor (Windows code {result}).");
- }
- // Dynamic change (not CDS_FULLSCREEN): a CDS_FULLSCREEN mode is tied to the launcher, and Windows dropped
- // it back to the desktop rate when the game window took focus (60 Hz chosen, 165 Hz measured in game).
- // It is not saved to the registry; RestoreMonitorRefresh puts the previous mode back after the game exits.
- result = ChangeDisplaySettingsEx(device, ref requested, IntPtr.Zero, 0, IntPtr.Zero);
- if (result != 0) {
- throw new InvalidOperationException($"Windows could not apply {hz} Hz (code {result}).");
- }
- original.dmFields = requested.dmFields;
- previousDisplayMode = original;
- changedDisplay = device;
- DEVMODE actual = CreateDevMode();
- if (!EnumDisplaySettings(device, ENUM_CURRENT_SETTINGS, ref actual) ||
- Math.Abs(actual.dmDisplayFrequency - hz) > 1 ||
- (changeResolution && (actual.dmPelsWidth != width || actual.dmPelsHeight != height))) {
- throw new InvalidOperationException("Windows did not apply the selected monitor refresh rate.");
- }
- }
-
- private void RestoreMonitorRefresh()
- {
- if (changedDisplay == null) return;
- string device = changedDisplay;
- changedDisplay = null;
- // Back to the mode saved in Windows display settings (the change above is dynamic and never saved);
- // fall back to the mode read before the change.
- int result = ChangeDisplaySettingsExToRegistry(device, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero);
- if (result != 0) {
- result = ChangeDisplaySettingsEx(device, ref previousDisplayMode, IntPtr.Zero, 0, IntPtr.Zero);
- }
- if (result != 0) {
- ShowError($"Could not restore the monitor refresh rate (Windows code {result}). Check Windows display settings.");
- }
- }
-
- private void ShowError(string message)
- {
- UpdateStatus("Check your settings", false);
-
- MessageBox.Show(
- message,
- "ReStreet Launcher",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error
- );
- }
-
- private void BrowseExe()
- {
- using var dialog = new OpenFileDialog
- {
- Filter = "FIFA Street executable|fifastreet.exe|Executables|*.exe"
- };
-
- if (dialog.ShowDialog() == DialogResult.OK)
- exePathBox.Text = dialog.FileName;
- }
-
- private void BrowseGame()
- {
- using var dialog = new FolderBrowserDialog
- {
- Description = "Select the folder containing default.xex"
- };
-
- if (dialog.ShowDialog() == DialogResult.OK)
- gamePathBox.Text = dialog.SelectedPath;
- }
-
- private void OpenLogs()
- {
- string exe = exePathBox.Text.Trim();
-
- if (!File.Exists(exe)) {
- ShowError("Select an existing game executable first.");
- return;
- }
-
- string logs = Path.Combine(
- Path.GetDirectoryName(exe)!,
- "Logs"
- );
-
- Directory.CreateDirectory(logs);
-
- Process.Start(new ProcessStartInfo
- {
- FileName = "explorer.exe",
- Arguments = $"\"{logs}\"",
- UseShellExecute = true
- });
- }
-
- private void OpenGameFolder()
- {
- string exe = exePathBox.Text.Trim();
-
- if (!File.Exists(exe)) {
- ShowError("Select an existing game executable first.");
- return;
- }
-
- Process.Start(new ProcessStartInfo
- {
- FileName = "explorer.exe",
- Arguments = $"\"{Path.GetDirectoryName(exe)}\"",
- UseShellExecute = true
- });
- }
-
- // post effect: 0 none, 1 FXAA, 2 FXAA extreme; internal resolution index = scale - 1;
- // readback: 0 full, 1 some (visually broken, never used), 2 fast
- private void ApplyProfile()
- {
- if (applyingProfile)
- return;
- (int post, int scale, bool msaa, int readback, bool occlusion)? values = profileBox.SelectedIndex switch
- {
- 0 => (1, 0, false, 1, false), // Balanced: the shipped defaults (Some readback)
- 1 => (2, 1, true, 1, false), // Quality: 2x internal resolution, FXAA extreme, MSAA (Some readback)
- 2 => (0, 0, false, 2, false), // Performance: native resolution, no post, faster readback
- _ => null
- };
- if (values == null)
- return;
- applyingProfile = true;
- try
- {
- postEffectBox.SelectedIndex = values.Value.post;
- internalResolutionBox.SelectedIndex = values.Value.scale;
- msaaBox.Checked = values.Value.msaa;
- readbackResolveBox.SelectedIndex = values.Value.readback;
- occlusionQueryBox.Checked = values.Value.occlusion;
- }
- finally
- {
- applyingProfile = false;
- }
- }
-
- private void MarkCustomProfile()
- {
- if (!applyingProfile && profileBox.SelectedIndex != ProfileNames.Length - 1)
- {
- applyingProfile = true;
- profileBox.SelectedIndex = ProfileNames.Length - 1;
- applyingProfile = false;
- }
- }
-
- private void SaveSettings()
- {
- try
- {
- var settings = new LauncherSettings
- {
- ExePath = exePathBox.Text,
- GamePath = gamePathBox.Text,
- Resolution = resolutionBox.Text,
- RefreshRate = refreshBox.Text,
- Fullscreen = displayModeBox.SelectedIndex == 0,
- Monitor = monitorBox.SelectedIndex,
- GraphicsApi = graphicsApiBox.SelectedIndex,
- GameLanguage = GameLanguageIds[Math.Max(0, gameLanguageBox.SelectedIndex)],
- Gpu = gpuBox.SelectedIndex,
- GpuUsesDxgi = true,
- PostEffect = postEffectBox.SelectedIndex,
- InternalResolutionScale = internalResolutionBox.SelectedIndex,
- ReadbackResolve = readbackResolveBox.SelectedIndex,
- LogFrameStats = logFrameStatsBox.Checked,
- ReadbackMemexport = readbackMemexportBox.Checked,
- ReadbackMemexportFast = readbackMemexportFastBox.Checked,
- ClearMemoryPageState = clearMemoryPageStateBox.Checked,
- OcclusionQueries = occlusionQueryBox.Checked,
- AsyncShaders = asyncShadersBox.Checked,
- VSync = vsyncBox.Checked,
- VRR = vrrBox.Checked,
- MSAA = msaaBox.Checked,
- Profile = profileBox.SelectedIndex
- };
-
- string json = JsonSerializer.Serialize(
- settings,
- new JsonSerializerOptions
- {
- WriteIndented = true
- }
- );
-
- File.WriteAllText(SettingsPath, json);
- }
- catch (Exception ex)
- {
- throw new IOException("Could not save launcher settings: " + ex.Message, ex);
- }
- }
-
- private void LoadSettings()
- {
- try
- {
- if (!File.Exists(SettingsPath))
- return;
-
- var settings =
- JsonSerializer.Deserialize<LauncherSettings>(
- File.ReadAllText(SettingsPath)
- );
-
- if (settings == null)
- return;
- int languageIndex = Array.IndexOf(GameLanguageIds, settings.GameLanguage);
- gameLanguageBox.SelectedIndex = Math.Max(0, languageIndex);
-
- exePathBox.Text = settings.ExePath ?? exePathBox.Text;
- const string oldDefaultExe = @"C:\Users\Samuel M\Desktop\FIFASTREET - 2012\Jogo\FifaStreetRex\out\build\win-amd64-debug\fifastreet.exe";
- string releaseExe = oldDefaultExe.Replace("win-amd64-debug", "win-amd64-release");
- if (string.Equals(exePathBox.Text, oldDefaultExe, StringComparison.OrdinalIgnoreCase)
- && File.Exists(releaseExe))
- exePathBox.Text = releaseExe;
- gamePathBox.Text = settings.GamePath ?? gamePathBox.Text;
-
- displayModeBox.SelectedIndex =
- settings.Fullscreen ? 0 : 1;
-
- if (settings.Monitor >= 0 &&
- settings.Monitor < monitorBox.Items.Count)
- {
- monitorBox.SelectedIndex = settings.Monitor;
- }
-
- DetectDisplayModes();
-
- SelectItem(resolutionBox, settings.Resolution);
- SelectItem(refreshBox, settings.RefreshRate);
-
- if (settings.GraphicsApi >= 0 &&
- settings.GraphicsApi < graphicsApiBox.Items.Count)
- {
- graphicsApiBox.SelectedIndex = settings.GraphicsApi;
- }
-
- if (settings.GpuUsesDxgi && settings.Gpu >= 0 &&
- settings.Gpu < gpuBox.Items.Count)
- {
- gpuBox.SelectedIndex = settings.Gpu;
- }
-
- if (settings.PostEffect >= 0 &&
- settings.PostEffect < postEffectBox.Items.Count)
- {
- postEffectBox.SelectedIndex = settings.PostEffect;
- }
-if (settings.InternalResolutionScale >= 0 &&
- settings.InternalResolutionScale < internalResolutionBox.Items.Count)
-{
- internalResolutionBox.SelectedIndex = settings.InternalResolutionScale;
-}
-
- if (settings.ReadbackResolve >= 0 &&
- settings.ReadbackResolve < readbackResolveBox.Items.Count)
- readbackResolveBox.SelectedIndex = settings.ReadbackResolve;
- logFrameStatsBox.Checked = settings.LogFrameStats;
- readbackMemexportBox.Checked = settings.ReadbackMemexport;
- readbackMemexportFastBox.Checked = settings.ReadbackMemexportFast;
- clearMemoryPageStateBox.Checked = settings.ClearMemoryPageState;
- occlusionQueryBox.Checked = settings.OcclusionQueries;
- asyncShadersBox.Checked = settings.AsyncShaders;
-
- vsyncBox.Checked = settings.VSync;
- vrrBox.Checked = settings.VRR;
- msaaBox.Checked = settings.MSAA;
- if (settings.Profile >= 0 && settings.Profile < profileBox.Items.Count)
- profileBox.SelectedIndex = settings.Profile;
- }
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
- {
- // Unreadable or corrupt settings fall back to the defaults.
- Debug.WriteLine("Could not load launcher settings: " + ex.Message);
- }
- }
-
- private static void SelectItem(ComboBox box, string? value)
- {
- if (string.IsNullOrWhiteSpace(value))
- return;
-
- int index = box.Items.IndexOf(value);
-
- if (index >= 0)
- box.SelectedIndex = index;
- }
-
- private void ApplyGameLanguage(ProcessStartInfo startInfo)
- {
- int index = Math.Max(0, gameLanguageBox.SelectedIndex);
- startInfo.Environment["REX_USER_LANGUAGE"] = GameLanguageIds[index].ToString(System.Globalization.CultureInfo.InvariantCulture);
- }
-
- private sealed class MessiPicture : PictureBox
- {
- private const float CropX = 100f / 1280f;
- private const float CropY = 225f / 1819f;
- private const float CropWidth = 640f / 1280f;
-
- protected override void OnPaint(PaintEventArgs e)
- {
- if (Image == null || ClientSize.Width <= 0 || ClientSize.Height <= 0)
- return;
-
- e.Graphics.Clear(Color.FromArgb(10, 12, 16));
- e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
-
- float sourceX = Image.Width * CropX;
- float sourceY = Image.Height * CropY;
- float sourceWidth = Image.Width * CropWidth;
-
- // Preserve the same horizontal framing. Expanding the launcher
- // reveals more of the source image vertically without stretching.
- float scale = ClientSize.Width / sourceWidth;
- float sourceHeight = ClientSize.Height / scale;
- float availableHeight = Image.Height - sourceY;
- sourceHeight = Math.Min(sourceHeight, availableHeight);
-
- var sourceRect = new RectangleF(sourceX, sourceY, sourceWidth, sourceHeight);
- float destinationHeight = sourceHeight * scale;
- var destinationRect = new RectangleF(0, 0, ClientSize.Width, destinationHeight);
-
- e.Graphics.DrawImage(Image, destinationRect, sourceRect, GraphicsUnit.Pixel);
- }
- }
-}
-
-public class LauncherSettings
-{
- public string? ExePath { get; set; }
- public string? GamePath { get; set; }
- public string? Resolution { get; set; }
- public string? RefreshRate { get; set; }
- public bool Fullscreen { get; set; } = true;
- public int Monitor { get; set; }
- public int GraphicsApi { get; set; } = 0;
- public int GameLanguage { get; set; } = 1;
- public int Gpu { get; set; }
- public bool GpuUsesDxgi { get; set; }
- public int PostEffect { get; set; } = 1;
- public int ReadbackResolve { get; set; } = 0;
- public bool LogFrameStats { get; set; } = false;
- public int InternalResolutionScale { get; set; } = 0;
- public bool ReadbackMemexport { get; set; } = true;
- public bool ReadbackMemexportFast { get; set; } = true;
- public bool ClearMemoryPageState { get; set; } = false;
- public bool OcclusionQueries { get; set; } = true;
- public bool AsyncShaders { get; set; } = true;
- public bool VSync { get; set; } = false;
- public bool VRR { get; set; } = true;
- public bool MSAA { get; set; } = false;
- public int Profile { get; set; } = 0;
-}
-
-public class RoundedPanel : Panel, IFlatPanel
-{
- public Color FillColor { get; set; } = Color.FromArgb(18, 22, 28);
- public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
- public int Radius { get; set; } = 16;
-
- public RoundedPanel()
- {
- DoubleBuffered = true;
- BackColor = Color.Transparent;
- }
-
- protected override void OnPaint(PaintEventArgs e)
- {
- base.OnPaint(e);
-
- e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
-
- Rectangle rect = ClientRectangle;
- rect.Width -= 1;
- rect.Height -= 1;
-
- using var path = CreateRoundedRectangle(rect, Radius);
- using var fill = new SolidBrush(FillColor);
- using var border = new Pen(BorderColor, 1F);
-
- e.Graphics.FillPath(fill, path);
- e.Graphics.DrawPath(border, path);
- }
-
- protected override void OnResize(EventArgs eventargs)
- {
- base.OnResize(eventargs);
- Invalidate();
- }
-
- private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
- {
- int diameter = radius * 2;
-
- var path = new GraphicsPath();
-
- if (diameter <= 0)
- {
- path.AddRectangle(rect);
- return path;
- }
-
- var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
-
- path.AddArc(arc, 180, 90);
-
- arc.X = rect.Right - diameter;
- path.AddArc(arc, 270, 90);
-
- arc.Y = rect.Bottom - diameter;
- path.AddArc(arc, 0, 90);
-
- arc.X = rect.Left;
- path.AddArc(arc, 90, 90);
-
- path.CloseFigure();
-
- return path;
- }
-}
-
-public class ModernButton : Button
-{
- public Color FillColor { get; set; } = Color.FromArgb(24, 29, 36);
- public Color HoverColor { get; set; } = Color.FromArgb(34, 41, 50);
- public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
- public int Radius { get; set; } = 10;
-
- private bool hovered;
-
- public ModernButton()
- {
- FlatStyle = FlatStyle.Flat;
- FlatAppearance.BorderSize = 0;
- Cursor = Cursors.Hand;
- UseVisualStyleBackColor = false;
- DoubleBuffered = true;
- BackColor = Color.Transparent;
-
- MouseEnter += (_, _) =>
- {
- hovered = true;
- Invalidate();
- };
-
- MouseLeave += (_, _) =>
- {
- hovered = false;
- Invalidate();
- };
- }
-
- protected override void OnPaint(PaintEventArgs pevent)
- {
- pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
-
- Rectangle rect = ClientRectangle;
- rect.Width -= 1;
- rect.Height -= 1;
-
- using var path = CreateRoundedRectangle(rect, Radius);
- using var fill = new SolidBrush(hovered ? HoverColor : FillColor);
- using var border = new Pen(BorderColor, 1F);
-
- pevent.Graphics.FillPath(fill, path);
- pevent.Graphics.DrawPath(border, path);
-
- TextRenderer.DrawText(
- pevent.Graphics,
- Text,
- Font,
- ClientRectangle,
- ForeColor,
- TextFormatFlags.HorizontalCenter |
- TextFormatFlags.VerticalCenter |
- TextFormatFlags.EndEllipsis
- );
- }
-
- private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
- {
- int diameter = radius * 2;
-
- var path = new GraphicsPath();
-
- if (diameter <= 0)
- {
- path.AddRectangle(rect);
- return path;
- }
-
- var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
-
- path.AddArc(arc, 180, 90);
-
- arc.X = rect.Right - diameter;
- path.AddArc(arc, 270, 90);
-
- arc.Y = rect.Bottom - diameter;
- path.AddArc(arc, 0, 90);
-
- arc.X = rect.Left;
- path.AddArc(arc, 90, 90);
-
- path.CloseFigure();
-
- return path;
- }
-}
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using System.Windows.Forms;
+using ReStreet.Ui;
+
+namespace FifaStreetLauncher;
+
+public partial class LauncherForm : Form, ISceneHost, IUiScaled
+{
+ // Until it has finished once: starts the stadium pictures (stadium-thumbs next to the game exe) from the player's own
+ // game files, with the bundled tools\ReStreetAssetExplorer.exe, without waiting for it. Nothing from the game ships.
+ // The tool writes stadium-thumbs\.complete2 last (2: placeholder icons skipped + names.json, so older sets are redone),
+ // so an interrupted run is simply started again on the next PLAY.
+ private static void EnsureStadiumThumbs(string exeDir, string gameRoot)
+ {
+ string folder = Path.Combine(exeDir, "stadium-thumbs");
+ if (File.Exists(Path.Combine(folder, ".complete2"))) return;
+ // A run started from a previous PLAY may still be working on the same folder.
+ var running = Process.GetProcessesByName("ReStreetAssetExplorer");
+ foreach (var process in running) process.Dispose();
+ if (running.Length > 0) return;
+ string tool = Path.Combine(AppContext.BaseDirectory, "tools", "ReStreetAssetExplorer.exe");
+ if (!File.Exists(tool)) return;
+ try
+ {
+ var info = new ProcessStartInfo
+ {
+ FileName = tool,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ };
+ info.ArgumentList.Add("--stadiumpics");
+ info.ArgumentList.Add(gameRoot);
+ info.ArgumentList.Add(folder);
+ // Runs in the background so the game starts at once; the pictures show from the next session.
+ _ = Process.Start(info);
+ }
+ catch (Exception)
+ {
+ // The game still starts; the stadium picker then shows names only.
+ }
+ }
+
+ private readonly UiScaler scaler;
+ public float UiScale => scaler.Scale;
+
+ private readonly Color Bg = StreetTheme.Asphalt;
+ private readonly Color Surface = Color.FromArgb(28, 31, 36);
+ private readonly Color SurfaceAlt = StreetTheme.Field;
+ private readonly Color Border = Color.FromArgb(62, 66, 72);
+ private readonly Color Accent = StreetTheme.Yellow;
+ private readonly Color AccentHover = Color.FromArgb(255, 212, 48);
+ private readonly Color TextPrimary = StreetTheme.Ink;
+ private readonly Color TextSecondary = StreetTheme.Muted;
+
+ private readonly GlassCombo resolutionBox = new();
+ private readonly GlassCombo refreshBox = new();
+ private readonly GlassCombo displayModeBox = new();
+ private readonly GlassCombo monitorBox = new();
+ private readonly GlassCombo graphicsApiBox = new();
+ private readonly GlassCombo gpuBox = new();
+ private readonly List<int> gpuAdapterIndices = new();
+ private readonly GlassCombo postEffectBox = new();
+ private readonly GlassCombo internalResolutionBox = new();
+ private readonly GlassCombo gameLanguageBox = new();
+ private readonly GlassCombo readbackResolveBox = new();
+ private readonly GlassCombo profileBox = new();
+ private bool applyingProfile;
+ private static readonly string[] ProfileNames =
+ {
+ "Balanced (default)",
+ "Quality (strong PCs)",
+ "Performance (weak PCs)",
+ "Custom"
+ };
+ private static readonly string[] ReadbackResolveModes = { "full", "some", "fast", "none" };
+ // Xbox language ids; PtBrLanguageId is ReStreet's Brazilian Portuguese: English to the game (the translation takes
+ // the English slot) plus FIFASTREET_GAME_LANGUAGE=pt-BR, which loads locale_ptbr.big and shows cm/kg.
+ private const int PtBrLanguageId = 1001;
+ private static readonly int[] GameLanguageIds = { 1, 5, 4, 3, 6, PtBrLanguageId };
+
+ private readonly GlassToggle vsyncBox = new();
+ private readonly GlassToggle vrrBox = new();
+ private readonly GlassToggle msaaBox = new();
+ private readonly GlassToggle readbackMemexportBox = new();
+ private readonly GlassToggle readbackMemexportFastBox = new();
+ private readonly GlassToggle clearMemoryPageStateBox = new();
+ private readonly GlassToggle occlusionQueryBox = new();
+ private readonly GlassToggle asyncShadersBox = new();
+ private readonly GlassToggle logFrameStatsBox = new();
+
+ private readonly TextBox gamePathBox = new();
+ private readonly TextBox exePathBox = new();
+
+ private readonly ThemedLabel statusLabel = new();
+ private readonly ThemedLabel hardwareLabel = new();
+ private readonly Label advancedChevron = new();
+
+ private readonly RoundedPanel advancedPanel = new();
+ private readonly SlantButton advancedButton = new();
+ private readonly RoundedPanel compatibilityPanel = new();
+ private readonly SlantButton compatibilityButton = new();
+
+ private bool gameRunning;
+ private Process? gameProcess; // the game this launcher started, while it runs
+ private bool closeAfterGame;
+ private DiscordPresence? discord;
+ private System.Windows.Forms.Timer? presenceTimer;
+ private string? changedDisplay;
+ private DEVMODE previousDisplayMode;
+ private bool advancedVisible;
+ private bool compatibilityVisible;
+
+ private string SettingsPath =>
+ Path.Combine(AppContext.BaseDirectory, "settings.json");
+
+ public LauncherForm()
+ {
+ Text = "ReStreet Launcher";
+ using (var icon = typeof(LauncherForm).Assembly.GetManifestResourceStream("fifastreet.ico")!)
+ Icon = new Icon(icon);
+ ClientSize = new Size(1250, 720);
+ scaler = new UiScaler(this, 1250, 720);
+ DoubleBuffered = true;
+ ResizeRedraw = true;
+ HandleCreated += (_, _) => StreetTheme.ApplyDarkTitleBar(Handle);
+ StartPosition = FormStartPosition.CenterScreen;
+ FormBorderStyle = FormBorderStyle.FixedSingle;
+ MaximizeBox = false;
+ BackColor = Bg;
+ ForeColor = TextPrimary;
+ Font = new Font("Segoe UI", 10F);
+
+ BuildInterface();
+ WireEvents();
+ applyingProfile = true; // loading values must not flip the profile to Custom
+ LoadDefaults();
+ profileBox.SelectedIndex = 0;
+ LoadSettings();
+ InitDeckOptions();
+ applyingProfile = false;
+ UpdateGraphicsApiState();
+ UpdateRefreshRates();
+ UpdateSummary();
+ UpdateStatus(ReadyText(), true);
+ scaler.Capture();
+ // Stay invisible until the new page has loaded, so the classic controls underneath never flash on screen.
+ if (Environment.GetEnvironmentVariable("RESTREET_CLASSIC_UI") != "1") Opacity = 0;
+ Shown += (_, _) => { InitGlassUi(); _ = CheckForUpdateAsync(); };
+ }
+
+ // Layout on an 8 px grid (design pixels, window 1250 x 720): left column margin 48; glass sheet
+ // 620..1202 x 32..688 (margin 48 / 32) with 24 px padding, so content spans x 644..1178 as two
+ // 259 px columns with a 16 px gap. Captions are 16 high, fields 36, buttons 40.
+ private const float DesignW = 1250f, DesignH = 720f;
+ private const int Left = 48;
+ private const int SheetX = 620, SheetY = 32, SheetW = 582, SheetH = 656, Pad = 24;
+ private const int ContentX = SheetX + Pad, ContentW = SheetW - 2 * Pad;
+ private const int ColW = 259, Col1 = ContentX, Col2 = ContentX + ColW + 16;
+ private const int PanelY = 720, PanelX = Left, PanelW = 1154;
+ private Bitmap? scene;
+ private Size sceneSize;
+
+ public Bitmap SceneBitmap { get { BuildScene(); return scene!; } }
+
+ protected override void OnPaintBackground(PaintEventArgs e)
+ {
+ BuildScene();
+ using (var floor = new SolidBrush(StreetTheme.Asphalt)) e.Graphics.FillRectangle(floor, ClientRectangle);
+ e.Graphics.DrawImageUnscaled(scene!, 0, 0);
+ }
+
+ // Court backdrop, glass sheet, wordmark and credit, painted once per window size.
+ private void BuildScene()
+ {
+ float s = ClientSize.Width / DesignW;
+ var size = new Size(ClientSize.Width, (int)Math.Ceiling(DesignH * s));
+ if (scene != null && sceneSize == size) return;
+ scene?.Dispose();
+ sceneSize = size;
+ try
+ {
+ BuildSceneFull(size, s);
+ }
+ catch (Exception ex) when (ex is NotImplementedException or ArgumentException or System.Runtime.InteropServices.ExternalException or OutOfMemoryException or InvalidOperationException)
+ {
+ // Last resort (seen on Wine/Proton): a plain background, so the controls still draw on top of it.
+ scene?.Dispose();
+ scene = new Bitmap(Math.Max(1, size.Width), Math.Max(1, size.Height));
+ using var g = Graphics.FromImage(scene);
+ g.Clear(StreetTheme.Asphalt);
+ }
+ }
+
+ private void BuildSceneFull(Size size, float s)
+ {
+ using var backdrop = StreetTheme.RenderBackdrop(size, DesignW, DesignH);
+ using var blurred = StreetTheme.Blur(backdrop, 10);
+ scene = new Bitmap(backdrop);
+ using var g = Graphics.FromImage(scene);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
+ g.ScaleTransform(s, s);
+
+ StreetTheme.DrawGlass(g, blurred, s, new RectangleF(SheetX, SheetY, SheetW, SheetH), 14);
+ StreetTheme.DrawSection(g, "GENERAL", ContentX, 56, ContentX + ContentW);
+ StreetTheme.DrawSection(g, "DISPLAY", ContentX, 166, ContentX + ContentW);
+ StreetTheme.DrawSection(g, "GRAPHICS", ContentX, 350, ContentX + ContentW);
+ using (var line = new Pen(StreetTheme.Hairline, 1f)) g.DrawLine(line, ContentX, 607.5f, ContentX + ContentW, 607.5f);
+ // Status block: yellow rule beside the hardware summary and the online status.
+ using (var rule = new SolidBrush(StreetTheme.Yellow)) g.FillRectangle(rule, Left, 314, 3, 52);
+ using (var line = new Pen(StreetTheme.Hairline, 1f)) g.DrawLine(line, Left, 627.5f, Left + 480, 627.5f);
+
+ using (var small = new Font(StreetTheme.CondensedFamily, 17, FontStyle.Bold, GraphicsUnit.Pixel))
+ using (var yellow = new SolidBrush(StreetTheme.Yellow))
+ StreetTheme.DrawSpaced(g, "FIFA STREET 2012 RECOMPILED", small, yellow, new PointF(Left, 56), 3.6f);
+ StreetTheme.DrawWordmark(g, "ReStreet", new PointF(Left, 88), 178, StreetTheme.Ink);
+ var tag = new RectangleF(Left, 240, 270, 36);
+ using (var bar = new SolidBrush(StreetTheme.Yellow)) g.FillPolygon(bar, StreetTheme.Slant(tag, 12));
+ using (var tagFont = new Font(StreetTheme.CondensedFamily, 18, FontStyle.Bold, GraphicsUnit.Pixel))
+ using (var dark = new SolidBrush(StreetTheme.YellowDark))
+ StreetTheme.DrawSpaced(g, "V" + LauncherVersion + " · ONLINE BETA", tagFont, dark, new PointF(Left + 14, 246), 2.8f);
+
+ using var name = new Font("Segoe UI", 15, FontStyle.Regular, GraphicsUnit.Pixel);
+ StreetTheme.DrawLabelValue(g, "Ported by:", "SamuelitoDaVila", name, StreetTheme.Ink, StreetTheme.Ink, Left, 642);
+ StreetTheme.DrawLabelValue(g, "Contributions:", "Emran_Ahm3d", name, StreetTheme.Muted, StreetTheme.Muted, Left, 665);
+ }
+
+ // online.json is written by the online patch, next to this launcher.
+ internal static (string Server, string Name, string Key)? LoadOnlineConfig()
+ {
+ try
+ {
+ string path = Path.Combine(AppContext.BaseDirectory, "online.json");
+ if (!File.Exists(path)) return null;
+ using var doc = JsonDocument.Parse(File.ReadAllText(path));
+ string? server = doc.RootElement.TryGetProperty("server", out var s) ? s.GetString() : null;
+ string? name = doc.RootElement.TryGetProperty("name", out var n) ? n.GetString() : null;
+ string? key = doc.RootElement.TryGetProperty("key", out var k) ? k.GetString() : null;
+ return string.IsNullOrWhiteSpace(server) || string.IsNullOrWhiteSpace(name) ? null : (server.Trim(), name.Trim(), (key ?? "").Trim());
+ }
+ catch (Exception error) when (error is IOException or JsonException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
+ private string ReadyText()
+ {
+ var online = LoadOnlineConfig();
+ if (online != null && !onlineModeBox.Checked) return "Ready to play offline (online is off)";
+ return online == null ? "Online is not set up. Run the online patch again" : "Ready to play online as " + online.Value.Name;
+ }
+
+ private void BuildInterface()
+ {
+ SuspendLayout();
+
+ // Three sections (titles painted in BuildScene at y 56 / 166 / 350). A field is a 16 px caption,
+ // 6 px gap and a 36 px box; rows inside a section are 74 apart.
+ void Field(string label, ComboBox box, int x, int y)
+ {
+ AddFieldLabel(this, label, x, y);
+ ConfigureCombo(box, x, y + 22, ColW);
+ Controls.Add(box);
+ }
+ Field("Profile", profileBox, Col1, 84);
+ profileBox.AccessibleName = "Performance profile";
+ profileBox.Items.AddRange(ProfileNames);
+ profileBox.SelectedIndex = 0;
+ profileBox.SelectedIndexChanged += (_, _) => ApplyProfile();
+ postEffectBox.SelectedIndexChanged += (_, _) => MarkCustomProfile();
+ internalResolutionBox.SelectedIndexChanged += (_, _) => MarkCustomProfile();
+ readbackResolveBox.SelectedIndexChanged += (_, _) => MarkCustomProfile();
+ msaaBox.CheckedChanged += (_, _) => MarkCustomProfile();
+ occlusionQueryBox.CheckedChanged += (_, _) => MarkCustomProfile();
+
+ Field("Game language", gameLanguageBox, Col2, 84);
+ gameLanguageBox.AccessibleName = "Game language";
+ Field("Resolution", resolutionBox, Col1, 194);
+ Field("Refresh rate", refreshBox, Col2, 194);
+ Field("Display mode", displayModeBox, Col1, 268);
+ Field("Monitor", monitorBox, Col2, 268);
+ Field("Graphics API", graphicsApiBox, Col1, 378);
+ Field("GPU", gpuBox, Col2, 378);
+ Field("Post-processing", postEffectBox, Col1, 452);
+ Field("Internal resolution", internalResolutionBox, Col2, 452);
+
+ // Switches in one row, 24 px apart.
+ vsyncBox.CheckedChanged += (_, _) => UpdateGraphicsApiState();
+ readbackMemexportBox.CheckedChanged += (_, _) => UpdateGraphicsApiState();
+ int switchX = Col1;
+ foreach (var (box, text) in new (GlassToggle, string)[] { (vsyncBox, "VSync"), (vrrBox, "VRR / Tearing (D3D12)"), (msaaBox, "Native 2x MSAA") })
+ {
+ ConfigureCheck(box, text, switchX, 526);
+ Controls.Add(box);
+ switchX += box.GetPreferredSize(Size.Empty).Width + 24;
+ }
+
+ var tip = new ThemedLabel
+ {
+ Text = "Weaker PC? Pick the Performance profile.",
+ ForeColor = TextSecondary,
+ Font = StreetTheme.Body(10F),
+ Bounds = new Rectangle(ContentX, 568, ContentW, 20)
+ };
+ Controls.Add(tip);
+
+ // Bottom row: five equal buttons, 100 wide with 8 px gaps (5 x 100 + 4 x 8 = 532).
+ void Chip(SlantButton button, string text, int index)
+ {
+ button.Kind = SlantKind.Glass;
+ button.Text = text;
+ button.Font = StreetTheme.Body(10F);
+ button.Bounds = new Rectangle(ContentX + index * 108, 624, 100, 40);
+ Controls.Add(button);
+ }
+ Chip(advancedButton, "Advanced", 0);
+ Chip(compatibilityButton, "Compatibility", 1);
+ var logsButton = new SlantButton();
+ logsButton.Click += (_, _) => OpenLogs();
+ Chip(logsButton, "Open logs", 2);
+ var folderButton = new SlantButton();
+ folderButton.Click += (_, _) => OpenGameFolder();
+ Chip(folderButton, "Open folder", 3);
+ var shortcutButton = new SlantButton();
+ shortcutButton.Click += (_, _) => CreateDesktopShortcut();
+ Chip(shortcutButton, "Shortcut", 4);
+
+ ConfigureAdvancedPanel();
+ Controls.Add(advancedPanel);
+
+ ConfigureCompatibilityPanel();
+ Controls.Add(compatibilityPanel);
+
+ hardwareLabel.Text = "Detecting hardware...";
+ hardwareLabel.ForeColor = TextSecondary;
+ hardwareLabel.Font = StreetTheme.Body(11F);
+ hardwareLabel.AutoEllipsis = true;
+ hardwareLabel.TextAlign = ContentAlignment.MiddleLeft;
+ hardwareLabel.Bounds = new Rectangle(Left + 16, 314, 496, 24);
+ Controls.Add(hardwareLabel);
+
+ statusLabel.Font = StreetTheme.Body(11F, FontStyle.Bold);
+ statusLabel.ForeColor = TextSecondary;
+ statusLabel.TextAlign = ContentAlignment.MiddleLeft;
+ statusLabel.Bounds = new Rectangle(Left + 16, 342, 496, 24);
+ Controls.Add(statusLabel);
+
+ var playButton = new SlantButton
+ {
+ Kind = SlantKind.Primary,
+ Text = "PLAY",
+ Font = StreetTheme.Condensed(36, FontStyle.Bold),
+ Bounds = new Rectangle(Left, 520, 480, 88)
+ };
+ playButton.Click += (_, _) => LaunchGame();
+ Controls.Add(playButton);
+ if (LoadOnlineConfig() != null)
+ {
+ // Online build: PLAY shares its row with the lobby and the friends list.
+ playButton.Width = 240;
+ var lobbyButton = new SlantButton
+ {
+ Kind = SlantKind.Glass,
+ Text = "LOBBY",
+ Font = StreetTheme.Condensed(22, FontStyle.Bold),
+ Bounds = new Rectangle(Left + 240 + 8, 520, 112, 88)
+ };
+ lobbyButton.Click += (_, _) =>
+ {
+ var current = LoadOnlineConfig();
+ if (current == null) return;
+ using var lobby = new LobbyForm(current.Value.Server, current.Value.Name);
+ lobby.ShowDialog(this);
+ };
+ Controls.Add(lobbyButton);
+ var friendsButton = new SlantButton
+ {
+ Kind = SlantKind.Glass,
+ Text = "FRIENDS",
+ Font = StreetTheme.Condensed(22, FontStyle.Bold),
+ Bounds = new Rectangle(Left + 240 + 8 + 112 + 8, 520, 112, 88)
+ };
+ friendsButton.Click += (_, _) =>
+ {
+ var current = LoadOnlineConfig();
+ if (current == null) return;
+ using var friends = new FriendsForm(current.Value.Server, current.Value.Name, current.Value.Key);
+ friends.ShowDialog(this);
+ };
+ Controls.Add(friendsButton);
+ }
+ AcceptButton = playButton;
+ ActiveControl = playButton;
+
+ ResumeLayout(false);
+ PerformLayout();
+ }
+
+ private void ConfigureAdvancedPanel()
+ {
+ advancedPanel.Bounds = new Rectangle(PanelX, PanelY, PanelW, 192);
+ advancedPanel.FillColor = StreetTheme.PanelFlat;
+ advancedPanel.BorderColor = Color.FromArgb(52, 55, 60);
+ advancedPanel.Radius = 14;
+ advancedPanel.Visible = false;
+
+ const int browseW = 96, gap = 8, innerW = PanelW - 2 * Pad;
+ void PathRow(string label, TextBox box, int y, Action browse)
+ {
+ AddFieldLabel(advancedPanel, label, Pad, y);
+ advancedPanel.Controls.Add(new FieldFrame(box) { Bounds = new Rectangle(Pad, y + 24, innerW - browseW - gap, 40) });
+ box.Font = StreetTheme.Body(10F);
+ var button = new SlantButton { Kind = SlantKind.Glass, Text = "Browse", Font = StreetTheme.Body(10F), Bounds = new Rectangle(Pad + innerW - browseW, y + 24, browseW, 40) };
+ button.Click += (_, _) => browse();
+ advancedPanel.Controls.Add(button);
+ }
+ PathRow("Game executable", exePathBox, Pad, BrowseExe);
+ PathRow("Game data folder", gamePathBox, Pad + 80, BrowseGame);
+ }
+
+ private void ConfigureCompatibilityPanel()
+ {
+ compatibilityPanel.Bounds = new Rectangle(PanelX, PanelY, PanelW, 248);
+ compatibilityPanel.FillColor = StreetTheme.PanelFlat;
+ compatibilityPanel.BorderColor = Color.FromArgb(52, 55, 60);
+ compatibilityPanel.Radius = 14;
+ compatibilityPanel.Visible = false;
+
+ compatibilityPanel.Controls.Add(new ThemedLabel
+ {
+ Text = "COMPATIBILITY", Font = StreetTheme.Condensed(12F, FontStyle.Bold), ForeColor = StreetTheme.Yellow,
+ Bounds = new Rectangle(Pad, Pad, 400, 24)
+ });
+ compatibilityPanel.Controls.Add(new ThemedLabel
+ {
+ Text = "Renderer options for textures, lighting, black screens and stutter.", Font = StreetTheme.Body(10F), ForeColor = TextSecondary,
+ Bounds = new Rectangle(Pad, Pad + 28, 800, 20)
+ });
+
+ AddFieldLabel(compatibilityPanel, "Readback Resolve", Pad, 92);
+ ConfigureCombo(readbackResolveBox, Pad, 116, ColW);
+ readbackResolveBox.AccessibleName = "Readback Resolve";
+ compatibilityPanel.Controls.Add(readbackResolveBox);
+
+ // Switches on the same 275 px column pitch as the main sheet (x = 299, 574, 849).
+ int[] cols = { Pad + 275, Pad + 550, Pad + 825 };
+ ConfigureCheck(readbackMemexportBox, "Memory Export", cols[0], 120);
+ ConfigureCheck(readbackMemexportFastBox, "Fast MemExport", cols[1], 120);
+ ConfigureCheck(clearMemoryPageStateBox, "Memory Page State", cols[2], 120);
+ ConfigureCheck(occlusionQueryBox, "Occlusion Queries", cols[0], 162);
+ ConfigureCheck(asyncShadersBox, "Async Shaders", cols[1], 162);
+ ConfigureCheck(logFrameStatsBox, "Frame stats log", cols[2], 162);
+ foreach (var box in new[] { readbackMemexportBox, readbackMemexportFastBox, clearMemoryPageStateBox, occlusionQueryBox, asyncShadersBox, logFrameStatsBox })
+ compatibilityPanel.Controls.Add(box);
+
+ compatibilityPanel.Controls.Add(new ThemedLabel
+ {
+ Text = "Readback Resolve: Some is the recommended mode (more FPS with the validated fixes). Full is the most compatible; Fast gives more FPS but may cause graphical corruption.",
+ Font = StreetTheme.Body(10F), ForeColor = TextSecondary,
+ Bounds = new Rectangle(Pad, 204, PanelW - 2 * Pad, 20)
+ });
+ }
+
+ private void WireEvents()
+ {
+ advancedButton.Click += (_, _) => ToggleAdvanced();
+ advancedChevron.Click += (_, _) => ToggleAdvanced();
+ compatibilityButton.Click += (_, _) => ToggleCompatibility();
+ onlineModeBox.CheckedChanged += (_, _) =>
+ {
+ if (applyingProfile) return; // loading settings.json, not a player's change
+ if (!gameRunning) UpdateStatus(ReadyText(), true);
+ try { SaveSettings(); }
+ catch (IOException ex) { Debug.WriteLine(ex.Message); }
+ };
+
+ monitorBox.SelectedIndexChanged += (_, _) =>
+ {
+ DetectDisplayModes();
+ UpdateSummary();
+ };
+
+ graphicsApiBox.SelectedIndexChanged += (_, _) =>
+ {
+ UpdateGraphicsApiState();
+ UpdateSummary();
+ };
+
+ resolutionBox.SelectedIndexChanged += (_, _) => { UpdateRefreshRates(); UpdateSummary(); };
+internalResolutionBox.SelectedIndexChanged += (_, _) =>
+{
+ UpdateSummary();
+ if (!gameRunning)
+ UpdateStatus(internalResolutionBox.SelectedIndex >= 2
+ ? "High internal resolution may reduce FPS"
+ : ReadyText(), true);
+};
+refreshBox.SelectedIndexChanged += (_, _) => UpdateSummary();
+gpuBox.SelectedIndexChanged += (_, _) => UpdateSummary();
+
+gpuBox.DropDown += (_, _) =>
+{
+ int width = gpuBox.Width;
+
+ using Graphics graphics = gpuBox.CreateGraphics();
+
+ foreach (var item in gpuBox.Items)
+ {
+ int itemWidth = (int)Math.Ceiling(
+ graphics.MeasureString(
+ item?.ToString() ?? string.Empty,
+ gpuBox.Font).Width);
+
+ width = Math.Max(width, itemWidth + 40);
+ }
+
+ gpuBox.DropDownWidth = Math.Min(width, 500);
+};
+displayModeBox.SelectedIndexChanged += (_, _) => { UpdateRefreshRates(); UpdateSummary(); };
+ }
+
+ private void ToggleAdvanced()
+ {
+ if (compatibilityVisible)
+ {
+ compatibilityVisible = false;
+ compatibilityPanel.Visible = false;
+ }
+
+ advancedVisible = !advancedVisible;
+ advancedPanel.Visible = advancedVisible;
+ advancedChevron.Text = advancedVisible ? "⌃" : "⌄";
+ advancedButton.Active = advancedVisible;
+ compatibilityButton.Active = compatibilityVisible;
+
+ if (advancedVisible)
+ {
+ scaler.DesignHeight = 944;
+ }
+ else
+ {
+ scaler.DesignHeight = 720;
+ }
+ }
+
+ private void ToggleCompatibility()
+ {
+ if (advancedVisible)
+ {
+ advancedVisible = false;
+ advancedPanel.Visible = false;
+ advancedChevron.Text = "⌄";
+ }
+
+ compatibilityVisible = !compatibilityVisible;
+ compatibilityPanel.Visible = compatibilityVisible;
+ compatibilityButton.Active = compatibilityVisible;
+ advancedButton.Active = advancedVisible;
+
+ if (compatibilityVisible)
+ {
+ scaler.DesignHeight = 1000;
+ }
+ else
+ {
+ scaler.DesignHeight = 720;
+ }
+ }
+
+ private void MoveBottomControls(int secondaryY, int playY, int footerY)
+ {
+ foreach (Control control in Controls)
+ {
+ if (control is ModernButton button)
+ {
+ if (button.Text == "OPEN LOGS" || button.Text == "OPEN FOLDER")
+ button.Top = secondaryY;
+ else if (button.Text == "PLAY")
+ button.Top = playY;
+ }
+ else if (control is Label label &&
+ (label.Text.StartsWith("ReStreet •", StringComparison.Ordinal) || label.Tag as string == "credit"))
+ {
+ label.Top = footerY;
+ }
+ }
+ }
+
+ private RoundedPanel CreateCard(Point location, Size size)
+ {
+ return new RoundedPanel
+ {
+ Location = location,
+ Size = size,
+ FillColor = Surface,
+ BorderColor = Border,
+ Radius = 16
+ };
+ }
+
+ private void AddSectionHeader(Control parent, string title, string subtitle, int x, int y)
+ {
+ var titleLabel = new Label
+ {
+ Text = title,
+ ForeColor = TextPrimary,
+ Font = new Font("Segoe UI Semibold", 11F, FontStyle.Bold),
+ AutoSize = true,
+ Location = new Point(x, y)
+ };
+ parent.Controls.Add(titleLabel);
+
+ var subtitleLabel = new Label
+ {
+ Text = subtitle,
+ ForeColor = TextSecondary,
+ Font = new Font("Segoe UI", 8.8F),
+ AutoSize = true,
+ Location = new Point(x, y + 26)
+ };
+ parent.Controls.Add(subtitleLabel);
+ }
+
+ private void AddFieldLabel(Control parent, string text, int x, int y)
+ {
+ parent.Controls.Add(new ThemedLabel
+ {
+ Text = text.ToUpperInvariant(),
+ ForeColor = TextSecondary,
+ Font = StreetTheme.Condensed(8.5F, FontStyle.Bold),
+ Bounds = new Rectangle(x, y, ColW, 16)
+ });
+ }
+
+ private void ConfigureCombo(ComboBox box, int x, int y, int width)
+ {
+ box.Bounds = new Rectangle(x, y, width, 36);
+ box.DropDownHeight = 240;
+ }
+
+ private void ConfigureCheck(CheckBox box, string text, int x, int y)
+ {
+ box.Text = text;
+ box.Location = new Point(x, y);
+ box.AutoSize = true;
+ box.ForeColor = TextPrimary;
+ box.BackColor = Color.Transparent;
+ box.Font = StreetTheme.Body(10F);
+ box.Cursor = Cursors.Hand;
+ }
+
+ private void StyleTextBox(TextBox box)
+ {
+ box.BackColor = SurfaceAlt;
+ box.ForeColor = TextPrimary;
+ box.BorderStyle = BorderStyle.FixedSingle;
+ box.Font = new Font("Segoe UI", 9F);
+ }
+
+ private void LoadDefaults()
+ {
+ // 1.5.5 layout: Binaries\ (exe, DLLs, Logs) and Game\ (the game's files); older installs had Game\ + GameData\.
+ bool oldLayout = !Directory.Exists(Path.Combine(AppContext.BaseDirectory, "Binaries")) &&
+ Directory.Exists(Path.Combine(AppContext.BaseDirectory, "GameData"));
+ exePathBox.Text =
+ Path.Combine(AppContext.BaseDirectory, oldLayout ? "Game" : "Binaries", "fifastreet.exe");
+
+ gamePathBox.Text =
+ Path.Combine(AppContext.BaseDirectory, oldLayout ? "GameData" : "Game");
+
+ displayModeBox.Items.AddRange(new object[]
+ {
+ "Fullscreen",
+ "Windowed"
+ });
+ displayModeBox.SelectedIndex = 0;
+
+ graphicsApiBox.Items.AddRange(new object[]
+ {
+ "Direct3D 12",
+ "Vulkan"
+ });
+ graphicsApiBox.SelectedIndex = 0;
+ gameLanguageBox.Items.AddRange(new object[] { "English", "Español", "Français", "Deutsch", "Italiano", "Português (Brasil)" });
+ gameLanguageBox.SelectedIndex = 0;
+
+ readbackResolveBox.Items.AddRange(new object[]
+ {
+ "Full (compatible)",
+ "Some (recommended)",
+ "Fast (more FPS, may glitch)",
+ "None (experimental)"
+ });
+ readbackResolveBox.SelectedIndex = 1;
+
+ monitorBox.Items.Clear();
+ foreach (var screen in Screen.AllScreens)
+ {
+ string primary = screen.Primary ? " • Primary" : "";
+ monitorBox.Items.Add(
+ $"{monitorBox.Items.Count}: {screen.DeviceName}{primary}"
+ );
+ }
+
+ if (monitorBox.Items.Count > 0)
+ monitorBox.SelectedIndex = Math.Max(0, Array.FindIndex(Screen.AllScreens, screen => screen.Primary));
+
+ DetectDisplayModes();
+ DetectGpus();
+
+ postEffectBox.Items.AddRange(new object[]
+{
+ "None",
+ "FXAA",
+ "FXAA Extreme"
+});
+ postEffectBox.SelectedIndex = 1;
+
+ internalResolutionBox.Items.AddRange(new object[]
+{
+ "1x - Native (1280 x 720)",
+ "2x - 2560 x 1440",
+ "3x - 3840 x 2160",
+ "4x - 5120 x 2880"
+});
+ internalResolutionBox.SelectedIndex = 0;
+
+
+ readbackMemexportBox.Checked = true;
+ readbackMemexportFastBox.Checked = true;
+ clearMemoryPageStateBox.Checked = false;
+ logFrameStatsBox.Checked = false;
+ occlusionQueryBox.Checked = false;
+ asyncShadersBox.Checked = true;
+
+ vsyncBox.Checked = false;
+ vrrBox.Checked = true;
+ msaaBox.Checked = false;
+ }
+
+ private void DetectGpus()
+ {
+ gpuBox.Items.Clear();
+ gpuAdapterIndices.Clear();
+ gpuBox.Items.Add("Automatic");
+ gpuAdapterIndices.Add(-1);
+
+ try
+ {
+ foreach (var gpu in DxgiAdapters.Enumerate())
+ {
+ gpuBox.Items.Add(
+ $"Adapter {gpu.Index}: {gpu.Name}"
+ );
+ gpuAdapterIndices.Add(checked((int)gpu.Index));
+ }
+ }
+ catch
+ {
+ // Automatic selection remains available when DXGI enumeration fails.
+ }
+
+ gpuBox.Items.Add("WARP (Software)");
+ gpuAdapterIndices.Add(-2);
+ gpuBox.SelectedIndex = 0;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
+ private struct DEVMODE
+ {
+ private const int CCHDEVICENAME = 32;
+ private const int CCHFORMNAME = 32;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
+ public string dmDeviceName;
+
+ public short dmSpecVersion;
+ public short dmDriverVersion;
+ public short dmSize;
+ public short dmDriverExtra;
+ public int dmFields;
+
+ public int dmPositionX;
+ public int dmPositionY;
+ public int dmDisplayOrientation;
+ public int dmDisplayFixedOutput;
+
+ public short dmColor;
+ public short dmDuplex;
+ public short dmYResolution;
+ public short dmTTOption;
+ public short dmCollate;
+
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]
+ public string dmFormName;
+
+ public short dmLogPixels;
+ public int dmBitsPerPel;
+ public int dmPelsWidth;
+ public int dmPelsHeight;
+ public int dmDisplayFlags;
+ public int dmDisplayFrequency;
+
+ public int dmICMMethod;
+ public int dmICMIntent;
+ public int dmMediaType;
+ public int dmDitherType;
+ public int dmReserved1;
+ public int dmReserved2;
+ public int dmPanningWidth;
+ public int dmPanningHeight;
+ }
+
+ [DllImport("user32.dll", CharSet = CharSet.Ansi)]
+ private static extern bool EnumDisplaySettings(
+ string deviceName,
+ int modeNum,
+ ref DEVMODE devMode
+ );
+
+ private const int ENUM_CURRENT_SETTINGS = -1;
+
+ private void DetectDisplayModes()
+ {
+ string? oldResolution = resolutionBox.SelectedItem?.ToString();
+ string? oldRefresh = refreshBox.SelectedItem?.ToString();
+
+ resolutionBox.Items.Clear();
+ refreshBox.Items.Clear();
+
+ var resolutions = new HashSet<string>();
+ var refreshRates = new SortedSet<int>();
+
+ Screen screen =
+ monitorBox.SelectedIndex >= 0 &&
+ monitorBox.SelectedIndex < Screen.AllScreens.Length
+ ? Screen.AllScreens[monitorBox.SelectedIndex]
+ : Screen.PrimaryScreen!;
+
+ int modeNum = 0;
+
+ while (true)
+ {
+ DEVMODE mode = CreateDevMode();
+
+ if (!EnumDisplaySettings(
+ screen.DeviceName,
+ modeNum,
+ ref mode))
+ {
+ break;
+ }
+
+ if (mode.dmPelsWidth >= 1280 &&
+ mode.dmPelsHeight >= 720 &&
+ mode.dmBitsPerPel >= 32)
+ {
+ resolutions.Add(
+ $"{mode.dmPelsWidth}x{mode.dmPelsHeight}"
+ );
+
+ if (mode.dmDisplayFrequency > 20 &&
+ mode.dmDisplayFrequency < 1000)
+ {
+ refreshRates.Add(mode.dmDisplayFrequency);
+ }
+ }
+
+ modeNum++;
+ }
+
+ // Always expose common output resolutions up to 4K,
+ // even when the current monitor does not advertise them.
+ resolutions.Add("1280x720");
+ resolutions.Add("1920x1080");
+ resolutions.Add("2560x1440");
+ resolutions.Add("3200x1800");
+ resolutions.Add("3840x2160");
+
+ foreach (string resolution in resolutions
+ .OrderBy(x =>
+ {
+ var p = x.Split('x');
+ return int.Parse(p[0]) * int.Parse(p[1]);
+ }))
+ {
+ resolutionBox.Items.Add(resolution);
+ }
+
+ foreach (int hz in refreshRates)
+ {
+ refreshBox.Items.Add(hz.ToString());
+ }
+
+ if (resolutionBox.Items.Count == 0)
+ {
+ resolutionBox.Items.AddRange(new object[]
+ {
+ "1280x720",
+ "1600x900",
+ "1920x1080",
+ "2560x1440",
+ "3200x1800",
+ "3840x2160"
+ });
+ }
+
+ if (refreshBox.Items.Count == 0)
+ {
+ refreshBox.Items.AddRange(new object[]
+ {
+ "30", "50", "60", "75", "100",
+ "120", "144", "165", "180", "200", "240"
+ });
+ }
+
+ if (!string.IsNullOrWhiteSpace(oldResolution) &&
+ resolutionBox.Items.Contains(oldResolution))
+ {
+ resolutionBox.SelectedItem = oldResolution;
+ }
+ else
+ {
+ string currentResolution =
+ $"{screen.Bounds.Width}x{screen.Bounds.Height}";
+
+ if (resolutionBox.Items.Contains(currentResolution))
+ resolutionBox.SelectedItem = currentResolution;
+ else if (resolutionBox.Items.Count > 0)
+ resolutionBox.SelectedIndex = resolutionBox.Items.Count - 1;
+ }
+
+ if (!string.IsNullOrWhiteSpace(oldRefresh) &&
+ refreshBox.Items.Contains(oldRefresh))
+ {
+ refreshBox.SelectedItem = oldRefresh;
+ }
+ else
+ {
+ DEVMODE currentMode = CreateDevMode();
+
+ if (EnumDisplaySettings(
+ screen.DeviceName,
+ ENUM_CURRENT_SETTINGS,
+ ref currentMode))
+ {
+ string currentHz =
+ currentMode.dmDisplayFrequency.ToString();
+
+ if (refreshBox.Items.Contains(currentHz))
+ refreshBox.SelectedItem = currentHz;
+ }
+
+ if (refreshBox.SelectedIndex < 0 &&
+ refreshBox.Items.Count > 0)
+ {
+ refreshBox.SelectedIndex = 0;
+ }
+ }
+ }
+
+ private void UpdateRefreshRates()
+ {
+ if (monitorBox.SelectedIndex < 0 || resolutionBox.SelectedIndex < 0) return;
+ string previous = refreshBox.Text;
+ Screen screen = Screen.AllScreens[monitorBox.SelectedIndex];
+ DEVMODE desktop = CreateDevMode();
+ if (!EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref desktop)) return;
+ string[] size = resolutionBox.Text.Split('x');
+ if (size.Length != 2 || !int.TryParse(size[0], out int width) ||
+ !int.TryParse(size[1], out int height)) return;
+ if (displayModeBox.SelectedIndex != 0) {
+ width = desktop.dmPelsWidth;
+ height = desktop.dmPelsHeight;
+ }
+ var rates = new SortedSet<int>();
+ for (int i = 0; ; i++) {
+ DEVMODE mode = CreateDevMode();
+ if (!EnumDisplaySettings(screen.DeviceName, i, ref mode)) break;
+ if (mode.dmPelsWidth == width && mode.dmPelsHeight == height &&
+ mode.dmBitsPerPel >= 32 && mode.dmDisplayFrequency > 20)
+ rates.Add(mode.dmDisplayFrequency);
+ }
+ refreshBox.Items.Clear();
+ foreach (int rate in rates) refreshBox.Items.Add(rate.ToString());
+ if (refreshBox.Items.Contains(previous)) refreshBox.SelectedItem = previous;
+ else if (refreshBox.Items.Contains(desktop.dmDisplayFrequency.ToString()))
+ refreshBox.SelectedItem = desktop.dmDisplayFrequency.ToString();
+ else if (refreshBox.Items.Count > 0) refreshBox.SelectedIndex = 0;
+ }
+
+ private static DEVMODE CreateDevMode()
+ {
+ return new DEVMODE
+ {
+ dmDeviceName = new string('\0', 32),
+ dmFormName = new string('\0', 32),
+ dmSize = (short)Marshal.SizeOf<DEVMODE>()
+ };
+ }
+
+ private void UpdateGraphicsApiState()
+ {
+ bool isD3D12 = graphicsApiBox.SelectedIndex != 1;
+
+ // GPU adapter selection is currently specific to the D3D12 backend.
+ // Vulkan uses automatic device selection (REX_VULKAN_DEVICE=-1).
+ gpuBox.Enabled = isD3D12;
+ vrrBox.Enabled = isD3D12 && !vsyncBox.Checked;
+ vrrBox.Text = "VRR / Tearing (D3D12)";
+ readbackMemexportFastBox.Enabled = readbackMemexportBox.Checked;
+
+ if (!isD3D12)
+ {
+ gpuBox.BackColor = Color.FromArgb(34, 38, 43);
+ }
+ else
+ {
+ gpuBox.BackColor = Color.FromArgb(24, 28, 32);
+ }
+ }
+ private void UpdateSummary()
+ {
+ string gpu;
+
+ if (graphicsApiBox.SelectedIndex == 1)
+ {
+ gpu = "Automatic GPU (Vulkan)";
+ }
+ else
+ {
+ gpu = gpuBox.SelectedItem?.ToString() ?? "Automatic GPU";
+ if (gpu == "Automatic") gpu = "Automatic GPU";
+
+ if (gpu.StartsWith("Adapter ", StringComparison.Ordinal))
+ {
+ int colon = gpu.IndexOf(':');
+ if (colon >= 0 && colon + 1 < gpu.Length)
+ gpu = gpu[(colon + 1)..].Trim();
+ }
+ }
+
+ string resolution = resolutionBox.SelectedItem?.ToString() ?? "Resolution";
+ string hz = refreshBox.SelectedItem?.ToString() ?? "--";
+
+ hardwareLabel.Text =
+ $"{gpu} · {resolution} · {hz} Hz";
+ }
+
+ private void UpdateStatus(string text, bool ok)
+ {
+ statusLabel.Text = text;
+ statusLabel.ForeColor = ok ? TextSecondary : Color.FromArgb(255, 120, 120);
+ }
+
+ // Direct play (--play): the window stays invisible, the game starts with the saved settings and the
+ // launcher closes by itself after the game exits (it still restores the display mode first).
+ public void StartDirect()
+ {
+ closeAfterGame = true;
+ ShowInTaskbar = false;
+ Opacity = 0;
+ StartPosition = FormStartPosition.Manual;
+ Location = new Point(-32000, -32000);
+ Shown += (_, _) => LaunchGame();
+ }
+
+ private void CreateDesktopShortcut()
+ {
+ try
+ {
+ SaveSettings();
+ string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
+ string target = Environment.ProcessPath ?? Application.ExecutablePath;
+ string path = Path.Combine(desktop, "ReStreet (direct play).lnk");
+ Type? shellType = Type.GetTypeFromProgID("WScript.Shell");
+ if (shellType == null) throw new InvalidOperationException("Windows Script Host is not available.");
+ dynamic shell = Activator.CreateInstance(shellType)!;
+ dynamic link = shell.CreateShortcut(path);
+ link.TargetPath = target;
+ link.Arguments = "--play";
+ link.WorkingDirectory = Path.GetDirectoryName(target);
+ link.IconLocation = target + ",0";
+ link.Description = "Start ReStreet directly with the settings saved in the launcher";
+ link.Save();
+ MessageBox.Show(
+ "A shortcut was created on your desktop: ReStreet (direct play)." + Environment.NewLine + Environment.NewLine +
+ "It starts the game straight away with the settings you have now. " +
+ "To change settings later, open the launcher normally and click Shortcut again to refresh it.",
+ "ReStreet Launcher", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(ex.Message, "Could not create the shortcut", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+
+ private async void LaunchGame()
+ {
+ if (gameRunning) {
+ ShowError("ReStreet is already running.");
+ return;
+ }
+ try
+ {
+ string exe = exePathBox.Text.Trim();
+ string gameRoot = gamePathBox.Text.Trim();
+
+ if (!File.Exists(exe))
+ {
+ ShowError("fifastreet.exe was not found.");
+ return;
+ }
+
+ if (!Directory.Exists(gameRoot))
+ {
+ ShowError("The game data folder does not exist.");
+ return;
+ }
+
+ if (!File.Exists(Path.Combine(gameRoot, "default.xex")))
+ {
+ MessageBox.Show(
+ "The selected folder does not contain default.xex.",
+ "Invalid folder",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Warning
+ );
+ return;
+ }
+
+ // Select the validated ReXGlue graphics backend.
+ string graphicsApi = graphicsApiBox.SelectedIndex == 1
+ ? "Vulkan"
+ : "D3D12";
+
+ string backendDirectory = Path.Combine(
+ Path.GetDirectoryName(exe)!,
+ "Backends",
+ graphicsApi);
+
+ string backendRuntime = Path.Combine(
+ backendDirectory,
+ "rexruntime.dll");
+
+ string backendGpu = Path.Combine(
+ backendDirectory,
+ "rexgpu-xenos.dll");
+
+ if (!File.Exists(backendRuntime) || !File.Exists(backendGpu))
+ {
+ MessageBox.Show(
+ $"The {graphicsApi} graphics backend is missing.\n\n" +
+ $"Expected files in:\n{backendDirectory}",
+ "ReStreet Launcher",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error);
+ return;
+ }
+
+ string executableDirectory = Path.GetDirectoryName(exe)!;
+
+ File.Copy(
+ backendRuntime,
+ Path.Combine(executableDirectory, "rexruntime.dll"),
+ true);
+
+ File.Copy(
+ backendGpu,
+ Path.Combine(executableDirectory, "rexgpu-xenos.dll"),
+ true);
+
+ var resolution = resolutionBox.Text.Split('x');
+ if (resolution.Length != 2 ||
+ !int.TryParse(resolution[0], out int width) ||
+ !int.TryParse(resolution[1], out int height) ||
+ width <= 0 || height <= 0)
+ {
+ ShowError("Select a valid resolution.");
+ return;
+ }
+ string refresh = refreshBox.Text;
+
+ bool fullscreen =
+ displayModeBox.SelectedItem?.ToString() == "Fullscreen";
+
+ int monitor = Math.Clamp(monitorBox.SelectedIndex, 0, Screen.AllScreens.Length - 1);
+
+ int adapter = gpuBox.SelectedIndex >= 0
+ ? gpuAdapterIndices[gpuBox.SelectedIndex] : -1;
+
+ string postEffect = postEffectBox.SelectedIndex switch
+ {
+ 1 => "fxaa",
+ 2 => "fxaa_extreme",
+ _ => "none"
+ };
+
+
+ string logsDir = Path.Combine(
+ Path.GetDirectoryName(exe)!,
+ "Logs"
+ );
+
+ Directory.CreateDirectory(logsDir);
+
+ string logFile =
+ Path.Combine(logsDir, "fifastreet.log");
+
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = exe,
+ WorkingDirectory = Path.GetDirectoryName(exe)!,
+ UseShellExecute = false
+ };
+
+ // ReXGlue resolves each setting in this order, lowest priority first:
+ // built-in default -> fifastreet.toml -> REX_* environment -> command line.
+ // The REX_* variables set here therefore win over the TOML file.
+
+ startInfo.Environment["REX_GAME_DATA_ROOT"] = gameRoot;
+ int internalResolutionScale = Math.Max(1, internalResolutionBox.SelectedIndex + 1);
+ string readbackResolve = ReadbackResolveModes[Math.Clamp(readbackResolveBox.SelectedIndex, 0, ReadbackResolveModes.Length - 1)];
+ bool deck = IsDeckBase(executableDirectory);
+ if (deck)
+ {
+ ApplyDeckLaunch(startInfo, executableDirectory, graphicsApi, adapter);
+ // Not in fifastreet.toml: the game language and the monitor go as variables, like on 1.5.
+ ApplyGameLanguage(startInfo);
+ startInfo.Environment["REX_MONITOR"] = (monitor + 1).ToString();
+ }
+ else
+ {
+ startInfo.Environment["REX_VIDEO_MODE_WIDTH"] = width.ToString();
+ startInfo.Environment["REX_VIDEO_MODE_HEIGHT"] = height.ToString();
+ // The display size does not change the Xbox 360 render targets.
+
+startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_X"] =
+ internalResolutionScale.ToString();
+
+startInfo.Environment["REX_DRAW_RESOLUTION_SCALE_Y"] =
+ internalResolutionScale.ToString();
+ startInfo.Environment["REX_WINDOW_WIDTH"] = width.ToString();
+ startInfo.Environment["REX_WINDOW_HEIGHT"] = height.ToString();
+ // Apply the selected rate to both the monitor and Xbox video timing.
+ startInfo.Environment["REX_VIDEO_MODE_REFRESH_RATE"] = refresh;
+ // VSync on: lift the game's own 40 FPS replay/cutscene cap up to the chosen rate.
+ // VSync off: no frame limit at all (the game's own limiter is raised out of the way).
+ startInfo.Environment["REX_FRAME_LIMITER_MIN_HZ"] = vsyncBox.Checked ? "auto" : "1000";
+ // Keep the one synchronous readback that keeps stadium floors clean (default 1282B000), drop the
+ // other small-range ones that held goals, replays and match setup below the chosen rate.
+ startInfo.Environment.Remove("REX_READBACK_SOME_SYNC_ADDRS");
+ startInfo.Environment["REX_READBACK_SOME_SYNC_BELOW"] = "0";
+ ApplyGameLanguage(startInfo);
+ // The game keeps its own clock in both modes (True VSync shows its newest frame at each refresh).
+ startInfo.Environment["REX_GUEST_VBLANK_UNLOCKED"] = "true";
+ startInfo.Environment["REX_FULLSCREEN"] =
+ fullscreen ? "true" : "false";
+ startInfo.Environment["REX_MONITOR"] = (monitor + 1).ToString();
+ startInfo.Environment["REX_LAUNCHER_MONITOR_DEVICE"] = Screen.AllScreens[monitor].DeviceName;
+ // "VSync" = True VSync: no tearing, the display shows the game's newest frame at every refresh of the
+ // chosen rate (any rate), and the FPS counter shows displayed frames like GPU overlays do. The old
+ // blocking host VSync (REX_VSYNC) stays off: it made every GPU wait cost two refreshes.
+ startInfo.Environment["REX_VSYNC"] = "false";
+ startInfo.Environment["REX_TRUE_VSYNC"] = vsyncBox.Checked ? "1" : "0";
+ startInfo.Environment["REX_NATIVE_2X_MSAA"] =
+ msaaBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_SWAP_POST_EFFECT"] = postEffect;
+
+ if (graphicsApi == "D3D12")
+ {
+ // Validated D3D12 configuration.
+ startInfo.Environment["REX_D3D12_ALLOW_VARIABLE_REFRESH_RATE_AND_TEARING"] =
+ !vsyncBox.Checked && vrrBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_D3D12_ADAPTER"] = adapter.ToString();
+
+ // Do not force ROV/RTV. The validated D3D12 build uses
+ // ReXGlue's automatic render target path selection.
+ startInfo.Environment["REX_RENDER_TARGET_PATH_D3D12"] = "";
+ }
+ else
+ {
+ // Validated Vulkan configuration.
+ // Vulkan device stays automatic; DXGI adapter indices are
+ // not interchangeable with Vulkan device indices.
+ startInfo.Environment["REX_VULKAN_DEVICE"] = "-1";
+ startInfo.Environment["REX_RENDER_TARGET_PATH_VULKAN"] = "fbo";
+ // Vulkan-only image settings that remove the goal-replay blur
+ // (user-tested together on AMD; not bisected to a single one).
+ startInfo.Environment["REX_DRAW_RESOLUTION_SCALED_TEXTURE_OFFSETS"] = "false";
+ startInfo.Environment["REX_DEPTH_FLOAT24_CONVERT_IN_PIXEL_SHADER"] = "true"; // needed: false (or float24 round) blurs goal replays
+ startInfo.Environment["REX_GAMMA_RENDER_TARGET_AS_UNORM16"] = "false";
+ startInfo.Environment["REX_SNORM16_RENDER_TARGET_FULL_RANGE"] = "false";
+ startInfo.Environment["REX_VULKAN_DYNAMIC_RENDERING"] = "false";
+ startInfo.Environment["REX_HALF_PIXEL_OFFSET"] = "false";
+ startInfo.Environment["REX_ANISOTROPIC_OVERRIDE"] = "-1";
+ startInfo.Environment["REX_DIRECT_HOST_RESOLVE"] = "false"; // true leaves some court floors black
+ // Override legacy TOML values: checked means FIFO, unchecked
+ // requests immediate presentation without display synchronization.
+ // With VSync on, prefer MAILBOX (latest frame wins, no tearing, never blocks the queue).
+ startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_IMMEDIATE"] =
+ vsyncBox.Checked ? "false" : "true";
+ startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_MAILBOX"] =
+ vsyncBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_VULKAN_ALLOW_PRESENT_MODE_FIFO_RELAXED"] =
+ vsyncBox.Checked ? "false" : "true";
+ }
+
+ // Compatibilidade / coerência GPU.
+ startInfo.Environment["REX_READBACK_RESOLVE"] = readbackResolve;
+ // Keep synchronous Full Readback; reduce scheduler round trips for
+ // short GPU work without reading before its fence is signalled.
+ startInfo.Environment["REX_D3D12_READBACK_SHORT_WAIT"] = "true";
+ startInfo.Environment["REX_D3D12_READBACK_SPIN_US"] = "500";
+ startInfo.Environment["REX_VULKAN_READBACK_SHORT_WAIT"] = "true";
+ startInfo.Environment["REX_VULKAN_READBACK_SPIN_US"] = "500";
+ startInfo.Environment["REX_READBACK_MEMEXPORT"] =
+ readbackMemexportBox.Checked ? "true" : "false";
+ startInfo.Environment[graphicsApi == "Vulkan"
+ ? "REX_VULKAN_READBACK_MEMEXPORT" : "REX_D3D12_READBACK_MEMEXPORT"] =
+ readbackMemexportBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_READBACK_MEMEXPORT_FAST"] =
+ readbackMemexportBox.Checked && readbackMemexportFastBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_CLEAR_MEMORY_PAGE_STATE"] =
+ clearMemoryPageStateBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_OCCLUSION_QUERY_ENABLE"] =
+ occlusionQueryBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_ASYNC_SHADER_COMPILATION"] =
+ asyncShadersBox.Checked ? "true" : "false";
+ }
+ ApplyControls(startInfo);
+
+ startInfo.Environment["REX_LOG_VERBOSE"] = "false";
+ startInfo.Environment["REX_LOG_LEVEL"] = "info";
+ startInfo.Environment["REX_LOG_FRAME_STATS"] = logFrameStatsBox.Checked ? "true" : "false";
+ startInfo.Environment["REX_BIND_DEBUG_OVERLAY"] = "Home";
+ startInfo.Environment["REX_LOG_FILE"] = logFile;
+ // Performance report (FPS per scene), read back after the session: see PerfReport.cs.
+ string perfReport = Path.Combine(logsDir, "perf-report.json");
+ try { File.Delete(perfReport); } catch (IOException) { }
+ startInfo.Environment["REX_PERF_REPORT"] = perfReport;
+ var perfSettings = new Dictionary<string, object?>
+ {
+ ["api"] = graphicsApi, ["profile"] = profileBox.Text, ["resolution"] = $"{width}x{height}",
+ ["refresh"] = refresh, ["fullscreen"] = fullscreen, ["internal_scale"] = internalResolutionScale,
+ ["vsync"] = vsyncBox.Checked, ["post"] = postEffect, ["msaa"] = msaaBox.Checked,
+ ["readback"] = deck ? "deck" : readbackResolve,
+ };
+
+ // Online play: the server and the player name come from the online patch.
+ var online = LoadOnlineConfig();
+ if (online != null && onlineModeBox.Checked)
+ {
+ startInfo.Environment["FIFASTREET_SERVER"] = online.Value.Server;
+ startInfo.Environment["FIFASTREET_PLAYER_NAME"] = online.Value.Name;
+ startInfo.Environment["FIFASTREET_PLAYER_KEY"] = online.Value.Key;
+ startInfo.Environment["FIFASTREET_ONLINE_EXPERIMENT"] = "1";
+ startInfo.Environment["FIFASTREET_ONLINE_ENDPOINT_PROBE"] = "1";
+ startInfo.Environment["FIFASTREET_NET_DIAG"] = "";
+ if (!logFrameStatsBox.Checked) startInfo.Environment["REX_LOG_LEVEL"] = "warn";
+ }
+
+ // Mantemos game_data_root também como argumento porque esta
+ // aplicação já confirmou que o aceita diretamente.
+ startInfo.ArgumentList.Add($"--game_data_root={gameRoot}");
+
+ // Settings and the diagnostic summary are conveniences: a read-only install folder must not
+ // prevent the game from starting.
+ try { SaveSettings(); }
+ catch (IOException ex) { Debug.WriteLine(ex.Message); }
+
+ string launcherDebug = Path.Combine(
+ logsDir,
+ "launcher_settings.txt"
+ );
+
+ try {
+ File.WriteAllText(
+ launcherDebug,
+ $"Resolution={width}x{height}{Environment.NewLine}" +
+ $"InternalResolution={1280 * internalResolutionScale}x{720 * internalResolutionScale} ({internalResolutionScale}x){Environment.NewLine}" +
+ $"MonitorRefreshRate={refresh}{Environment.NewLine}" +
+ $"GuestRefreshRate={refresh}{Environment.NewLine}" +
+ $"GuestVblankUnlocked={!vsyncBox.Checked}{Environment.NewLine}" +
+ $"GraphicsApi={graphicsApi}{Environment.NewLine}" +
+ $"Fullscreen={fullscreen}{Environment.NewLine}" +
+ $"Monitor={monitor}{Environment.NewLine}" +
+ $"VSync={vsyncBox.Checked}{Environment.NewLine}" +
+ $"VRRRequested={vrrBox.Checked}; VRREffective={graphicsApi == "D3D12" && !vsyncBox.Checked && vrrBox.Checked}{Environment.NewLine}" +
+ $"MSAA={msaaBox.Checked}{Environment.NewLine}" +
+ $"PostEffect={postEffect}{Environment.NewLine}" +
+ $"Adapter={adapter}{Environment.NewLine}" +
+ $"ReadbackResolve={readbackResolve}{Environment.NewLine}" +
+ $"ReadbackMemexport={readbackMemexportBox.Checked}{Environment.NewLine}" +
+ $"ReadbackMemexportFast={readbackMemexportBox.Checked && readbackMemexportFastBox.Checked}{Environment.NewLine}" +
+ $"ClearMemoryPageState={clearMemoryPageStateBox.Checked}{Environment.NewLine}" +
+ $"OcclusionQueries={occlusionQueryBox.Checked}{Environment.NewLine}" +
+ $"AsyncShaders={asyncShadersBox.Checked}{Environment.NewLine}"
+ );
+ } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+
+ // Discord live state: the game DLL writes "mode=<key>" to this file (presence_state.cpp).
+ // A file left over from the last session would show a stale mode, so start from none.
+ var presenceConfig = PresenceConfig.Load(AppContext.BaseDirectory);
+ if (presenceConfig.Usable && ResolveStateFile(presenceConfig.StateFile) is { } presenceFile)
+ {
+ try { File.Delete(presenceFile); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Debug.WriteLine(ex.Message); }
+ startInfo.Environment["FIFASTREET_PRESENCE_FILE"] = presenceFile;
+ }
+
+ UpdateStatus("Starting ReStreet...", true);
+
+ if (!deck) ApplyMonitorRefresh(monitor, refresh, fullscreen ? width : 0, fullscreen ? height : 0);
+ EnsureStadiumThumbs(Path.GetDirectoryName(exe)!, gameRoot);
+ using var process = Process.Start(startInfo);
+ gameRunning = process != null;
+ gameProcess = process;
+
+ UpdateStatus(
+ process != null
+ ? $"Running • PID {process.Id}"
+ : "Could not start the game",
+ process != null
+ );
+ if (process != null) {
+ StartPresence(process.Id, graphicsApi, width, height, refresh,
+ internalResolutionScale, gpuBox.Text,
+ GameLanguageIds[Math.Max(0, gameLanguageBox.SelectedIndex)]);
+ await process.WaitForExitAsync();
+ OnSessionEnded(perfReport, logFile, perfSettings, process.ExitCode);
+ UpdateStatus(ReadyText(), true);
+ }
+ }
+ catch (Exception ex)
+ {
+ UpdateStatus("Launch failed", false);
+
+ MessageBox.Show(
+ ex.Message,
+ "Error starting ReStreet",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error
+ );
+ }
+ finally {
+ StopPresence();
+ RestoreMonitorRefresh();
+ gameRunning = false;
+ gameProcess = null;
+ if (closeAfterGame) Close();
+ }
+ }
+
+ // ---- Discord Rich Presence (ReStreet presence v2) --------------------------
+ // Off unless presence.json exists next to the launcher and names a Discord
+ // application id. Everything is wrapped: a missing Discord, a broken config or
+ // a closed pipe can never stop the game from starting or keep the launcher open.
+
+ private void StartPresence(int pid, string graphicsApi, int width, int height,
+ string refresh, int internalScale, string gpuName,
+ int gameLanguageId)
+ {
+ try
+ {
+ var config = PresenceConfig.Load(AppContext.BaseDirectory);
+ if (!config.Usable) return;
+
+ // The card follows the game language chosen in the launcher.
+ var text = config.Resolve(PresenceConfig.LanguageCode(gameLanguageId));
+ string apiName = graphicsApi == "D3D12" ? "Direct3D 12" : "Vulkan";
+
+ string Fill(string template) => template
+ .Replace("{api}", apiName)
+ .Replace("{width}", width.ToString())
+ .Replace("{height}", height.ToString())
+ .Replace("{refresh}", refresh)
+ .Replace("{internal}", internalScale + "x")
+ .Replace("{profile}", profileBox.Text)
+ .Replace("{gpu}", gpuName);
+
+ var started = DateTimeOffset.UtcNow;
+ string? stateFilePath = ResolveStateFile(config.StateFile);
+ var stateFile = new PresenceStateFile(stateFilePath);
+
+ DiscordActivity Compose()
+ {
+ stateFile.Poll();
+
+ // The game side writes a canonical mode name (world_tour), never a
+ // translated one, so it never has to know the player's language.
+ string? live = stateFile.State;
+ if (live is null && stateFile.Mode is { Length: > 0 } mode)
+ {
+ live = text.Modes is not null && text.Modes.TryGetValue(mode, out var label)
+ ? label
+ : mode.Replace('_', ' ');
+ }
+
+ return new DiscordActivity
+ {
+ Details = stateFile.Details ?? Fill(text.Details ?? ""),
+ State = live ?? Fill(text.State ?? ""),
+ Start = started,
+ LargeImage = config.LargeImage,
+ LargeText = Fill(text.LargeText ?? ""),
+ SmallImage = graphicsApi == "D3D12"
+ ? config.SmallImageD3D12 : config.SmallImageVulkan,
+ SmallText = apiName,
+ Buttons = config.Buttons.ConvertAll(
+ b => new DiscordButton { Label = b.Label, Url = b.Url })
+ };
+ }
+
+ discord = new DiscordPresence(config.ApplicationId!.Trim(), pid);
+ discord.Set(Compose());
+
+ if (stateFilePath is not null)
+ {
+ presenceTimer = new System.Windows.Forms.Timer { Interval = 5000 };
+ presenceTimer.Tick += (_, _) =>
+ {
+ try { discord?.Set(Compose()); } catch { }
+ };
+ presenceTimer.Start();
+ }
+ }
+ catch
+ {
+ discord = null;
+ }
+ }
+
+ private void StopPresence()
+ {
+ try { presenceTimer?.Stop(); presenceTimer?.Dispose(); } catch { }
+ presenceTimer = null;
+ try { discord?.Dispose(); } catch { }
+ discord = null;
+ }
+
+ private string? ResolveStateFile(string? configured)
+ {
+ if (string.IsNullOrWhiteSpace(configured)) return null;
+ if (Path.IsPathRooted(configured)) return configured;
+ var exeDir = Path.GetDirectoryName(exePathBox.Text.Trim());
+ return string.IsNullOrEmpty(exeDir) ? null : Path.Combine(exeDir, configured);
+ }
+
+ protected override void OnFormClosing(FormClosingEventArgs e)
+ {
+ if (gameRunning && e.CloseReason == CloseReason.UserClosing) {
+ // Keep the launcher alive to restore the display after the game exits.
+ closeAfterGame = true;
+ e.Cancel = true;
+ Hide();
+ }
+ base.OnFormClosing(e);
+ }
+
+ [DllImport("user32.dll", CharSet = CharSet.Ansi)]
+ private static extern int ChangeDisplaySettingsEx(
+ string deviceName, ref DEVMODE mode, IntPtr window, uint flags, IntPtr parameter);
+
+ [DllImport("user32.dll", CharSet = CharSet.Ansi, EntryPoint = "ChangeDisplaySettingsEx")]
+ private static extern int ChangeDisplaySettingsExToRegistry(
+ string deviceName, IntPtr mode, IntPtr window, uint flags, IntPtr parameter);
+
+ private void ApplyMonitorRefresh(int monitor, string refresh, int width, int height)
+ {
+ const uint CDS_TEST = 2;
+ const int DM_DISPLAYFREQUENCY = 0x00400000;
+ if (monitor < 0 || monitor >= Screen.AllScreens.Length ||
+ !int.TryParse(refresh, out int hz) || hz <= 1) {
+ throw new InvalidOperationException("Select a valid monitor and refresh rate.");
+ }
+ string device = Screen.AllScreens[monitor].DeviceName;
+ DEVMODE original = CreateDevMode();
+ if (!EnumDisplaySettings(device, ENUM_CURRENT_SETTINGS, ref original)) {
+ throw new InvalidOperationException("Could not read the monitor's current display mode.");
+ }
+ bool changeResolution = width > 0 && height > 0;
+ if (original.dmDisplayFrequency == hz &&
+ (!changeResolution || (original.dmPelsWidth == width && original.dmPelsHeight == height))) return;
+ DEVMODE requested = original;
+ requested.dmDisplayFrequency = hz;
+ requested.dmFields = DM_DISPLAYFREQUENCY;
+ if (changeResolution) {
+ requested.dmPelsWidth = width;
+ requested.dmPelsHeight = height;
+ requested.dmFields |= 0x00080000 | 0x00100000; // DM_PELSWIDTH | DM_PELSHEIGHT
+ }
+ int result = ChangeDisplaySettingsEx(device, ref requested, IntPtr.Zero, CDS_TEST, IntPtr.Zero);
+ if (result != 0) {
+ throw new InvalidOperationException(
+ $"The selected resolution and {hz} Hz are not available on this monitor (Windows code {result}).");
+ }
+ // Dynamic change (not CDS_FULLSCREEN): a CDS_FULLSCREEN mode is tied to the launcher, and Windows dropped
+ // it back to the desktop rate when the game window took focus (60 Hz chosen, 165 Hz measured in game).
+ // It is not saved to the registry; RestoreMonitorRefresh puts the previous mode back after the game exits.
+ result = ChangeDisplaySettingsEx(device, ref requested, IntPtr.Zero, 0, IntPtr.Zero);
+ if (result != 0) {
+ throw new InvalidOperationException($"Windows could not apply {hz} Hz (code {result}).");
+ }
+ original.dmFields = requested.dmFields;
+ previousDisplayMode = original;
+ changedDisplay = device;
+ DEVMODE actual = CreateDevMode();
+ if (!EnumDisplaySettings(device, ENUM_CURRENT_SETTINGS, ref actual) ||
+ Math.Abs(actual.dmDisplayFrequency - hz) > 1 ||
+ (changeResolution && (actual.dmPelsWidth != width || actual.dmPelsHeight != height))) {
+ throw new InvalidOperationException("Windows did not apply the selected monitor refresh rate.");
+ }
+ }
+
+ private void RestoreMonitorRefresh()
+ {
+ if (changedDisplay == null) return;
+ string device = changedDisplay;
+ changedDisplay = null;
+ // Back to the mode saved in Windows display settings (the change above is dynamic and never saved);
+ // fall back to the mode read before the change.
+ int result = ChangeDisplaySettingsExToRegistry(device, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero);
+ if (result != 0) {
+ result = ChangeDisplaySettingsEx(device, ref previousDisplayMode, IntPtr.Zero, 0, IntPtr.Zero);
+ }
+ if (result != 0) {
+ ShowError($"Could not restore the monitor refresh rate (Windows code {result}). Check Windows display settings.");
+ }
+ }
+
+ private void ShowError(string message)
+ {
+ UpdateStatus("Check your settings", false);
+
+ MessageBox.Show(
+ message,
+ "ReStreet Launcher",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error
+ );
+ }
+
+ private void BrowseExe()
+ {
+ using var dialog = new OpenFileDialog
+ {
+ Filter = "FIFA Street executable|fifastreet.exe|Executables|*.exe"
+ };
+
+ if (dialog.ShowDialog() == DialogResult.OK)
+ exePathBox.Text = dialog.FileName;
+ }
+
+ private void BrowseGame()
+ {
+ using var dialog = new FolderBrowserDialog
+ {
+ Description = "Select the folder containing default.xex"
+ };
+
+ if (dialog.ShowDialog() == DialogResult.OK)
+ gamePathBox.Text = dialog.SelectedPath;
+ }
+
+ private void OpenLogs()
+ {
+ string exe = exePathBox.Text.Trim();
+
+ if (!File.Exists(exe)) {
+ ShowError("Select an existing game executable first.");
+ return;
+ }
+
+ string logs = Path.Combine(
+ Path.GetDirectoryName(exe)!,
+ "Logs"
+ );
+
+ Directory.CreateDirectory(logs);
+
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = "explorer.exe",
+ Arguments = $"\"{logs}\"",
+ UseShellExecute = true
+ });
+ }
+
+ private void OpenGameFolder()
+ {
+ string exe = exePathBox.Text.Trim();
+
+ if (!File.Exists(exe)) {
+ ShowError("Select an existing game executable first.");
+ return;
+ }
+
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = "explorer.exe",
+ Arguments = $"\"{Path.GetDirectoryName(exe)}\"",
+ UseShellExecute = true
+ });
+ }
+
+ // post effect: 0 none, 1 FXAA, 2 FXAA extreme; internal resolution index = scale - 1;
+ // readback: 0 full, 1 some (default since v1.1), 2 fast
+ private void ApplyProfile()
+ {
+ if (applyingProfile)
+ return;
+ (int post, int scale, bool msaa, int readback, bool occlusion)? values = profileBox.SelectedIndex switch
+ {
+ 0 => (1, 0, false, 1, false), // Balanced: the shipped defaults (Some readback)
+ 1 => (2, 1, true, 1, false), // Quality: 2x internal resolution, FXAA extreme, MSAA (Some readback)
+ 2 => (0, 0, false, 2, false), // Performance: native resolution, no post, faster readback
+ _ => null
+ };
+ if (values == null)
+ return;
+ applyingProfile = true;
+ try
+ {
+ postEffectBox.SelectedIndex = values.Value.post;
+ internalResolutionBox.SelectedIndex = values.Value.scale;
+ msaaBox.Checked = values.Value.msaa;
+ readbackResolveBox.SelectedIndex = values.Value.readback;
+ occlusionQueryBox.Checked = values.Value.occlusion;
+ }
+ finally
+ {
+ applyingProfile = false;
+ }
+ }
+
+ private void MarkCustomProfile()
+ {
+ if (!applyingProfile && profileBox.SelectedIndex != ProfileNames.Length - 1)
+ {
+ applyingProfile = true;
+ profileBox.SelectedIndex = ProfileNames.Length - 1;
+ applyingProfile = false;
+ }
+ }
+
+ private void SaveSettings()
+ {
+ try
+ {
+ var settings = new LauncherSettings
+ {
+ ExePath = exePathBox.Text,
+ GamePath = gamePathBox.Text,
+ Resolution = resolutionBox.Text,
+ RefreshRate = refreshBox.Text,
+ Fullscreen = displayModeBox.SelectedIndex == 0,
+ Monitor = monitorBox.SelectedIndex,
+ GraphicsApi = graphicsApiBox.SelectedIndex,
+ GameLanguage = GameLanguageIds[Math.Max(0, gameLanguageBox.SelectedIndex)],
+ Gpu = gpuBox.SelectedIndex,
+ GpuUsesDxgi = true,
+ PostEffect = postEffectBox.SelectedIndex,
+ InternalResolutionScale = internalResolutionBox.SelectedIndex,
+ ReadbackResolve = readbackResolveBox.SelectedIndex,
+ LogFrameStats = logFrameStatsBox.Checked,
+ ReadbackMemexport = readbackMemexportBox.Checked,
+ ReadbackMemexportFast = readbackMemexportFastBox.Checked,
+ ClearMemoryPageState = clearMemoryPageStateBox.Checked,
+ OcclusionQueries = occlusionQueryBox.Checked,
+ AsyncShaders = asyncShadersBox.Checked,
+ VSync = vsyncBox.Checked,
+ VRR = vrrBox.Checked,
+ MSAA = msaaBox.Checked,
+ Profile = profileBox.SelectedIndex,
+ OnlineMode = onlineModeBox.Checked
+ };
+
+ string json = JsonSerializer.Serialize(
+ settings,
+ new JsonSerializerOptions
+ {
+ WriteIndented = true
+ }
+ );
+
+ File.WriteAllText(SettingsPath, json);
+ }
+ catch (Exception ex)
+ {
+ throw new IOException("Could not save launcher settings: " + ex.Message, ex);
+ }
+ }
+
+ private void LoadSettings()
+ {
+ try
+ {
+ if (!File.Exists(SettingsPath))
+ return;
+
+ var settings =
+ JsonSerializer.Deserialize<LauncherSettings>(
+ File.ReadAllText(SettingsPath)
+ );
+
+ if (settings == null)
+ return;
+ onlineModeBox.Checked = settings.OnlineMode;
+ int languageIndex = Array.IndexOf(GameLanguageIds, settings.GameLanguage);
+ gameLanguageBox.SelectedIndex = Math.Max(0, languageIndex);
+
+ // A saved path that no longer exists (the folders moved to the 1.5.5 layout) gives way to the default.
+ if (settings.ExePath != null && File.Exists(settings.ExePath)) exePathBox.Text = settings.ExePath;
+ if (settings.GamePath != null && Directory.Exists(settings.GamePath)) gamePathBox.Text = settings.GamePath;
+
+ displayModeBox.SelectedIndex =
+ settings.Fullscreen ? 0 : 1;
+
+ if (settings.Monitor >= 0 &&
+ settings.Monitor < monitorBox.Items.Count)
+ {
+ monitorBox.SelectedIndex = settings.Monitor;
+ }
+
+ DetectDisplayModes();
+
+ SelectItem(resolutionBox, settings.Resolution);
+ SelectItem(refreshBox, settings.RefreshRate);
+
+ if (settings.GraphicsApi >= 0 &&
+ settings.GraphicsApi < graphicsApiBox.Items.Count)
+ {
+ graphicsApiBox.SelectedIndex = settings.GraphicsApi;
+ }
+
+ if (settings.GpuUsesDxgi && settings.Gpu >= 0 &&
+ settings.Gpu < gpuBox.Items.Count)
+ {
+ gpuBox.SelectedIndex = settings.Gpu;
+ }
+
+ if (settings.PostEffect >= 0 &&
+ settings.PostEffect < postEffectBox.Items.Count)
+ {
+ postEffectBox.SelectedIndex = settings.PostEffect;
+ }
+if (settings.InternalResolutionScale >= 0 &&
+ settings.InternalResolutionScale < internalResolutionBox.Items.Count)
+{
+ internalResolutionBox.SelectedIndex = settings.InternalResolutionScale;
+}
+
+ if (settings.ReadbackResolve >= 0 &&
+ settings.ReadbackResolve < readbackResolveBox.Items.Count)
+ readbackResolveBox.SelectedIndex = settings.ReadbackResolve;
+ logFrameStatsBox.Checked = settings.LogFrameStats;
+ readbackMemexportBox.Checked = settings.ReadbackMemexport;
+ readbackMemexportFastBox.Checked = settings.ReadbackMemexportFast;
+ clearMemoryPageStateBox.Checked = settings.ClearMemoryPageState;
+ occlusionQueryBox.Checked = settings.OcclusionQueries;
+ asyncShadersBox.Checked = settings.AsyncShaders;
+
+ vsyncBox.Checked = settings.VSync;
+ vrrBox.Checked = settings.VRR;
+ msaaBox.Checked = settings.MSAA;
+ if (settings.Profile >= 0 && settings.Profile < profileBox.Items.Count)
+ profileBox.SelectedIndex = settings.Profile;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ // Unreadable or corrupt settings fall back to the defaults.
+ Debug.WriteLine("Could not load launcher settings: " + ex.Message);
+ }
+ }
+
+ private static void SelectItem(ComboBox box, string? value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ return;
+
+ int index = box.Items.IndexOf(value);
+
+ if (index >= 0)
+ box.SelectedIndex = index;
+ }
+
+ private void ApplyGameLanguage(ProcessStartInfo startInfo)
+ {
+ int id = GameLanguageIds[Math.Max(0, gameLanguageBox.SelectedIndex)];
+ startInfo.Environment["REX_USER_LANGUAGE"] = (id == PtBrLanguageId ? 1 : id).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ if (id == PtBrLanguageId) startInfo.Environment["FIFASTREET_GAME_LANGUAGE"] = "pt-BR";
+ else startInfo.Environment.Remove("FIFASTREET_GAME_LANGUAGE");
+ }
+
+ private sealed class MessiPicture : PictureBox
+ {
+ private const float CropX = 100f / 1280f;
+ private const float CropY = 225f / 1819f;
+ private const float CropWidth = 640f / 1280f;
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ if (Image == null || ClientSize.Width <= 0 || ClientSize.Height <= 0)
+ return;
+
+ e.Graphics.Clear(Color.FromArgb(10, 12, 16));
+ e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
+
+ float sourceX = Image.Width * CropX;
+ float sourceY = Image.Height * CropY;
+ float sourceWidth = Image.Width * CropWidth;
+
+ // Preserve the same horizontal framing. Expanding the launcher
+ // reveals more of the source image vertically without stretching.
+ float scale = ClientSize.Width / sourceWidth;
+ float sourceHeight = ClientSize.Height / scale;
+ float availableHeight = Image.Height - sourceY;
+ sourceHeight = Math.Min(sourceHeight, availableHeight);
+
+ var sourceRect = new RectangleF(sourceX, sourceY, sourceWidth, sourceHeight);
+ float destinationHeight = sourceHeight * scale;
+ var destinationRect = new RectangleF(0, 0, ClientSize.Width, destinationHeight);
+
+ e.Graphics.DrawImage(Image, destinationRect, sourceRect, GraphicsUnit.Pixel);
+ }
+ }
+}
+
+public class LauncherSettings
+{
+ public string? ExePath { get; set; }
+ public string? GamePath { get; set; }
+ public string? Resolution { get; set; }
+ public string? RefreshRate { get; set; }
+ public bool Fullscreen { get; set; } = true;
+ public int Monitor { get; set; }
+ public int GraphicsApi { get; set; } = 0;
+ public int GameLanguage { get; set; } = 1;
+ public int Gpu { get; set; }
+ public bool GpuUsesDxgi { get; set; }
+ public int PostEffect { get; set; } = 1;
+ public int ReadbackResolve { get; set; } = 0;
+ public bool LogFrameStats { get; set; } = false;
+ public int InternalResolutionScale { get; set; } = 0;
+ public bool ReadbackMemexport { get; set; } = true;
+ public bool ReadbackMemexportFast { get; set; } = true;
+ public bool ClearMemoryPageState { get; set; } = false;
+ public bool OcclusionQueries { get; set; } = true;
+ public bool AsyncShaders { get; set; } = true;
+ public bool VSync { get; set; } = false;
+ public bool VRR { get; set; } = true;
+ public bool MSAA { get; set; } = false;
+ public int Profile { get; set; } = 0;
+ public bool OnlineMode { get; set; } = true;
+}
+
+public class RoundedPanel : Panel, IFlatPanel
+{
+ public Color FillColor { get; set; } = Color.FromArgb(18, 22, 28);
+ public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
+ public int Radius { get; set; } = 16;
+
+ public RoundedPanel()
+ {
+ DoubleBuffered = true;
+ BackColor = Color.Transparent;
+ }
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ base.OnPaint(e);
+
+ e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
+
+ Rectangle rect = ClientRectangle;
+ rect.Width -= 1;
+ rect.Height -= 1;
+
+ using var path = CreateRoundedRectangle(rect, Radius);
+ using var fill = new SolidBrush(FillColor);
+ using var border = new Pen(BorderColor, 1F);
+
+ e.Graphics.FillPath(fill, path);
+ e.Graphics.DrawPath(border, path);
+ }
+
+ protected override void OnResize(EventArgs eventargs)
+ {
+ base.OnResize(eventargs);
+ Invalidate();
+ }
+
+ private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
+ {
+ int diameter = radius * 2;
+
+ var path = new GraphicsPath();
+
+ if (diameter <= 0)
+ {
+ path.AddRectangle(rect);
+ return path;
+ }
+
+ var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
+
+ path.AddArc(arc, 180, 90);
+
+ arc.X = rect.Right - diameter;
+ path.AddArc(arc, 270, 90);
+
+ arc.Y = rect.Bottom - diameter;
+ path.AddArc(arc, 0, 90);
+
+ arc.X = rect.Left;
+ path.AddArc(arc, 90, 90);
+
+ path.CloseFigure();
+
+ return path;
+ }
+}
+
+public class ModernButton : Button
+{
+ public Color FillColor { get; set; } = Color.FromArgb(24, 29, 36);
+ public Color HoverColor { get; set; } = Color.FromArgb(34, 41, 50);
+ public Color BorderColor { get; set; } = Color.FromArgb(48, 57, 68);
+ public int Radius { get; set; } = 10;
+
+ private bool hovered;
+
+ public ModernButton()
+ {
+ FlatStyle = FlatStyle.Flat;
+ FlatAppearance.BorderSize = 0;
+ Cursor = Cursors.Hand;
+ UseVisualStyleBackColor = false;
+ DoubleBuffered = true;
+ BackColor = Color.Transparent;
+
+ MouseEnter += (_, _) =>
+ {
+ hovered = true;
+ Invalidate();
+ };
+
+ MouseLeave += (_, _) =>
+ {
+ hovered = false;
+ Invalidate();
+ };
+ }
+
+ protected override void OnPaint(PaintEventArgs pevent)
+ {
+ pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
+
+ Rectangle rect = ClientRectangle;
+ rect.Width -= 1;
+ rect.Height -= 1;
+
+ using var path = CreateRoundedRectangle(rect, Radius);
+ using var fill = new SolidBrush(hovered ? HoverColor : FillColor);
+ using var border = new Pen(BorderColor, 1F);
+
+ pevent.Graphics.FillPath(fill, path);
+ pevent.Graphics.DrawPath(border, path);
+
+ TextRenderer.DrawText(
+ pevent.Graphics,
+ Text,
+ Font,
+ ClientRectangle,
+ ForeColor,
+ TextFormatFlags.HorizontalCenter |
+ TextFormatFlags.VerticalCenter |
+ TextFormatFlags.EndEllipsis
+ );
+ }
+
+ private static GraphicsPath CreateRoundedRectangle(Rectangle rect, int radius)
+ {
+ int diameter = radius * 2;
+
+ var path = new GraphicsPath();
+
+ if (diameter <= 0)
+ {
+ path.AddRectangle(rect);
+ return path;
+ }
+
+ var arc = new Rectangle(rect.Location, new Size(diameter, diameter));
+
+ path.AddArc(arc, 180, 90);
+
+ arc.X = rect.Right - diameter;
+ path.AddArc(arc, 270, 90);
+
+ arc.Y = rect.Bottom - diameter;
+ path.AddArc(arc, 0, 90);
+
+ arc.X = rect.Left;
+ path.AddArc(arc, 90, 90);
+
+ path.CloseFigure();
+
+ return path;
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/LobbyForm.cs b/Launcher/FifaStreetLauncher/LobbyForm.cs
new file mode 100644
index 0000000..ea8f802
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/LobbyForm.cs
@@ -0,0 +1,446 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Linq;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+using ReStreet.Ui;
+
+namespace FifaStreetLauncher;
+
+internal enum LobbyState { Header, Searching, InMatch, Online }
+
+// One line of the lobby: a section header or a player with a status symbol.
+internal sealed record LobbyRow(LobbyState State, string Name, string Detail = "", bool IsMe = false);
+
+// The lobby list is drawn by hand so it matches the rest of the launcher.
+// Symbols (shape + colour, so they also read without colour): green dot = online in the menus,
+// pulsing yellow ring = searching for a match, blue play triangle = in a match.
+internal sealed class LobbyList : Control
+{
+ const int RowH = 44, HeaderH = 32;
+ static readonly Color Green = Color.FromArgb(86, 214, 120);
+ static readonly Color Blue = Color.FromArgb(90, 170, 255);
+ readonly List<LobbyRow> rows = new();
+ int scroll;
+ bool pulse;
+ readonly System.Windows.Forms.Timer pulseTimer = new() { Interval = 550 };
+
+ public string EmptyText { get; set; } = "";
+
+ public LobbyList()
+ {
+ SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
+ BackColor = StreetTheme.Field;
+ pulseTimer.Tick += (_, _) => { pulse = !pulse; if (rows.Any(r => r.State == LobbyState.Searching)) Invalidate(); };
+ pulseTimer.Start();
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing) pulseTimer.Dispose();
+ base.Dispose(disposing);
+ }
+
+ public void SetRows(IEnumerable<LobbyRow> items)
+ {
+ rows.Clear();
+ rows.AddRange(items);
+ ClampScroll();
+ Invalidate();
+ }
+
+ float K => StreetTheme.K(this);
+ int RowHeight(LobbyRow row) => (int)((row.State == LobbyState.Header ? HeaderH : RowH) * K);
+ int TotalHeight() { int sum = 0; foreach (var row in rows) sum += RowHeight(row); return sum; }
+ void ClampScroll() => scroll = Math.Max(0, Math.Min(scroll, Math.Max(0, TotalHeight() - Height)));
+
+ protected override void OnMouseWheel(MouseEventArgs e)
+ {
+ scroll -= Math.Sign(e.Delta) * (int)(RowH * K);
+ ClampScroll();
+ Invalidate();
+ }
+
+ protected override void OnPaintBackground(PaintEventArgs e) { }
+
+ static void DrawSymbol(Graphics g, LobbyState state, RectangleF box, bool pulseOn)
+ {
+ switch (state)
+ {
+ case LobbyState.Online:
+ using (var brush = new SolidBrush(Green)) g.FillEllipse(brush, box);
+ break;
+ case LobbyState.Searching:
+ {
+ float width = (pulseOn ? 3.2f : 2.2f) * box.Width / 12f;
+ var ring = RectangleF.Inflate(box, -width / 2, -width / 2);
+ using var pen = new Pen(StreetTheme.Yellow, width);
+ g.DrawEllipse(pen, ring);
+ float core = box.Width * (pulseOn ? 0.22f : 0.34f);
+ using var dot = new SolidBrush(StreetTheme.Yellow);
+ g.FillEllipse(dot, box.X + (box.Width - core) / 2, box.Y + (box.Height - core) / 2, core, core);
+ break;
+ }
+ case LobbyState.InMatch:
+ {
+ var triangle = new[]
+ {
+ new PointF(box.X + box.Width * 0.18f, box.Y),
+ new PointF(box.Right, box.Y + box.Height / 2),
+ new PointF(box.X + box.Width * 0.18f, box.Bottom)
+ };
+ using var brush = new SolidBrush(Blue);
+ g.FillPolygon(brush, triangle);
+ break;
+ }
+ }
+ }
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ var g = e.Graphics;
+ StreetTheme.PaintBehind(this, g);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ float k = K;
+ var frame = new RectangleF(0.5f, 0.5f, Width - 1, Height - 1);
+ using var path = StreetTheme.Round(frame, 8 * k);
+ using (var fill = new SolidBrush(StreetTheme.Field)) g.FillPath(fill, path);
+ var saved = g.Save();
+ g.SetClip(path, CombineMode.Intersect);
+
+ using var nameFont = new Font("Segoe UI", 14f * k, GraphicsUnit.Pixel);
+ using var nameBold = new Font("Segoe UI", 14f * k, FontStyle.Bold, GraphicsUnit.Pixel);
+ using var detailFont = new Font("Segoe UI", 12.67f * k, GraphicsUnit.Pixel);
+ using var headerFont = new Font(StreetTheme.CondensedFamily, 11 * k, FontStyle.Bold, GraphicsUnit.Pixel);
+
+ if (rows.Count == 0)
+ TextRenderer.DrawText(g, EmptyText, nameFont, new Rectangle((int)(16 * k), (int)(14 * k), Width - (int)(32 * k), Height), StreetTheme.Muted,
+ TextFormatFlags.WordBreak | TextFormatFlags.NoPadding);
+
+ int y = -scroll;
+ foreach (var row in rows)
+ {
+ int h = RowHeight(row);
+ var bounds = new Rectangle(0, y, Width, h);
+ y += h;
+ if (bounds.Bottom < 0 || bounds.Top > Height) continue;
+
+ if (row.State == LobbyState.Header)
+ {
+ using var yellow = new SolidBrush(StreetTheme.Yellow);
+ StreetTheme.DrawSpaced(g, row.Name, headerFont, yellow, new PointF(16 * k, bounds.Y + 12 * k), 2.2f * k);
+ continue;
+ }
+
+ float symbol = 12 * k;
+ DrawSymbol(g, row.State, new RectangleF(16 * k, bounds.Y + (h - symbol) / 2, symbol, symbol), pulse);
+
+ string name = row.IsMe ? row.Name + " (you)" : row.Name;
+ int detailWidth = (int)(190 * k);
+ TextRenderer.DrawText(g, name, row.IsMe ? nameBold : nameFont,
+ new Rectangle((int)(38 * k), bounds.Y, Width - (int)(38 * k) - detailWidth - (int)(14 * k), h), StreetTheme.Ink,
+ TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
+ Color detailColor = row.State switch { LobbyState.Searching => StreetTheme.Yellow, LobbyState.InMatch => Blue, _ => StreetTheme.Muted };
+ TextRenderer.DrawText(g, row.Detail, detailFont,
+ new Rectangle(Width - detailWidth - (int)(14 * k), bounds.Y, detailWidth, h), detailColor,
+ TextFormatFlags.VerticalCenter | TextFormatFlags.Right | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
+ }
+ g.Restore(saved);
+ using var edge = new Pen(Color.FromArgb(60, 255, 255, 255));
+ g.DrawPath(edge, path);
+ }
+}
+
+// Who is online, who is searching for a match (and in which mode) and who is in a match.
+// Same frame, fonts and colours as the friends window.
+internal sealed class LobbyForm : Form, ISceneHost, IUiScaled
+{
+ readonly UiScaler scaler;
+ public float UiScale => scaler.Scale;
+
+ const float DesignHeight = 610f;
+ new const int Left = 48;
+ const int SheetX = 480, SheetY = 32, SheetW = 422, SheetH = 546, Pad = 24;
+ const int ContentX = SheetX + Pad, ContentW = SheetW - 2 * Pad;
+
+ static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(5) };
+
+ readonly string server, me;
+ readonly SlantButton closeButton = new();
+ readonly LobbyList list = new();
+ readonly ThemedLabel meLabel = new();
+ readonly ThemedLabel connection = new();
+ readonly ThemedLabel summary = new();
+ readonly System.Windows.Forms.Timer poll = new() { Interval = 4000 };
+
+ Bitmap? scene;
+ Size sceneSize;
+ bool busy;
+ bool previewing; // sample rows for screenshots: never overwritten by a refresh
+
+ public Bitmap SceneBitmap { get { BuildScene(); return scene!; } }
+
+ internal LobbyForm(string server, string me)
+ {
+ this.server = server;
+ this.me = me;
+ Text = "ReStreet - Lobby";
+ using (var icon = typeof(LobbyForm).Assembly.GetManifestResourceStream("fifastreet.ico")!)
+ Icon = new Icon(icon);
+ ClientSize = new Size(930, 610);
+ scaler = new UiScaler(this, 930, 610);
+ StartPosition = FormStartPosition.CenterParent;
+ FormBorderStyle = FormBorderStyle.FixedSingle;
+ MaximizeBox = false;
+ MinimizeBox = false;
+ DoubleBuffered = true;
+ ResizeRedraw = true;
+ BackColor = StreetTheme.Asphalt;
+ ForeColor = StreetTheme.Ink;
+ Font = StreetTheme.Body(10);
+ HandleCreated += (_, _) => StreetTheme.ApplyDarkTitleBar(Handle);
+
+ meLabel.SetBounds(Left, 264, 384, 28);
+ meLabel.Font = StreetTheme.Body(13f, FontStyle.Bold);
+ meLabel.ForeColor = StreetTheme.Ink;
+ meLabel.Text = "Playing as " + me;
+ Controls.Add(meLabel);
+ connection.SetBounds(Left, 296, 384, 24);
+ connection.Font = StreetTheme.Body(10);
+ connection.ForeColor = StreetTheme.Muted;
+ connection.Text = "Connecting…";
+ Controls.Add(connection);
+ Controls.Add(new ThemedLabel
+ {
+ Text = "In the game: Xbox LIVE, Street Seasons, Division Match, then pick a game mode. Search in the same mode as the person you want to play: " +
+ "the server only pairs players who search for the same mode.",
+ Bounds = new Rectangle(Left, 336, 384, 96),
+ Font = StreetTheme.Body(10),
+ ForeColor = StreetTheme.Muted
+ });
+ Controls.Add(new LegendPanel { Bounds = new Rectangle(Left, 440, 384, 84) });
+
+ Controls.Add(new ThemedLabel
+ {
+ Text = "Lobby", Bounds = new Rectangle(ContentX, SheetY + Pad, ContentW, 32),
+ Font = StreetTheme.Condensed(20f, FontStyle.Bold), ForeColor = StreetTheme.Ink
+ });
+ summary.SetBounds(ContentX, 90, ContentW, 20);
+ summary.Font = StreetTheme.Body(10);
+ summary.ForeColor = StreetTheme.Muted;
+ Controls.Add(summary);
+
+ list.Bounds = new Rectangle(ContentX, 118, ContentW, 392);
+ list.EmptyText = "Nobody is online right now. Open the game and be the first.";
+ Controls.Add(list);
+
+ closeButton.Kind = SlantKind.Text;
+ closeButton.Align = StringAlignment.Far;
+ closeButton.Text = "Close";
+ closeButton.Font = StreetTheme.Body(10);
+ closeButton.Bounds = new Rectangle(ContentX + ContentW - 150, 522, 150, 32);
+ closeButton.Click += (_, _) => Close();
+ Controls.Add(closeButton);
+ CancelButton = closeButton;
+
+ poll.Tick += async (_, _) => await Refresh();
+ Shown += async (_, _) => { poll.Start(); await Refresh(); };
+ FormClosed += (_, _) => poll.Dispose();
+ scaler.Capture();
+ }
+
+ // Legend of the three symbols, drawn with the same shapes as the list.
+ sealed class LegendPanel : Control
+ {
+ public LegendPanel()
+ {
+ SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
+ BackColor = Color.Transparent;
+ }
+
+ protected override void OnPaintBackground(PaintEventArgs e) => StreetTheme.PaintBehind(this, e.Graphics);
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ var g = e.Graphics;
+ StreetTheme.PaintBehind(this, g);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ float k = StreetTheme.K(this);
+ using var font = new Font("Segoe UI", 13f * k, GraphicsUnit.Pixel);
+ var items = new[]
+ {
+ (LobbyState.Online, "Online, in the menus"),
+ (LobbyState.Searching, "Searching for a match"),
+ (LobbyState.InMatch, "In a match")
+ };
+ int y = 0;
+ foreach (var (state, text) in items)
+ {
+ float symbol = 12 * k;
+ LobbyList_DrawSymbol(g, state, new RectangleF(2 * k, y + 5 * k, symbol, symbol));
+ TextRenderer.DrawText(g, text, font, new Rectangle((int)(26 * k), y, Width - (int)(26 * k), (int)(26 * k)), StreetTheme.Ink,
+ TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
+ y += (int)(28 * k);
+ }
+ }
+
+ static void LobbyList_DrawSymbol(Graphics g, LobbyState state, RectangleF box)
+ {
+ switch (state)
+ {
+ case LobbyState.Online:
+ using (var brush = new SolidBrush(Color.FromArgb(86, 214, 120))) g.FillEllipse(brush, box);
+ break;
+ case LobbyState.Searching:
+ {
+ float width = 2.4f * box.Width / 12f;
+ using var pen = new Pen(StreetTheme.Yellow, width);
+ g.DrawEllipse(pen, RectangleF.Inflate(box, -width / 2, -width / 2));
+ float core = box.Width * 0.3f;
+ using var dot = new SolidBrush(StreetTheme.Yellow);
+ g.FillEllipse(dot, box.X + (box.Width - core) / 2, box.Y + (box.Height - core) / 2, core, core);
+ break;
+ }
+ default:
+ {
+ var triangle = new[]
+ {
+ new PointF(box.X + box.Width * 0.18f, box.Y), new PointF(box.Right, box.Y + box.Height / 2), new PointF(box.X + box.Width * 0.18f, box.Bottom)
+ };
+ using var brush = new SolidBrush(Color.FromArgb(90, 170, 255));
+ g.FillPolygon(brush, triangle);
+ break;
+ }
+ }
+ }
+ }
+
+ protected override void OnPaintBackground(PaintEventArgs e)
+ {
+ BuildScene();
+ using (var floor = new SolidBrush(StreetTheme.Asphalt)) e.Graphics.FillRectangle(floor, ClientRectangle);
+ e.Graphics.DrawImageUnscaled(scene!, 0, 0);
+ }
+
+ void BuildScene()
+ {
+ float s = ClientSize.Width / (float)StreetTheme.DesignWidth;
+ var size = new Size(ClientSize.Width, (int)Math.Ceiling(DesignHeight * s));
+ if (scene != null && sceneSize == size) return;
+ scene?.Dispose();
+ sceneSize = size;
+ using var backdrop = StreetTheme.RenderBackdrop(size, StreetTheme.DesignWidth, DesignHeight);
+ using var blurred = StreetTheme.Blur(backdrop, 10);
+ scene = new Bitmap(backdrop);
+ using var g = Graphics.FromImage(scene);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
+ g.ScaleTransform(s, s);
+
+ StreetTheme.DrawGlass(g, blurred, s, new RectangleF(SheetX, SheetY, SheetW, SheetH), 16);
+
+ using (var small = new Font(StreetTheme.CondensedFamily, 16, FontStyle.Bold, GraphicsUnit.Pixel))
+ using (var yellow = new SolidBrush(StreetTheme.Yellow))
+ StreetTheme.DrawSpaced(g, "FIFA STREET 2012 RECOMPILED", small, yellow, new PointF(Left, 56), 3.2f);
+ StreetTheme.DrawWordmark(g, "ReStreet", new PointF(Left, 88), 118, StreetTheme.Ink);
+ var tag = new RectangleF(Left, 192, 236, 32);
+ using (var bar = new SolidBrush(StreetTheme.Yellow)) g.FillPolygon(bar, StreetTheme.Slant(tag, 10));
+ using (var tagFont = new Font(StreetTheme.CondensedFamily, 16, FontStyle.Bold, GraphicsUnit.Pixel))
+ using (var dark = new SolidBrush(StreetTheme.YellowDark))
+ StreetTheme.DrawSpaced(g, "LOBBY · ONLINE BETA", tagFont, dark, new PointF(Left + 12, 198), 2.6f);
+
+ using var name = new Font("Segoe UI", 15, FontStyle.Regular, GraphicsUnit.Pixel);
+ StreetTheme.DrawLabelValue(g, "Ported by:", "SamuelitoDaVila", name, StreetTheme.Ink, StreetTheme.Ink, Left, 534);
+ StreetTheme.DrawLabelValue(g, "Contributions:", "Emran_Ahm3d", name, StreetTheme.Muted, StreetTheme.Muted, Left, 557);
+ }
+
+ // Sample rows for the --preview-lobby screenshot.
+ internal void PreviewRows()
+ {
+ previewing = true;
+ poll.Stop();
+ connection.Text = "Connected · 42 ms to the server";
+ ApplyRows(
+ new[] { ("StreetKing", "Division · 5-a-side", 14), ("NightFox", "Division · Futsal", 9), ("Kaito_77", "Division · 6-a-side", 3) },
+ new[] { "Lola", "Rafa10", "Zed", "Mika" },
+ new[] { "Dante", "Nina_K" },
+ false, 64);
+ }
+
+ string Url(string path) => "http://" + server + ":29812" + path;
+
+ static string Waited(int seconds) => seconds < 60 ? seconds + " s" : (seconds / 60) + " min " + (seconds % 60) + " s";
+
+ void ApplyRows((string Name, string Mode, int Waited)[] searching, string[] online, string[] inMatch, bool paused, int maxOnline)
+ {
+ var rows = new List<LobbyRow>();
+ if (searching.Length > 0)
+ {
+ rows.Add(new LobbyRow(LobbyState.Header, "SEARCHING FOR A MATCH · " + searching.Length));
+ rows.AddRange(searching.OrderByDescending(s => s.Waited)
+ .Select(s => new LobbyRow(LobbyState.Searching, s.Name, s.Mode + " · " + Waited(s.Waited), IsMe(s.Name))));
+ }
+ if (inMatch.Length > 0)
+ {
+ rows.Add(new LobbyRow(LobbyState.Header, "IN A MATCH · " + inMatch.Length));
+ rows.AddRange(inMatch.OrderBy(n => n, StringComparer.OrdinalIgnoreCase).Select(n => new LobbyRow(LobbyState.InMatch, n, "In a match", IsMe(n))));
+ }
+ if (online.Length > 0)
+ {
+ rows.Add(new LobbyRow(LobbyState.Header, "ONLINE · " + online.Length));
+ rows.AddRange(online.OrderBy(n => n, StringComparer.OrdinalIgnoreCase).Select(n => new LobbyRow(LobbyState.Online, n, "In the menus", IsMe(n))));
+ }
+ int total = searching.Length + online.Length + inMatch.Length;
+ summary.Text = total + " online · " + searching.Length + " searching · " + inMatch.Length + " in a match"
+ + (paused ? " · matchmaking paused" : "");
+ list.SetRows(rows);
+ }
+
+ bool IsMe(string name) => string.Equals(name, me, StringComparison.OrdinalIgnoreCase);
+
+ async Task Refresh()
+ {
+ if (busy || previewing) return;
+ busy = true;
+ try
+ {
+ var watch = Stopwatch.StartNew();
+ string text = await Http.GetStringAsync(Url("/v1/online"));
+ int ping = (int)watch.ElapsedMilliseconds;
+ using var doc = JsonDocument.Parse(text);
+ var root = doc.RootElement;
+ connection.ForeColor = StreetTheme.Muted;
+ connection.Text = "Connected · " + ping + " ms to the server";
+
+ var searching = new List<(string, string, int)>();
+ if (root.TryGetProperty("searching_list", out var searchList) && searchList.ValueKind == JsonValueKind.Array)
+ foreach (var item in searchList.EnumerateArray())
+ searching.Add((item.GetProperty("name").GetString() ?? "?", item.GetProperty("mode").GetString() ?? "?",
+ item.TryGetProperty("waited_s", out var w) && w.TryGetInt32(out var seconds) ? seconds : 0));
+ var online = new List<string>();
+ var inMatch = new List<string>();
+ if (root.TryGetProperty("players", out var players) && players.ValueKind == JsonValueKind.Array)
+ foreach (var item in players.EnumerateArray())
+ {
+ string name = item.GetProperty("name").GetString() ?? "?";
+ string state = item.TryGetProperty("state", out var s) ? s.GetString() ?? "" : "";
+ if (state == "online") online.Add(name);
+ else if (state == "in_game") inMatch.Add(name);
+ }
+ bool paused = root.TryGetProperty("matchmaking_paused", out var p) && p.ValueKind == JsonValueKind.True;
+ int max = root.TryGetProperty("max_online", out var m) && m.TryGetInt32(out var maxValue) ? maxValue : 0;
+ ApplyRows(searching.ToArray(), online.ToArray(), inMatch.ToArray(), paused, max);
+ }
+ catch (Exception error) when (error is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException)
+ {
+ connection.ForeColor = Color.FromArgb(255, 120, 110);
+ connection.Text = "Cannot reach the server. Check your internet connection.";
+ }
+ finally { busy = false; }
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/PerfReport.cs b/Launcher/FifaStreetLauncher/PerfReport.cs
new file mode 100644
index 0000000..fb77df8
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/PerfReport.cs
@@ -0,0 +1,172 @@
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Runtime.InteropServices;
+using Microsoft.Win32;
+
+namespace FifaStreetLauncher;
+
+// Performance report: the runtime writes Logs\perf-report.json (FPS per scene) while the game runs; after each session
+// the launcher adds the PC and the settings, shows it on the page and, if the player agreed once, sends it to the
+// server anonymously (a random id per install, no name, no key).
+public partial class LauncherForm
+{
+ private static readonly string PerfPrefsPath = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ReStreet", "perf.json");
+ private static readonly string PerfHistoryPath = Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ReStreet", "perf-history.json");
+ private static readonly HttpClient PerfHttp = new() { Timeout = TimeSpan.FromSeconds(8) };
+ private string? lastPerfJson;
+ private bool perfShareCached = LoadPerfPrefs().Share == true; // shown on the page every second, read once
+
+ private sealed class PerfPrefs
+ {
+ public bool? Share { get; set; } // null = not asked yet
+ public string InstallId { get; set; } = Guid.NewGuid().ToString("N");
+ }
+
+ private static PerfPrefs LoadPerfPrefs()
+ {
+ try
+ {
+ if (File.Exists(PerfPrefsPath))
+ return JsonSerializer.Deserialize<PerfPrefs>(File.ReadAllText(PerfPrefsPath)) ?? new PerfPrefs();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) { }
+ return new PerfPrefs();
+ }
+
+ private static void SavePerfPrefs(PerfPrefs prefs)
+ {
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(PerfPrefsPath)!);
+ File.WriteAllText(PerfPrefsPath, JsonSerializer.Serialize(prefs));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+
+ // Called by the page: {cmd:"perfShare", value:true|false}.
+ private void SetPerfSharing(bool share)
+ {
+ var prefs = LoadPerfPrefs();
+ prefs.Share = share;
+ perfShareCached = share;
+ SavePerfPrefs(prefs);
+ if (share && lastPerfJson != null) _ = SendPerfAsync(lastPerfJson);
+ }
+
+ // After the game exits: build the full report from the runtime file plus this PC and the launch settings.
+ private void OnSessionEnded(string reportPath, string logFile, Dictionary<string, object?> settings, int exitCode)
+ {
+ try
+ {
+ // No report (the game closed in the first seconds or crashed before 30 s): still count the session.
+ var report = File.Exists(reportPath) ? JsonNode.Parse(File.ReadAllText(reportPath))!.AsObject()
+ : new JsonObject { ["version"] = 1, ["scenes"] = new JsonObject() };
+ var prefs = LoadPerfPrefs();
+ SavePerfPrefs(prefs); // keeps the install id stable from the first report on
+ report["install_id"] = prefs.InstallId;
+ report["launcher"] = LauncherVersion;
+ report["gpu_used"] = ReadGpuFromLog(logFile);
+ report["pc"] = new JsonObject
+ {
+ ["cpu"] = Registry.GetValue(@"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0",
+ "ProcessorNameString", "")?.ToString()?.Trim(),
+ ["threads"] = Environment.ProcessorCount,
+ ["ram_gb"] = Math.Round(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1073741824.0),
+ ["windows"] = Environment.OSVersion.Version.ToString(),
+ };
+ report["settings"] = JsonSerializer.SerializeToNode(settings);
+ report["exit_code"] = exitCode;
+ report["time"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+ report["integrated_gpu"] = IsIntegratedGpu(report["gpu_used"]?.ToString());
+ lastPerfJson = report.ToJsonString();
+ File.WriteAllText(reportPath, report.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
+
+ AppendPerfHistory(report);
+ PostToPage(new { type = "perf", report = JsonNode.Parse(lastPerfJson), ask = prefs.Share == null, share = prefs.Share == true });
+ PushPerfHistory();
+ if (prefs.Share == true) _ = SendPerfAsync(lastPerfJson);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException) { }
+ }
+
+ // Last 30 sessions on this PC, newest first, for the Performance page.
+ private static JsonArray LoadPerfHistory()
+ {
+ try { if (File.Exists(PerfHistoryPath)) return JsonNode.Parse(File.ReadAllText(PerfHistoryPath)) as JsonArray ?? new JsonArray(); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) { }
+ return new JsonArray();
+ }
+
+ private static void AppendPerfHistory(JsonObject report)
+ {
+ var history = LoadPerfHistory();
+ history.Insert(0, report.DeepClone());
+ while (history.Count > 30) history.RemoveAt(history.Count - 1);
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(PerfHistoryPath)!);
+ File.WriteAllText(PerfHistoryPath, history.ToJsonString());
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+
+ private void PushPerfHistory()
+ {
+ var adapters = new List<object>();
+ try { adapters.AddRange(DxgiAdapters.Enumerate().Select(a => new { name = a.Name, vram_mb = (long)(a.DedicatedMemory / 1048576) })); }
+ catch (Exception ex) when (ex is COMException or DllNotFoundException) { }
+ PostToPage(new { type = "perfHistory", history = LoadPerfHistory(), adapters, share = perfShareCached });
+ }
+
+ // A GPU with little dedicated memory while this PC also has one with 1 GB or more: the game ran on the slow one.
+ private static bool IsIntegratedGpu(string? gpu)
+ {
+ if (string.IsNullOrEmpty(gpu)) return false;
+ // APU-only PCs have no dedicated card to compare against, and AMD APUs report 512 MB+ of carve-out, so match names first.
+ if (System.Text.RegularExpressions.Regex.IsMatch(gpu,
+ @"^Intel(?!.*Arc(\(TM\))? [AB]\d).*(HD|UHD|Iris|Graphics)|Radeon(\(TM\))? Graphics$|Vega \d+ Graphics|Radeon(\(TM\))? \d{3}M\b",
+ System.Text.RegularExpressions.RegexOptions.IgnoreCase))
+ return true;
+ try
+ {
+ var list = DxgiAdapters.Enumerate();
+ var used = list.FirstOrDefault(a => a.Name.Trim().Equals(gpu.Trim(), StringComparison.OrdinalIgnoreCase));
+ return used != null && used.DedicatedMemory < 512UL << 20 && list.Any(a => a.DedicatedMemory >= 1UL << 30);
+ }
+ catch (Exception ex) when (ex is COMException or DllNotFoundException) { return false; }
+ }
+
+ // The adapter the runtime really used (it can differ from the launcher's choice on automatic selection).
+ // The log keeps earlier sessions (it rotates at 5 MB), so the last adapter line is this session's.
+ private static string? ReadGpuFromLog(string logFile)
+ {
+ string? gpu = null;
+ try
+ {
+ using var stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+ using var reader = new StreamReader(stream);
+ while (reader.ReadLine() is { } line)
+ {
+ int d = line.IndexOf("DXGI adapter: ", StringComparison.Ordinal);
+ if (d >= 0) gpu = line[(d + 14)..].Split(" (vendor")[0];
+ int v = line.IndexOf("Vulkan device '", StringComparison.Ordinal);
+ if (v >= 0) gpu = line[(v + 15)..].Split('\'')[0];
+ }
+ }
+ catch (IOException) { }
+ return gpu;
+ }
+
+ private async Task SendPerfAsync(string json)
+ {
+ string server = LoadOnlineConfig()?.Server ?? Regions[0].Address;
+ try
+ {
+ using var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
+ using var _ = await PerfHttp.PostAsync($"http://{server}:29812/v1/perf", content);
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) { /* best effort */ }
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/PresenceConfig.cs b/Launcher/FifaStreetLauncher/PresenceConfig.cs
new file mode 100644
index 0000000..c81ee20
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/PresenceConfig.cs
@@ -0,0 +1,239 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+
+namespace FifaStreetLauncher;
+
+/// <summary>
+/// Everything the Discord card needs that is not a launcher setting. It lives in
+/// <c>presence.json</c> next to the launcher so the Discord application id, the
+/// art asset keys and the wording can be changed without a rebuild, and so a
+/// player who does not want the card can switch it off in one place.
+///
+/// When the file is missing, presence is off. Nothing is written automatically:
+/// no file, no Discord application, no card.
+/// </summary>
+public sealed class PresenceConfig
+{
+ /// <summary>Master switch.</summary>
+ public bool Enabled { get; set; } = true;
+
+ /// <summary>
+ /// The Discord application id. The application's NAME is what Discord prints
+ /// after "Playing", so the application should be called "ReStreet PC".
+ /// </summary>
+ public string? ApplicationId { get; set; }
+
+ /// <summary>First line of the card. Empty leaves the line off.</summary>
+ public string Details { get; set; } = "FIFA Street 2012 Recompiled";
+
+ /// <summary>
+ /// Second line. Empty leaves the line off entirely rather than drawing a
+ /// blank one. Placeholders filled in by the launcher:
+ /// {api} {width} {height} {refresh} {internal} {profile} {gpu}
+ /// </summary>
+ public string State { get; set; } = "";
+
+ /// <summary>Art asset keys uploaded in the developer portal (Rich Presence, Art Assets).</summary>
+ public string LargeImage { get; set; } = "cover";
+ public string LargeText { get; set; } = "ReStreet - FIFA Street 2012 Recompiled";
+
+ /// <summary>Corner badge. Empty on both means no badge at all.</summary>
+ public string SmallImageD3D12 { get; set; } = "";
+ public string SmallImageVulkan { get; set; } = "";
+
+ /// <summary>Up to two buttons. Leave the list empty for none.</summary>
+ public List<PresenceButton> Buttons { get; set; } = new();
+
+ /// <summary>
+ /// Optional file the game side can write to say what is happening right now
+ /// (see docs/DISCORD-PRESENCE.md). Relative paths resolve against the folder
+ /// holding fifastreet.exe. Missing file means the card keeps the static text.
+ /// </summary>
+ public string StateFile { get; set; } = "Logs\\presence.txt";
+
+ /// <summary>
+ /// Wording per language, keyed by the two-letter code of the game language
+ /// chosen in the launcher: en, es, pt, fr, de, it. Anything a translation
+ /// leaves out falls back to the values above, so a partial translation is
+ /// fine and an unknown language is never a failure.
+ /// </summary>
+ public Dictionary<string, PresenceText> Translations { get; set; } = new();
+
+ /// <summary>Mode names for the base language, keyed as in <see cref="PresenceText.Modes"/>.</summary>
+ public Dictionary<string, string> Modes { get; set; } = new();
+
+ /// <summary>The Xbox language ids the launcher uses, as two-letter codes.</summary>
+ public static string LanguageCode(int gameLanguageId) => gameLanguageId switch
+ {
+ 3 => "de",
+ 4 => "fr",
+ 5 => "es",
+ 6 => "it",
+ 9 => "pt",
+ _ => "en",
+ };
+
+ /// <summary>The wording to use for one language, with every gap filled in.</summary>
+ public PresenceText Resolve(string languageCode)
+ {
+ var text = new PresenceText
+ {
+ Details = Details,
+ State = State,
+ LargeText = LargeText,
+ Modes = new Dictionary<string, string>(Modes, StringComparer.OrdinalIgnoreCase),
+ };
+
+ if (Translations is null || string.IsNullOrWhiteSpace(languageCode))
+ return text;
+
+ foreach (var pair in Translations)
+ {
+ if (!string.Equals(pair.Key, languageCode, StringComparison.OrdinalIgnoreCase))
+ continue;
+
+ var t = pair.Value;
+ if (t is null) break;
+ if (t.Details is not null) text.Details = t.Details;
+ if (t.State is not null) text.State = t.State;
+ if (t.LargeText is not null) text.LargeText = t.LargeText;
+ if (t.Modes is not null)
+ {
+ foreach (var mode in t.Modes)
+ text.Modes[mode.Key] = mode.Value;
+ }
+ break;
+ }
+
+ return text;
+ }
+
+ public static PresenceConfig Load(string launcherDir)
+ {
+ try
+ {
+ var path = Path.Combine(launcherDir, "presence.json");
+ if (!File.Exists(path)) return new PresenceConfig { Enabled = false };
+
+ var parsed = System.Text.Json.JsonSerializer.Deserialize<PresenceConfig>(
+ File.ReadAllText(path),
+ new System.Text.Json.JsonSerializerOptions
+ {
+ PropertyNameCaseInsensitive = true,
+ ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip,
+ AllowTrailingCommas = true
+ });
+
+ return parsed ?? new PresenceConfig { Enabled = false };
+ }
+ catch
+ {
+ // A broken file must not stop the game from starting.
+ return new PresenceConfig { Enabled = false };
+ }
+ }
+
+ public bool Usable =>
+ Enabled && !string.IsNullOrWhiteSpace(ApplicationId) &&
+ ulong.TryParse(ApplicationId!.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out _);
+}
+
+/// <summary>One language's wording. Null fields fall back to the base values.</summary>
+public sealed class PresenceText
+{
+ public string? Details { get; set; }
+ public string? State { get; set; }
+ public string? LargeText { get; set; }
+
+ /// <summary>
+ /// Mode names, keyed by the canonical name the game side writes
+ /// (main_menu, hit_the_streets, world_tour, online, practice, ...).
+ /// Keeping the key in English means the game side never has to know which
+ /// language the player picked.
+ /// </summary>
+ public Dictionary<string, string>? Modes { get; set; }
+}
+
+public sealed class PresenceButton
+{
+ public string Label { get; set; } = "";
+ public string Url { get; set; } = "";
+}
+
+/// <summary>
+/// Reads the optional state file the game side may write. Format is one
+/// <c>key=value</c> per line. Recognised keys:
+///
+/// details=Some text replaces the first line as written
+/// state=Some text replaces the second line as written
+/// mode=world_tour replaces the second line with the player's
+/// language version of that mode name
+///
+/// Unknown keys are ignored, so the game side can add more later without
+/// breaking an older launcher.
+/// </summary>
+public sealed class PresenceStateFile
+{
+ private readonly string? path;
+ private DateTime lastWrite = DateTime.MinValue;
+ private long lastLength = -1;
+
+ public string? Details { get; private set; }
+ public string? State { get; private set; }
+ public string? Mode { get; private set; }
+
+ public PresenceStateFile(string? path)
+ {
+ this.path = string.IsNullOrWhiteSpace(path) ? null : path;
+ }
+
+ /// <summary>Returns true when the contents changed since the last call.</summary>
+ public bool Poll()
+ {
+ if (path is null) return false;
+ try
+ {
+ var info = new FileInfo(path);
+ if (!info.Exists)
+ {
+ if (Details is null && State is null && Mode is null) return false;
+ Details = State = Mode = null;
+ lastWrite = DateTime.MinValue;
+ lastLength = -1;
+ return true;
+ }
+
+ if (info.LastWriteTimeUtc == lastWrite && info.Length == lastLength) return false;
+ lastWrite = info.LastWriteTimeUtc;
+ lastLength = info.Length;
+
+ string? details = null, state = null, mode = null;
+ using var stream = new FileStream(
+ path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ using var text = new StreamReader(stream);
+ for (var line = text.ReadLine(); line is not null; line = text.ReadLine())
+ {
+ int split = line.IndexOf('=');
+ if (split <= 0) continue;
+ var key = line.Substring(0, split).Trim().ToLowerInvariant();
+ var value = line.Substring(split + 1).Trim();
+ if (value.Length == 0) continue;
+ if (key == "details") details = value;
+ else if (key == "state") state = value;
+ else if (key == "mode") mode = value;
+ }
+
+ if (details == Details && state == State && mode == Mode) return false;
+ Details = details;
+ State = state;
+ Mode = mode;
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/Program.cs b/Launcher/FifaStreetLauncher/Program.cs
index 139bd8d..eb0e679 100644
--- a/Launcher/FifaStreetLauncher/Program.cs
+++ b/Launcher/FifaStreetLauncher/Program.cs
@@ -9,6 +9,30 @@ internal static class Program
static void Main(string[] args)
{
ApplicationConfiguration.Initialize();
+ // --preview-lobby <png>: the lobby window with sample players and no server.
+ if (args.Length >= 2 && args[0] == "--preview-lobby")
+ {
+ using var lobby = new LobbyForm("127.0.0.1", "SamuelitoDaVila");
+ lobby.Show();
+ lobby.PreviewRows();
+ Application.DoEvents();
+ using var shot = new System.Drawing.Bitmap(lobby.Width, lobby.Height);
+ lobby.DrawToBitmap(shot, new System.Drawing.Rectangle(System.Drawing.Point.Empty, lobby.Size));
+ shot.Save(args[1]);
+ return;
+ }
+ // --preview-friends <png>: the friends window with sample rows and no server (127.0.0.1 refuses the connection).
+ if (args.Length >= 2 && args[0] == "--preview-friends")
+ {
+ using var friends = new FriendsForm("127.0.0.1", "SamuelitoDaVila", new string('a', 32));
+ friends.Show();
+ friends.PreviewRows();
+ Application.DoEvents();
+ using var shot = new System.Drawing.Bitmap(friends.Width, friends.Height);
+ friends.DrawToBitmap(shot, new System.Drawing.Rectangle(System.Drawing.Point.Empty, friends.Size));
+ shot.Save(args[1]);
+ return;
+ }
if (args.Length >= 2 && args[0] == "--preview")
{
using var form = new LauncherForm();
diff --git a/Launcher/FifaStreetLauncher/RoomLaunch.cs b/Launcher/FifaStreetLauncher/RoomLaunch.cs
new file mode 100644
index 0000000..8369405
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/RoomLaunch.cs
@@ -0,0 +1,35 @@
+using System.Text.Json;
+
+namespace FifaStreetLauncher;
+
+// Launcher rooms: when someone joins this player's room, the launcher starts the game itself (once per room). The game
+// covers itself with its loading page and walks to the friend match set-up on its own (game DLL room driver); the
+// server closes the room once both players are in the lobby, which removes it from both launchers.
+public partial class LauncherForm
+{
+ private long roomLaunchedFor; // room id the game was started for
+
+ // Called with the player's current room on every social refresh (null when not in a room).
+ private void OnRoomState(JsonElement? room)
+ {
+ if (room is not { ValueKind: JsonValueKind.Object } r) return;
+ long id = r.TryGetProperty("id", out var idv) && idv.ValueKind == JsonValueKind.Number ? idv.GetInt64() : 0;
+ int players = r.TryGetProperty("players", out var pv) && pv.ValueKind == JsonValueKind.Array ? pv.GetArrayLength() : 0;
+ int seats = r.TryGetProperty("seats", out var sv) && sv.ValueKind == JsonValueKind.Number ? sv.GetInt32() : 2;
+ if (players < seats || id == roomLaunchedFor || !onlineModeBox.Checked) return;
+ BeginInvoke(async () =>
+ {
+ roomLaunchedFor = id;
+ // A game that is already open sits on some menu the room driver cannot walk from (it starts at the
+ // title screen), so the match is never created: close it and start it again for the room. The page
+ // tells the player (launcher.html roomSteps).
+ if (gameRunning && gameProcess is { } running)
+ {
+ try { running.Kill(); }
+ catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception) { }
+ for (int i = 0; i < 100 && gameRunning; ++i) await Task.Delay(100); // LaunchGame's finally clears it
+ }
+ if (!gameRunning) LaunchGame();
+ });
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/Updater.cs b/Launcher/FifaStreetLauncher/Updater.cs
new file mode 100644
index 0000000..71645f2
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/Updater.cs
@@ -0,0 +1,134 @@
+using System.Diagnostics;
+using System.Security.Cryptography;
+using System.Text.Json;
+
+namespace FifaStreetLauncher;
+
+// Automatic updates: at start the launcher asks GitHub for the latest ReStreet release. When it is newer than this
+// launcher and has a patch (.exe plus .exe.sha256), the page offers it. "Update" downloads both files from GitHub only,
+// checks the SHA-256, starts the patch with --auto-update (it waits for the launcher to close, installs with the saved
+// name, key and server, and reopens the launcher) and closes the launcher. Only installs that have the online patch.
+public partial class LauncherForm
+{
+ internal const string LauncherVersion = "2.0.3";
+ private const string ReleasesApi = "https://api.github.com/repos/samuelit0davila/fifa-street-pc-port/releases/latest";
+ private static readonly HttpClient UpdateHttp = CreateUpdateHttp();
+ private (string Version, string ExeUrl, string ShaUrl, string Notes)? pendingUpdate;
+ private bool updating;
+
+ private static HttpClient CreateUpdateHttp()
+ {
+ var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
+ http.DefaultRequestHeaders.UserAgent.ParseAdd("ReStreetLauncher/" + LauncherVersion);
+ return http;
+ }
+
+ // "v1.5.1-online-beta" -> 1.5.1; anything unparsable compares as 0.
+ internal static Version ParseVersion(string tag)
+ {
+ var digits = new string(tag.TrimStart('v', 'V').TakeWhile(c => char.IsDigit(c) || c == '.').ToArray()).Trim('.');
+ return Version.TryParse(digits.Contains('.') ? digits : digits + ".0", out var v) ? v : new Version(0, 0);
+ }
+
+ private static bool FromGitHub(string url) =>
+ Uri.TryCreate(url, UriKind.Absolute, out var u) && u.Scheme == "https" &&
+ (u.Host == "github.com" || u.Host.EndsWith(".githubusercontent.com", StringComparison.Ordinal));
+
+ private async Task CheckForUpdateAsync()
+ {
+ if (LoadOnlineConfig() == null) return; // offline installs update with the full installer
+ try
+ {
+ using var doc = JsonDocument.Parse(await UpdateHttp.GetStringAsync(ReleasesApi));
+ var r = doc.RootElement;
+ string tag = r.GetProperty("tag_name").GetString() ?? "";
+ if (ParseVersion(tag) <= ParseVersion(LauncherVersion)) return;
+ string? exe = null, sha = null;
+ foreach (var a in r.GetProperty("assets").EnumerateArray())
+ {
+ string name = a.GetProperty("name").GetString() ?? "", url = a.GetProperty("browser_download_url").GetString() ?? "";
+ if (!FromGitHub(url)) continue;
+ if (name.EndsWith(".exe.sha256", StringComparison.OrdinalIgnoreCase)) sha = url;
+ else if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) exe = url;
+ }
+ if (exe == null || sha == null) return;
+ string notes = r.TryGetProperty("name", out var n) ? n.GetString() ?? tag : tag;
+ pendingUpdate = (ParseVersion(tag).ToString(), exe, sha, notes);
+ // The page may still be loading (it asks again with "state"); give it a moment to say whether it is up.
+ await Task.Delay(4000);
+ if (PageConnected)
+ {
+ PostToPage(new { type = "update", version = pendingUpdate.Value.Version, notes });
+ }
+ else
+ {
+ // Classic interface (no WebView2, for example on Wine/Proton): ask with a plain dialog.
+ var answer = MessageBox.Show(this, "ReStreet " + pendingUpdate.Value.Version + " is available.\n\nThe launcher downloads it from GitHub, " +
+ "checks it and installs it for you. Your name, server and saves are kept.\n\nUpdate now?", "ReStreet update",
+ MessageBoxButtons.YesNo, MessageBoxIcon.Information);
+ if (answer == DialogResult.Yes)
+ {
+ UpdateStatus("Downloading the update...", true);
+ await InstallUpdateAsync();
+ }
+ }
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException)
+ {
+ // No network or GitHub unavailable: try again next start.
+ }
+ }
+
+ private async Task InstallUpdateAsync()
+ {
+ if (pendingUpdate is not { } u || updating || gameRunning) return;
+ updating = true;
+ string folder = Path.Combine(Path.GetTempPath(), "ReStreet-update");
+ string exePath = Path.Combine(folder, "ReStreet-Update-" + u.Version + ".exe");
+ try
+ {
+ Directory.CreateDirectory(folder);
+ string expected = (await UpdateHttp.GetStringAsync(u.ShaUrl)).Trim().Split(' ', '\t')[0].ToLowerInvariant();
+ if (expected.Length != 64) throw new InvalidDataException("bad checksum file");
+ using (var response = await UpdateHttp.GetAsync(u.ExeUrl, HttpCompletionOption.ResponseHeadersRead))
+ {
+ response.EnsureSuccessStatusCode();
+ long total = response.Content.Headers.ContentLength ?? 0, done = 0;
+ await using var src = await response.Content.ReadAsStreamAsync();
+ await using var dst = File.Create(exePath);
+ var buffer = new byte[1 << 20];
+ int read, lastPercent = -1;
+ while ((read = await src.ReadAsync(buffer)) > 0)
+ {
+ await dst.WriteAsync(buffer.AsMemory(0, read));
+ done += read;
+ int percent = total > 0 ? (int)(done * 100 / total) : 0;
+ if (percent != lastPercent) { lastPercent = percent; PostToPage(new { type = "updateProgress", percent }); }
+ }
+ }
+ string actual;
+ await using (var check = File.OpenRead(exePath)) actual = Convert.ToHexString(await SHA256.HashDataAsync(check)).ToLowerInvariant();
+ if (actual != expected) throw new InvalidDataException("the download is damaged (checksum mismatch)");
+
+ string root = AppContext.BaseDirectory.TrimEnd('\\');
+ Process.Start(new ProcessStartInfo(exePath)
+ {
+ ArgumentList = { "--auto-update", root, Environment.ProcessId.ToString() },
+ UseShellExecute = false,
+ });
+ Close();
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException or UnauthorizedAccessException or InvalidDataException or System.ComponentModel.Win32Exception)
+ {
+ updating = false;
+ try { File.Delete(exePath); } catch (IOException) { }
+ PostToPage(new { type = "updateError", message = "Update failed: " + ex.Message });
+ if (!PageConnected) UpdateStatus("Update failed: " + ex.Message, false);
+ }
+ }
+
+ private void PostToPage(object message)
+ {
+ SendToPage(JsonSerializer.Serialize(message));
+ }
+}
diff --git a/Launcher/FifaStreetLauncher/ui/bg.jpg b/Launcher/FifaStreetLauncher/ui/bg.jpg
new file mode 100644
index 0000000..77e897d
Binary files /dev/null and b/Launcher/FifaStreetLauncher/ui/bg.jpg differ
diff --git a/Launcher/FifaStreetLauncher/ui/lang.js b/Launcher/FifaStreetLauncher/ui/lang.js
new file mode 100644
index 0000000..8654068
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/ui/lang.js
@@ -0,0 +1,484 @@
+// Launcher language. The page and the launcher write their texts in English; this file shows them in the chosen
+// language: every text node (and title/placeholder) is looked up in D, whole, or in PATTERNS when it carries a name or
+// a number. A MutationObserver covers the texts the page and the launcher set later. The choice is kept in this
+// page's storage; with none, the Windows language is used (English when it is not one of these).
+(() => {
+ const LANGS = [['en', 'English'], ['pt-BR', 'Português (Brasil)'], ['es', 'Español'], ['fr', 'Français'], ['de', 'Deutsch'], ['it', 'Italiano']];
+ const COL = {'pt-BR': 0, es: 1, fr: 2, de: 3, it: 4};
+ // English: [Português (Brasil), Español, Français, Deutsch, Italiano]
+ const D = {
+ 'Home': ['Início', 'Inicio', 'Accueil', 'Start', 'Home'],
+ 'Social': ['Social', 'Social', 'Social', 'Social', 'Social'],
+ 'Matches': ['Partidas', 'Partidas', 'Matchs', 'Spiele', 'Partite'],
+ 'Online': ['Online', 'En línea', 'En ligne', 'Online', 'Online'],
+ 'Display': ['Tela', 'Pantalla', 'Affichage', 'Anzeige', 'Schermo'],
+ 'Graphics': ['Gráficos', 'Gráficos', 'Graphismes', 'Grafik', 'Grafica'],
+ 'Performance': ['Desempenho', 'Rendimiento', 'Performances', 'Leistung', 'Prestazioni'],
+ 'Controls': ['Controles', 'Controles', 'Commandes', 'Steuerung', 'Comandi'],
+ 'Advanced': ['Avançado', 'Avanzado', 'Avancé', 'Erweitert', 'Avanzate'],
+ 'CREDITS': ['CRÉDITOS', 'CRÉDITOS', 'CRÉDITS', 'CREDITS', 'CREDITI'],
+ 'Performance ·': ['Desempenho ·', 'Rendimiento ·', 'Performances ·', 'Leistung ·', 'Prestazioni ·'],
+ 'PT-BR translation ·': ['Tradução PT-BR ·', 'Traducción PT-BR ·', 'Traduction PT-BR ·', 'PT-BR-Übersetzung ·', 'Traduzione PT-BR ·'],
+ 'Offline': ['Offline', 'Sin conexión', 'Hors ligne', 'Offline', 'Offline'],
+ 'Not set up': ['Não configurado', 'Sin configurar', 'Non configuré', 'Nicht eingerichtet', 'Non configurato'],
+ 'Minimize': ['Minimizar', 'Minimizar', 'Réduire', 'Minimieren', 'Riduci a icona'],
+ 'Close': ['Fechar', 'Cerrar', 'Fermer', 'Schließen', 'Chiudi'],
+
+ 'is back online.': ['voltou ao online.', 'vuelve a estar en línea.', 'est de retour en ligne.', 'ist wieder online.', 'è di nuovo online.'],
+ 'Division Match, weekly Cups and Friend Matches with real players. Pick up where you left off.': [
+ 'Partidas de Divisão, Copas semanais e Partidas entre Amigos com jogadores reais. Continue de onde parou.',
+ 'Partidos de División, Copas semanales y Partidos entre Amigos con jugadores reales. Continúa donde lo dejaste.',
+ 'Matchs de Division, Coupes hebdomadaires et Matchs entre amis avec de vrais joueurs. Reprenez là où vous vous étiez arrêté.',
+ 'Divisionsspiele, wöchentliche Pokale und Freundschaftsspiele mit echten Spielern. Mach weiter, wo du aufgehört hast.',
+ 'Partite di Divisione, Coppe settimanali e Partite tra amici con giocatori veri. Riprendi da dove avevi lasciato.'],
+ 'PLAY': ['JOGAR', 'JUGAR', 'JOUER', 'SPIELEN', 'GIOCA'],
+ 'PLAYING': ['JOGANDO', 'JUGANDO', 'EN JEU', 'LÄUFT', 'IN GIOCO'],
+ 'ONLINE NOW': ['ONLINE AGORA', 'EN LÍNEA AHORA', 'EN LIGNE', 'JETZT ONLINE', 'ONLINE ORA'],
+ 'on your server': ['no seu servidor', 'en tu servidor', 'sur votre serveur', 'auf deinem Server', 'sul tuo server'],
+ 'SERVER': ['SERVIDOR', 'SERVIDOR', 'SERVEUR', 'SERVER', 'SERVER'],
+ 'GRAPHICS': ['GRÁFICOS', 'GRÁFICOS', 'GRAPHISMES', 'GRAFIK', 'GRAFICA'],
+ 'LAST SESSION': ['ÚLTIMA SESSÃO', 'ÚLTIMA SESIÓN', 'DERNIÈRE SESSION', 'LETZTE SITZUNG', 'ULTIMA SESSIONE'],
+ 'server offline': ['servidor offline', 'servidor sin conexión', 'serveur hors ligne', 'Server offline', 'server offline'],
+ 'Ready to play online': ['Pronto para jogar online', 'Listo para jugar en línea', 'Prêt à jouer en ligne', 'Bereit für Online-Spiele', 'Pronto per giocare online'],
+ 'Playing': ['Jogando', 'Jugando', 'En jeu', 'Im Spiel', 'In gioco'],
+ 'Online is off': ['Online desligado', 'En línea desactivado', 'En ligne désactivé', 'Online ist aus', 'Online disattivato'],
+ 'Ready to play offline (online is off)': ['Pronto para jogar offline (online desligado)', 'Listo para jugar sin conexión (en línea desactivado)',
+ 'Prêt à jouer hors ligne (en ligne désactivé)', 'Bereit zum Offline-Spielen (Online ist aus)', 'Pronto per giocare offline (online disattivato)'],
+ 'Online is not set up. Run the online patch again': ['O online não está configurado. Execute o patch online de novo',
+ 'El modo en línea no está configurado. Vuelve a ejecutar el parche en línea', "Le jeu en ligne n'est pas configuré. Relancez le patch en ligne",
+ 'Online ist nicht eingerichtet. Führe den Online-Patch erneut aus', "L'online non è configurato. Esegui di nuovo la patch online"],
+ 'Starting ReStreet...': ['Iniciando o ReStreet...', 'Iniciando ReStreet...', 'Lancement de ReStreet...', 'ReStreet wird gestartet...', 'Avvio di ReStreet...'],
+ 'Launch failed': ['Falha ao iniciar', 'Error al iniciar', 'Échec du lancement', 'Start fehlgeschlagen', 'Avvio non riuscito'],
+ 'Check your settings': ['Verifique suas configurações', 'Revisa tu configuración', 'Vérifiez vos réglages', 'Prüfe deine Einstellungen', 'Controlla le impostazioni'],
+ 'Could not start the game': ['Não foi possível iniciar o jogo', 'No se pudo iniciar el juego', 'Impossible de lancer le jeu', 'Das Spiel konnte nicht gestartet werden', 'Impossibile avviare il gioco'],
+ 'High internal resolution may reduce FPS': ['Resolução interna alta pode reduzir o FPS', 'Una resolución interna alta puede reducir los FPS',
+ 'Une résolution interne élevée peut réduire les FPS', 'Hohe interne Auflösung kann die FPS senken', 'Una risoluzione interna alta può ridurre gli FPS'],
+ 'Downloading the update...': ['Baixando a atualização...', 'Descargando la actualización...', 'Téléchargement de la mise à jour...', 'Update wird heruntergeladen...', "Download dell'aggiornamento..."],
+ 'Checking and installing. The launcher will reopen by itself.': ['Verificando e instalando. O launcher vai reabrir sozinho.',
+ 'Comprobando e instalando. El launcher se volverá a abrir solo.', 'Vérification et installation. Le launcher se rouvrira tout seul.',
+ 'Wird geprüft und installiert. Der Launcher öffnet sich danach von selbst.', 'Verifica e installazione. Il launcher si riaprirà da solo.'],
+ 'Update available': ['Atualização disponível', 'Actualización disponible', 'Mise à jour disponible', 'Update verfügbar', 'Aggiornamento disponibile'],
+ 'A new version of ReStreet is ready. The launcher downloads it from GitHub, checks it and installs it for you. Your name, server and saves are kept.': [
+ 'Uma nova versão do ReStreet está pronta. O launcher baixa do GitHub, verifica e instala para você. Seu nome, servidor e saves são mantidos.',
+ 'Hay una nueva versión de ReStreet lista. El launcher la descarga de GitHub, la comprueba y la instala por ti. Se conservan tu nombre, servidor y partidas guardadas.',
+ "Une nouvelle version de ReStreet est prête. Le launcher la télécharge depuis GitHub, la vérifie et l'installe pour vous. Votre nom, votre serveur et vos sauvegardes sont conservés.",
+ 'Eine neue Version von ReStreet ist bereit. Der Launcher lädt sie von GitHub, prüft sie und installiert sie für dich. Name, Server und Spielstände bleiben erhalten.',
+ 'Una nuova versione di ReStreet è pronta. Il launcher la scarica da GitHub, la verifica e la installa per te. Nome, server e salvataggi vengono mantenuti.'],
+ 'Update now': ['Atualizar agora', 'Actualizar ahora', 'Mettre à jour', 'Jetzt aktualisieren', 'Aggiorna ora'],
+ 'Update': ['Atualizar', 'Actualizar', 'Mettre à jour', 'Aktualisieren', 'Aggiorna'],
+ 'Later': ['Depois', 'Más tarde', 'Plus tard', 'Später', 'Più tardi'],
+ 'Help make ReStreet faster': ['Ajude a deixar o ReStreet mais rápido', 'Ayuda a que ReStreet sea más rápido', 'Aidez à rendre ReStreet plus rapide',
+ 'Hilf mit, ReStreet schneller zu machen', 'Aiuta a rendere ReStreet più veloce'],
+ 'After each session, send an anonymous performance report: your graphics card, processor, memory, settings and FPS. No name, no account. You can turn it off in Advanced.': [
+ 'Depois de cada sessão, envia um relatório anônimo de desempenho: placa de vídeo, processador, memória, configurações e FPS. Sem nome, sem conta. Dá para desligar em Avançado.',
+ 'Después de cada sesión, envía un informe de rendimiento anónimo: tarjeta gráfica, procesador, memoria, configuración y FPS. Sin nombre ni cuenta. Puedes desactivarlo en Avanzado.',
+ 'Après chaque session, envoie un rapport de performances anonyme : carte graphique, processeur, mémoire, réglages et FPS. Sans nom ni compte. Désactivable dans Avancé.',
+ 'Sendet nach jeder Sitzung einen anonymen Leistungsbericht: Grafikkarte, Prozessor, Speicher, Einstellungen und FPS. Kein Name, kein Konto. Unter Erweitert abschaltbar.',
+ 'Dopo ogni sessione invia un report anonimo sulle prestazioni: scheda video, processore, memoria, impostazioni e FPS. Nessun nome, nessun account. Puoi disattivarlo in Avanzate.'],
+ 'Share': ['Compartilhar', 'Compartir', 'Partager', 'Teilen', 'Condividi'],
+ 'No thanks': ['Não, obrigado', 'No, gracias', 'Non merci', 'Nein danke', 'No, grazie'],
+
+ 'Friends': ['Amigos', 'Amigos', 'Amis', 'Freunde', 'Amici'],
+ 'Requests': ['Pedidos', 'Solicitudes', 'Demandes', 'Anfragen', 'Richieste'],
+ 'Add a friend by name': ['Adicionar amigo pelo nome', 'Añadir un amigo por nombre', 'Ajouter un ami par son nom', 'Freund per Name hinzufügen', 'Aggiungi un amico per nome'],
+ 'Add friend': ['Adicionar amigo', 'Añadir amigo', 'Ajouter en ami', 'Als Freund hinzufügen', 'Aggiungi amico'],
+ 'Add friends from the Online list': ['Adicione amigos pela lista Online', 'Añade amigos desde la lista En línea', 'Ajoutez des amis depuis la liste En ligne',
+ 'Füge Freunde aus der Online-Liste hinzu', 'Aggiungi amici dalla lista Online'],
+ 'No requests': ['Nenhum pedido', 'Sin solicitudes', 'Aucune demande', 'Keine Anfragen', 'Nessuna richiesta'],
+ 'Nobody online': ['Ninguém online', 'Nadie en línea', 'Personne en ligne', 'Niemand online', 'Nessuno online'],
+ 'Wants to be your friend': ['Quer ser seu amigo', 'Quiere ser tu amigo', 'Veut être votre ami', 'Möchte dein Freund sein', 'Vuole essere tuo amico'],
+ 'Request sent': ['Pedido enviado', 'Solicitud enviada', 'Demande envoyée', 'Anfrage gesendet', 'Richiesta inviata'],
+ 'Remove friend': ['Remover amigo', 'Eliminar amigo', "Retirer l'ami", 'Freund entfernen', 'Rimuovi amico'],
+ 'Block': ['Bloquear', 'Bloquear', 'Bloquer', 'Blockieren', 'Blocca'],
+ 'Message': ['Mensagem', 'Mensaje', 'Message', 'Nachricht', 'Messaggio'],
+ 'Send message': ['Enviar mensagem', 'Enviar mensaje', 'Envoyer un message', 'Nachricht senden', 'Invia messaggio'],
+ 'Send': ['Enviar', 'Enviar', 'Envoyer', 'Senden', 'Invia'],
+ 'Report message': ['Denunciar mensagem', 'Denunciar mensaje', 'Signaler le message', 'Nachricht melden', 'Segnala messaggio'],
+ 'be nice, chat is moderated': ['seja gentil, o chat é moderado', 'sé amable, el chat está moderado', 'soyez sympa, le chat est modéré',
+ 'sei nett, der Chat wird moderiert', 'sii gentile, la chat è moderata'],
+ 'Chat is not available on this server yet': ['O chat ainda não está disponível neste servidor', 'El chat aún no está disponible en este servidor',
+ "Le chat n'est pas encore disponible sur ce serveur", 'Der Chat ist auf diesem Server noch nicht verfügbar', 'La chat non è ancora disponibile su questo server'],
+ 'Online patch not installed': ['Patch online não instalado', 'Parche en línea no instalado', 'Patch en ligne non installé', 'Online-Patch nicht installiert', 'Patch online non installata'],
+ 'Server': ['Servidor', 'Servidor', 'Serveur', 'Server', 'Server'],
+
+ 'Post a match or join one. Keep the game closed: when someone joins, ReStreet opens for both of you straight into the match lobby.': [
+ 'Crie uma partida ou entre numa. Deixe o jogo fechado: quando alguém entrar, o ReStreet abre para os dois direto no lobby da partida.',
+ 'Publica una partida o únete a una. Mantén el juego cerrado: cuando alguien se una, ReStreet se abrirá para los dos directamente en la sala de la partida.',
+ "Créez un match ou rejoignez-en un. Gardez le jeu fermé : quand quelqu'un rejoint, ReStreet s'ouvre pour vous deux directement dans le salon du match.",
+ 'Erstelle ein Spiel oder tritt einem bei. Lass das Spiel geschlossen: Sobald jemand beitritt, öffnet sich ReStreet für euch beide direkt in der Spiellobby.',
+ 'Crea una partita o unisciti a una. Tieni il gioco chiuso: quando qualcuno entra, ReStreet si apre per entrambi direttamente nella lobby della partita.'],
+ 'OPEN MATCHES': ['PARTIDAS ABERTAS', 'PARTIDAS ABIERTAS', 'MATCHS OUVERTS', 'OFFENE SPIELE', 'PARTITE APERTE'],
+ 'LOOKING FOR A MATCH IN THE GAME': ['PROCURANDO PARTIDA NO JOGO', 'BUSCANDO PARTIDA EN EL JUEGO', 'EN RECHERCHE DE MATCH DANS LE JEU', 'SUCHEN IM SPIEL', 'IN CERCA DI UNA PARTITA NEL GIOCO'],
+ 'Nobody is searching in the game right now.': ['Ninguém está procurando no jogo agora.', 'Nadie está buscando en el juego ahora mismo.',
+ 'Personne ne cherche dans le jeu pour le moment.', 'Gerade sucht niemand im Spiel.', 'Nessuno sta cercando nel gioco in questo momento.'],
+ 'Search the same mode in the game (Xbox LIVE) to be paired with them.': ['Procure o mesmo modo no jogo (Xbox LIVE) para jogar com eles.',
+ 'Busca el mismo modo en el juego (Xbox LIVE) para emparejarte con ellos.', 'Cherchez le même mode dans le jeu (Xbox LIVE) pour être associé à eux.',
+ 'Suche im Spiel (Xbox LIVE) denselben Modus, um mit ihnen gepaart zu werden.', 'Cerca la stessa modalità nel gioco (Xbox LIVE) per essere abbinato a loro.'],
+ 'No open matches right now. Post one and anyone on your server can join.': ['Nenhuma partida aberta agora. Crie uma e qualquer pessoa do seu servidor pode entrar.',
+ 'No hay partidas abiertas ahora mismo. Publica una y cualquiera de tu servidor podrá unirse.',
+ "Aucun match ouvert pour le moment. Créez-en un et n'importe qui sur votre serveur pourra le rejoindre.",
+ 'Gerade gibt es keine offenen Spiele. Erstelle eins, dann kann jeder auf deinem Server beitreten.',
+ 'Nessuna partita aperta al momento. Creane una e chiunque sul tuo server potrà unirsi.'],
+ '▶ Post match': ['▶ Criar partida', '▶ Publicar partida', '▶ Créer un match', '▶ Spiel erstellen', '▶ Crea partita'],
+ 'POST': ['CRIAR', 'PUBLICAR', 'CRÉER', 'ERSTELLEN', 'CREA'],
+ 'Title (optional), e.g. Chill 5-a-side, no skills spam': ['Título (opcional), ex.: 5 contra 5 tranquilo, sem spam de dribles',
+ 'Título (opcional), p. ej.: 5 contra 5 tranquilo, sin abusar de regates', 'Titre (facultatif), ex. : 5 contre 5 tranquille, sans spam de gestes',
+ 'Titel (optional), z. B. Entspanntes 5 gegen 5, kein Trick-Spam', 'Titolo (facoltativo), es.: 5 contro 5 tranquillo, niente spam di trick'],
+ '5-a-side': ['5 contra 5', '5 contra 5', '5 contre 5', '5 gegen 5', '5 contro 5'],
+ '6-a-side': ['6 contra 6', '6 contra 6', '6 contre 6', '6 gegen 6', '6 contro 6'],
+ 'Leave': ['Sair', 'Salir', 'Quitter', 'Verlassen', 'Esci'],
+ 'Leave game': ['Sair da partida', 'Salir de la partida', 'Quitter la partie', 'Spiel verlassen', 'Lascia la partita'],
+ 'Full': ['Cheia', 'Llena', 'Complet', 'Voll', 'Piena'],
+ 'Game ready!': ['Partida pronta!', '¡Partida lista!', 'Match prêt !', 'Spiel bereit!', 'Partita pronta!'],
+ "Both players are in. Press PLAY: the game opens and takes you to the match by itself. Don't touch anything until the match set-up appears.": [
+ 'Os dois jogadores estão dentro. Aperte JOGAR: o jogo abre e leva você até a partida sozinho. Não toque em nada até aparecer a configuração da partida.',
+ 'Los dos jugadores están dentro. Pulsa JUGAR: el juego se abre y te lleva solo a la partida. No toques nada hasta que aparezca la configuración de la partida.',
+ "Les deux joueurs sont là. Appuyez sur JOUER : le jeu s'ouvre et vous emmène tout seul au match. Ne touchez à rien jusqu'à l'écran de configuration du match.",
+ 'Beide Spieler sind drin. Drück SPIELEN: Das Spiel öffnet sich und bringt dich von selbst zum Spiel. Nichts anfassen, bis die Spieleinrichtung erscheint.',
+ 'Entrambi i giocatori sono dentro. Premi GIOCA: il gioco si apre e ti porta da solo alla partita. Non toccare nulla finché non compare la configurazione della partita.'],
+ 'Your game is restarting so it can open the match by itself.': ['Seu jogo está reiniciando para abrir a partida sozinho.',
+ 'Tu juego se está reiniciando para abrir la partida solo.', 'Votre jeu redémarre pour ouvrir le match tout seul.',
+ 'Dein Spiel startet neu, um das Spiel von selbst zu öffnen.', 'Il tuo gioco si sta riavviando per aprire la partita da solo.'],
+
+ 'Your online name and the server you play on. Each server has its own players, seasons and friends.': [
+ 'Seu nome online e o servidor onde você joga. Cada servidor tem seus próprios jogadores, temporadas e amigos.',
+ 'Tu nombre en línea y el servidor en el que juegas. Cada servidor tiene sus propios jugadores, temporadas y amigos.',
+ 'Votre nom en ligne et le serveur sur lequel vous jouez. Chaque serveur a ses propres joueurs, saisons et amis.',
+ 'Dein Online-Name und der Server, auf dem du spielst. Jeder Server hat eigene Spieler, Saisons und Freunde.',
+ 'Il tuo nome online e il server su cui giochi. Ogni server ha i suoi giocatori, stagioni e amici.'],
+ 'PLAY MODE': ['MODO DE JOGO', 'MODO DE JUEGO', 'MODE DE JEU', 'SPIELMODUS', 'MODALITÀ DI GIOCO'],
+ 'Play online': ['Jogar online', 'Jugar en línea', 'Jouer en ligne', 'Online spielen', 'Gioca online'],
+ 'Off: the game starts offline, with no server, friends or rooms.': ['Desligado: o jogo abre offline, sem servidor, amigos nem salas.',
+ 'Desactivado: el juego se abre sin conexión, sin servidor, amigos ni salas.', 'Désactivé : le jeu démarre hors ligne, sans serveur, amis ni salons.',
+ 'Aus: Das Spiel startet offline, ohne Server, Freunde und Räume.', 'Disattivato: il gioco parte offline, senza server, amici né stanze.'],
+ 'ACCOUNT': ['CONTA', 'CUENTA', 'COMPTE', 'KONTO', 'ACCOUNT'],
+ 'ONLINE NAME': ['NOME ONLINE', 'NOMBRE EN LÍNEA', 'NOM EN LIGNE', 'ONLINE-NAME', 'NOME ONLINE'],
+ 'STATUS': ['STATUS', 'ESTADO', 'STATUT', 'STATUS', 'STATO'],
+ 'To change your online name, run the online patch again.': ['Para mudar seu nome online, execute o patch online de novo.',
+ 'Para cambiar tu nombre en línea, vuelve a ejecutar el parche en línea.', 'Pour changer votre nom en ligne, relancez le patch en ligne.',
+ 'Um deinen Online-Namen zu ändern, führe den Online-Patch erneut aus.', 'Per cambiare il nome online, esegui di nuovo la patch online.'],
+
+ 'Screen, refresh rate and language.': ['Tela, taxa de atualização e idioma.', 'Pantalla, frecuencia de actualización e idioma.',
+ 'Écran, fréquence de rafraîchissement et langue.', 'Bildschirm, Bildwiederholrate und Sprache.', 'Schermo, frequenza di aggiornamento e lingua.'],
+ 'RESOLUTION': ['RESOLUÇÃO', 'RESOLUCIÓN', 'RÉSOLUTION', 'AUFLÖSUNG', 'RISOLUZIONE'],
+ 'REFRESH RATE': ['TAXA DE ATUALIZAÇÃO', 'FRECUENCIA', 'FRÉQUENCE', 'BILDWIEDERHOLRATE', 'FREQUENZA'],
+ 'DISPLAY MODE': ['MODO DE TELA', 'MODO DE PANTALLA', "MODE D'AFFICHAGE", 'ANZEIGEMODUS', 'MODALITÀ SCHERMO'],
+ 'MONITOR': ['MONITOR', 'MONITOR', 'ÉCRAN', 'MONITOR', 'MONITOR'],
+ 'GAME LANGUAGE': ['IDIOMA DO JOGO', 'IDIOMA DEL JUEGO', 'LANGUE DU JEU', 'SPIELSPRACHE', 'LINGUA DEL GIOCO'],
+ 'LAUNCHER LANGUAGE': ['IDIOMA DO LAUNCHER', 'IDIOMA DEL LAUNCHER', 'LANGUE DU LAUNCHER', 'LAUNCHER-SPRACHE', 'LINGUA DEL LAUNCHER'],
+ 'SYNC': ['SINCRONIZAÇÃO', 'SINCRONIZACIÓN', 'SYNCHRO', 'SYNCHRONISATION', 'SINCRONIZZAZIONE'],
+ 'No tearing, a new frame every refresh': ['Sem tearing, um quadro novo a cada atualização', 'Sin tearing, un fotograma nuevo en cada refresco',
+ 'Sans déchirure, une nouvelle image à chaque rafraîchissement', 'Kein Tearing, ein neues Bild pro Bildaufbau', 'Niente tearing, un nuovo fotogramma a ogni aggiornamento'],
+ 'Fullscreen': ['Tela cheia', 'Pantalla completa', 'Plein écran', 'Vollbild', 'Schermo intero'],
+ 'Windowed': ['Janela', 'Ventana', 'Fenêtré', 'Fenster', 'Finestra'],
+
+ 'Quality and performance. Weaker PC? Pick the Performance profile.': ['Qualidade e desempenho. PC mais fraco? Escolha o perfil Desempenho.',
+ '¿Calidad o rendimiento? ¿PC menos potente? Elige el perfil Rendimiento.', 'Qualité et performances. PC moins puissant ? Choisissez le profil Performances.',
+ 'Qualität und Leistung. Schwächerer PC? Wähle das Profil Leistung.', 'Qualità e prestazioni. PC meno potente? Scegli il profilo Prestazioni.'],
+ 'PROFILE': ['PERFIL', 'PERFIL', 'PROFIL', 'PROFIL', 'PROFILO'],
+ 'GRAPHICS API': ['API GRÁFICA', 'API GRÁFICA', 'API GRAPHIQUE', 'GRAFIK-API', 'API GRAFICA'],
+ 'POST-PROCESSING': ['PÓS-PROCESSAMENTO', 'POSPROCESADO', 'POST-TRAITEMENT', 'NACHBEARBEITUNG', 'POST-ELABORAZIONE'],
+ 'INTERNAL RESOLUTION': ['RESOLUÇÃO INTERNA', 'RESOLUCIÓN INTERNA', 'RÉSOLUTION INTERNE', 'INTERNE AUFLÖSUNG', 'RISOLUZIONE INTERNA'],
+ 'ANTI-ALIASING': ['ANTISSERRILHAMENTO', 'ANTIALIASING', 'ANTICRÉNELAGE', 'KANTENGLÄTTUNG', 'ANTIALIASING'],
+ 'Native 2x MSAA': ['MSAA 2x nativo', 'MSAA 2x nativo', 'MSAA 2x natif', 'Natives 2x MSAA', 'MSAA 2x nativo'],
+ 'Smoother edges, costs performance': ['Bordas mais suaves, custa desempenho', 'Bordes más suaves, cuesta rendimiento',
+ 'Bords plus lisses, coûte des performances', 'Glattere Kanten, kostet Leistung', 'Bordi più morbidi, costa prestazioni'],
+ 'Balanced (default)': ['Equilibrado (padrão)', 'Equilibrado (predeterminado)', 'Équilibré (par défaut)', 'Ausgewogen (Standard)', 'Bilanciato (predefinito)'],
+ 'Quality (strong PCs)': ['Qualidade (PCs fortes)', 'Calidad (PC potentes)', 'Qualité (PC puissants)', 'Qualität (starke PCs)', 'Qualità (PC potenti)'],
+ 'Performance (weak PCs)': ['Desempenho (PCs fracos)', 'Rendimiento (PC modestos)', 'Performances (PC modestes)', 'Leistung (schwache PCs)', 'Prestazioni (PC deboli)'],
+ 'Custom': ['Personalizado', 'Personalizado', 'Personnalisé', 'Benutzerdefiniert', 'Personalizzato'],
+ 'None': ['Nenhum', 'Ninguno', 'Aucun', 'Keins', 'Nessuno'],
+ 'FXAA Extreme': ['FXAA extremo', 'FXAA extremo', 'FXAA extrême', 'FXAA extrem', 'FXAA estremo'],
+ '1x - Native (1280 x 720)': ['1x - Nativa (1280 x 720)', '1x - Nativa (1280 x 720)', '1x - Native (1280 x 720)', '1x - Nativ (1280 x 720)', '1x - Nativa (1280 x 720)'],
+ 'Automatic': ['Automático', 'Automático', 'Automatique', 'Automatisch', 'Automatico'],
+ 'FRAME RATE LIMIT': ['LIMITE DE QUADROS', 'LÍMITE DE FOTOGRAMAS', "LIMITE D'IMAGES", 'BILDRATENBEGRENZUNG', 'LIMITE FOTOGRAMMI'],
+ 'SCALING': ['ESCALA', 'ESCALADO', "MISE À L'ÉCHELLE", 'SKALIERUNG', 'SCALATURA'],
+ 'ASPECT RATIO': ['PROPORÇÃO', 'PROPORCIÓN', "FORMAT D'IMAGE", 'SEITENVERHÄLTNIS', 'PROPORZIONI'],
+ 'ANISOTROPIC FILTERING': ['FILTRO ANISOTRÓPICO', 'FILTRADO ANISOTRÓPICO', 'FILTRAGE ANISOTROPE', 'ANISOTROPE FILTERUNG', 'FILTRO ANISOTROPICO'],
+ 'AMBIENT OCCLUSION': ['OCLUSÃO AMBIENTE', 'OCLUSIÓN AMBIENTAL', 'OCCLUSION AMBIANTE', 'UMGEBUNGSVERDECKUNG', 'OCCLUSIONE AMBIENTALE'],
+ 'Game MSAA (4x in 3D)': ['MSAA do jogo (4x no 3D)', 'MSAA del juego (4x en 3D)', 'MSAA du jeu (4x en 3D)', 'MSAA des Spiels (4x in 3D)', 'MSAA del gioco (4x nel 3D)'],
+ 'Bilinear': ['Bilinear', 'Bilineal', 'Bilinéaire', 'Bilinear', 'Bilineare'],
+ 'FSR 1 Quality': ['FSR 1 Qualidade', 'FSR 1 Calidad', 'FSR 1 Qualité', 'FSR 1 Qualität', 'FSR 1 Qualità'],
+ 'FSR 1 Balanced': ['FSR 1 Equilibrado', 'FSR 1 Equilibrado', 'FSR 1 Équilibré', 'FSR 1 Ausgewogen', 'FSR 1 Bilanciato'],
+ 'FSR 1 Performance': ['FSR 1 Desempenho', 'FSR 1 Rendimiento', 'FSR 1 Performances', 'FSR 1 Leistung', 'FSR 1 Prestazioni'],
+ 'FSR 1 Ultra Performance': ['FSR 1 Ultra desempenho', 'FSR 1 Ultra rendimiento', 'FSR 1 Ultra performances', 'FSR 1 Ultra-Leistung', 'FSR 1 Ultra prestazioni'],
+ 'Match screen': ['Igual à tela', 'Igual que la pantalla', "Comme l'écran", 'Wie der Bildschirm', 'Come lo schermo'],
+ '16:9 (console)': ['16:9 (console)', '16:9 (consola)', '16:9 (console)', '16:9 (Konsole)', '16:9 (console)'],
+ 'Screen refresh rate': ['Taxa da tela', 'Frecuencia de la pantalla', "Fréquence de l'écran", 'Bildwiederholrate', 'Frequenza dello schermo'],
+ 'No limit': ['Sem limite', 'Sin límite', 'Sans limite', 'Kein Limit', 'Nessun limite'],
+ 'Game default': ['Padrão do jogo', 'El del juego', 'Celui du jeu', 'Wie das Spiel', 'Quello del gioco'],
+ 'Off': ['Desligado', 'Desactivado', 'Désactivé', 'Aus', 'Disattivato'],
+
+ 'How ReStreet ran on this PC in your last sessions. Matches, replays and menus are measured separately.': [
+ 'Como o ReStreet rodou neste PC nas suas últimas sessões. Partidas, replays e menus são medidos separadamente.',
+ 'Cómo funcionó ReStreet en este PC en tus últimas sesiones. Partidos, repeticiones y menús se miden por separado.',
+ 'Comment ReStreet a tourné sur ce PC lors de vos dernières sessions. Matchs, ralentis et menus sont mesurés séparément.',
+ 'Wie ReStreet in deinen letzten Sitzungen auf diesem PC lief. Spiele, Wiederholungen und Menüs werden getrennt gemessen.',
+ 'Come è andato ReStreet su questo PC nelle ultime sessioni. Partite, replay e menu sono misurati separatamente.'],
+ 'THIS PC': ['ESTE PC', 'ESTE PC', 'CE PC', 'DIESER PC', 'QUESTO PC'],
+ 'GRAPHICS CARD USED': ['PLACA DE VÍDEO USADA', 'TARJETA GRÁFICA USADA', 'CARTE GRAPHIQUE UTILISÉE', 'VERWENDETE GRAFIKKARTE', 'SCHEDA VIDEO USATA'],
+ 'LAST MATCH FPS': ['FPS DA ÚLTIMA PARTIDA', 'FPS DEL ÚLTIMO PARTIDO', 'FPS DU DERNIER MATCH', 'FPS LETZTES SPIEL', 'FPS ULTIMA PARTITA'],
+ 'AVERAGE (10 SESSIONS)': ['MÉDIA (10 SESSÕES)', 'MEDIA (10 SESIONES)', 'MOYENNE (10 SESSIONS)', 'DURCHSCHNITT (10 SITZUNGEN)', 'MEDIA (10 SESSIONI)'],
+ 'CRASHES': ['TRAVAMENTOS', 'CIERRES', 'PLANTAGES', 'ABSTÜRZE', 'CRASH'],
+ 'SESSIONS': ['SESSÕES', 'SESIONES', 'SESSIONS', 'SITZUNGEN', 'SESSIONI'],
+ 'WHEN': ['QUANDO', 'CUÁNDO', 'QUAND', 'WANN', 'QUANDO'],
+ 'MATCH': ['PARTIDA', 'PARTIDO', 'MATCH', 'SPIEL', 'PARTITA'],
+ 'MENUS': ['MENUS', 'MENÚS', 'MENUS', 'MENÜS', 'MENU'],
+ 'REPLAYS': ['REPLAYS', 'REPETICIONES', 'RALENTIS', 'WIEDERHOLUNGEN', 'REPLAY'],
+ '1% LOW': ['1% MÍN.', '1% MÍN.', '1% MIN.', '1% TIEF', '1% MIN.'],
+ 'Play a session and your results appear here.': ['Jogue uma sessão e seus resultados aparecem aqui.', 'Juega una sesión y tus resultados aparecerán aquí.',
+ 'Jouez une session et vos résultats apparaîtront ici.', 'Spiel eine Sitzung, dann erscheinen hier deine Ergebnisse.', 'Gioca una sessione e i risultati appariranno qui.'],
+ 'crash': ['travou', 'cierre', 'plantage', 'Absturz', 'crash'],
+ 'in matches': ['nas partidas', 'en partidos', 'en match', 'in Spielen', 'nelle partite'],
+ 'average': ['média', 'media', 'moyenne', 'Durchschnitt', 'media'],
+ 'Share performance reports': ['Compartilhar relatórios de desempenho', 'Compartir informes de rendimiento', 'Partager les rapports de performances',
+ 'Leistungsberichte teilen', 'Condividi i report sulle prestazioni'],
+ 'The game ran on your': ['O jogo rodou na sua', 'El juego se ejecutó en tu', 'Le jeu a tourné sur votre', 'Das Spiel lief auf deiner', 'Il gioco è andato sulla tua'],
+ 'integrated graphics': ['placa de vídeo integrada', 'gráfica integrada', 'carte graphique intégrée', 'integrierten Grafik', 'grafica integrata'],
+ 'while this PC has a faster card. In Graphics, pick the dedicated card, or in Windows Settings > Display > Graphics set FifaStreet to High performance.': [
+ 'enquanto este PC tem uma placa mais rápida. Em Gráficos, escolha a placa dedicada, ou em Configurações do Windows > Tela > Gráficos defina o FifaStreet como Alto desempenho.',
+ 'mientras este PC tiene una tarjeta más rápida. En Gráficos, elige la tarjeta dedicada, o en Configuración de Windows > Pantalla > Gráficos pon FifaStreet en Alto rendimiento.',
+ 'alors que ce PC a une carte plus rapide. Dans Graphismes, choisissez la carte dédiée, ou dans Paramètres Windows > Affichage > Graphiques réglez FifaStreet sur Hautes performances.',
+ 'obwohl dieser PC eine schnellere Karte hat. Wähle unter Grafik die dedizierte Karte oder stelle in den Windows-Einstellungen > Anzeige > Grafik FifaStreet auf Hohe Leistung.',
+ 'mentre questo PC ha una scheda più veloce. In Grafica scegli la scheda dedicata, oppure in Impostazioni di Windows > Schermo > Grafica imposta FifaStreet su Prestazioni elevate.'],
+ 'Many stutters in matches. Keep': ['Muitos travamentos nas partidas. Mantenha', 'Muchos tirones en los partidos. Mantén', 'Beaucoup de saccades en match. Gardez',
+ 'Viele Ruckler in Spielen. Lass', 'Molti scatti nelle partite. Tieni'],
+ 'on; the first matches on a new PC stutter while shaders are built.': ['ligado; as primeiras partidas num PC novo travam enquanto os shaders são criados.',
+ 'activado; los primeros partidos en un PC nuevo tienen tirones mientras se crean los shaders.',
+ 'activé ; les premiers matchs sur un nouveau PC saccadent pendant la création des shaders.',
+ 'an; die ersten Spiele auf einem neuen PC ruckeln, während Shader erstellt werden.',
+ 'attivo; le prime partite su un PC nuovo scattano mentre vengono creati gli shader.'],
+ 'The game closed with an error in several recent sessions. Update your graphics driver, or open the logs in Advanced and send them to us on Discord.': [
+ 'O jogo fechou com erro em várias sessões recentes. Atualize o driver de vídeo, ou abra os logs em Avançado e mande para nós no Discord.',
+ 'El juego se cerró con un error en varias sesiones recientes. Actualiza el controlador gráfico, o abre los registros en Avanzado y envíanoslos por Discord.',
+ "Le jeu s'est fermé avec une erreur lors de plusieurs sessions récentes. Mettez à jour le pilote graphique, ou ouvrez les journaux dans Avancé et envoyez-les-nous sur Discord.",
+ 'Das Spiel wurde in mehreren letzten Sitzungen mit einem Fehler beendet. Aktualisiere den Grafiktreiber oder öffne die Logs unter Erweitert und schick sie uns auf Discord.',
+ 'Il gioco si è chiuso con un errore in diverse sessioni recenti. Aggiorna il driver video, oppure apri i log in Avanzate e inviaceli su Discord.'],
+ 'profile, a lower internal resolution, or the other graphics API.': [', uma resolução interna menor ou a outra API gráfica.',
+ ', una resolución interna más baja o la otra API gráfica.', ", une résolution interne plus basse ou l'autre API graphique.",
+ ', eine niedrigere interne Auflösung oder die andere Grafik-API.', ", una risoluzione interna più bassa o l'altra API grafica."],
+
+ 'Play without a controller. The keyboard works as an Xbox controller, so menus, matches and online all work; a controller still works too.': [
+ 'Jogue sem controle. O teclado funciona como um controle de Xbox, então menus, partidas e online funcionam; um controle também continua funcionando.',
+ 'Juega sin mando. El teclado funciona como un mando de Xbox, así que menús, partidos y en línea funcionan; un mando también sigue funcionando.',
+ 'Jouez sans manette. Le clavier fonctionne comme une manette Xbox : menus, matchs et jeu en ligne marchent ; une manette fonctionne aussi.',
+ 'Spiel ohne Controller. Die Tastatur funktioniert wie ein Xbox-Controller, also gehen Menüs, Spiele und Online; ein Controller geht trotzdem.',
+ 'Gioca senza controller. La tastiera funziona come un controller Xbox, quindi menu, partite e online funzionano; anche un controller continua a funzionare.'],
+ 'Play with keyboard': ['Jogar com teclado', 'Jugar con teclado', 'Jouer au clavier', 'Mit Tastatur spielen', 'Gioca con la tastiera'],
+ 'Turn on to use the keys below': ['Ligue para usar as teclas abaixo', 'Actívalo para usar las teclas de abajo', 'Activez pour utiliser les touches ci-dessous',
+ 'Einschalten, um die Tasten unten zu nutzen', 'Attiva per usare i tasti qui sotto'],
+ 'Mouse for skill moves': ['Mouse para dribles', 'Ratón para regates', 'Souris pour les gestes techniques', 'Maus für Tricks', 'Mouse per i trick'],
+ 'The mouse moves the right stick': ['O mouse move o analógico direito', 'El ratón mueve el stick derecho', 'La souris déplace le stick droit',
+ 'Die Maus bewegt den rechten Stick', 'Il mouse muove la levetta destra'],
+ 'Mouse sensitivity': ['Sensibilidade do mouse', 'Sensibilidad del ratón', 'Sensibilité de la souris', 'Mausempfindlichkeit', 'Sensibilità del mouse'],
+ 'LAYOUT': ['LAYOUT', 'DISPOSICIÓN', 'DISPOSITION', 'BELEGUNG', 'LAYOUT'],
+ 'Keyboard + mouse': ['Teclado + mouse', 'Teclado + ratón', 'Clavier + souris', 'Tastatur + Maus', 'Tastiera + mouse'],
+ 'Keyboard only': ['Só teclado', 'Solo teclado', 'Clavier seul', 'Nur Tastatur', 'Solo tastiera'],
+ 'Recommended. WASD to move, the mouse does skill moves; left click pass, right click shoot, middle click lob.': [
+ 'Recomendado. WASD para mover, o mouse faz os dribles; clique esquerdo passa, clique direito chuta, clique do meio lança.',
+ 'Recomendado. WASD para moverte, el ratón hace los regates; clic izquierdo pase, clic derecho tiro, clic central pase alto.',
+ 'Recommandé. WASD pour bouger, la souris fait les gestes techniques ; clic gauche passe, clic droit tir, clic du milieu lob.',
+ 'Empfohlen. WASD zum Bewegen, die Maus macht Tricks; Linksklick Pass, Rechtsklick Schuss, Mittelklick Lupfer.',
+ 'Consigliato. WASD per muoverti, il mouse fa i trick; clic sinistro passaggio, clic destro tiro, clic centrale pallonetto.'],
+ 'WASD to move, J pass, K shoot, L lob, I manual pass, arrows for skill moves.': [
+ 'WASD para mover, J passe, K chute, L lançamento, I passe manual, setas para dribles.',
+ 'WASD para moverte, J pase, K tiro, L pase alto, I pase manual, flechas para regates.',
+ 'WASD pour bouger, J passe, K tir, L lob, I passe manuelle, flèches pour les gestes techniques.',
+ 'WASD zum Bewegen, J Pass, K Schuss, L Lupfer, I manueller Pass, Pfeiltasten für Tricks.',
+ 'WASD per muoverti, J passaggio, K tiro, L pallonetto, I passaggio manuale, frecce per i trick.'],
+ 'Both: Shift sprint, Space Street Ball Control (hold), Q flair (hold), E juggle. Menus: Enter select, Backspace back, Esc pause.': [
+ 'Os dois: Shift corre, Space controle de bola (segurar), Q floreio (segurar), E embaixadinha. Menus: Enter seleciona, Backspace volta, Esc pausa.',
+ 'Ambos: Shift esprint, Space control del balón (mantener), Q floritura (mantener), E toques. Menús: Enter seleccionar, Backspace volver, Esc pausa.',
+ 'Les deux : Shift sprint, Space contrôle du ballon (maintenir), Q fioriture (maintenir), E jonglage. Menus : Enter valider, Backspace retour, Esc pause.',
+ 'Beide: Shift Sprint, Space Ballkontrolle (halten), Q Flair (halten), E Jonglieren. Menüs: Enter auswählen, Backspace zurück, Esc Pause.',
+ 'Entrambi: Shift scatto, Space controllo palla (tieni), Q flair (tieni), E palleggio. Menu: Enter seleziona, Backspace indietro, Esc pausa.'],
+ 'Click a key to change it, then press the new key (or a mouse button). Each action can have two keys.': [
+ 'Clique numa tecla para mudar e aperte a nova tecla (ou um botão do mouse). Cada ação pode ter duas teclas.',
+ 'Haz clic en una tecla para cambiarla y pulsa la nueva (o un botón del ratón). Cada acción puede tener dos teclas.',
+ 'Cliquez sur une touche pour la changer, puis appuyez sur la nouvelle (ou un bouton de souris). Chaque action peut avoir deux touches.',
+ 'Klick auf eine Taste, um sie zu ändern, dann drück die neue Taste (oder eine Maustaste). Jede Aktion kann zwei Tasten haben.',
+ 'Clicca un tasto per cambiarlo, poi premi il nuovo tasto (o un pulsante del mouse). Ogni azione può avere due tasti.'],
+ 'cancels,': ['cancela,', 'cancela,', 'annule,', 'bricht ab,', 'annulla,'],
+ 'right-click': ['clique direito', 'clic derecho', 'clic droit', 'Rechtsklick', 'clic destro'],
+ 'clears a key.': ['limpa uma tecla.', 'borra una tecla.', 'efface une touche.', 'löscht eine Taste.', 'cancella un tasto.'],
+ 'Press a key...': ['Aperte uma tecla...', 'Pulsa una tecla...', 'Appuyez sur une touche...', 'Drück eine Taste...', 'Premi un tasto...'],
+ 'That key cannot be used.': ['Essa tecla não pode ser usada.', 'Esa tecla no se puede usar.', 'Cette touche ne peut pas être utilisée.',
+ 'Diese Taste kann nicht verwendet werden.', 'Quel tasto non può essere usato.'],
+ 'Saved.': ['Salvo.', 'Guardado.', 'Enregistré.', 'Gespeichert.', 'Salvato.'],
+ 'Cancelled.': ['Cancelado.', 'Cancelado.', 'Annulé.', 'Abgebrochen.', 'Annullato.'],
+ 'MOVEMENT (LEFT STICK)': ['MOVIMENTO (ANALÓGICO ESQUERDO)', 'MOVIMIENTO (STICK IZQUIERDO)', 'DÉPLACEMENT (STICK GAUCHE)', 'BEWEGUNG (LINKER STICK)', 'MOVIMENTO (LEVETTA SINISTRA)'],
+ 'SKILL MOVES (RIGHT STICK)': ['DRIBLES (ANALÓGICO DIREITO)', 'REGATES (STICK DERECHO)', 'GESTES TECHNIQUES (STICK DROIT)', 'TRICKS (RECHTER STICK)', 'TRICK (LEVETTA DESTRA)'],
+ 'BUTTONS': ['BOTÕES', 'BOTONES', 'BOUTONS', 'TASTEN', 'PULSANTI'],
+ 'Move up': ['Mover para cima', 'Mover arriba', 'Aller en haut', 'Nach oben', 'Muovi su'],
+ 'Move down': ['Mover para baixo', 'Mover abajo', 'Aller en bas', 'Nach unten', 'Muovi giù'],
+ 'Move left': ['Mover para a esquerda', 'Mover a la izquierda', 'Aller à gauche', 'Nach links', 'Muovi a sinistra'],
+ 'Move right': ['Mover para a direita', 'Mover a la derecha', 'Aller à droite', 'Nach rechts', 'Muovi a destra'],
+ 'Left stick click': ['Clique do analógico esquerdo', 'Pulsar stick izquierdo', 'Clic stick gauche', 'Linken Stick drücken', 'Pressione levetta sinistra'],
+ 'Skill up': ['Drible para cima', 'Regate arriba', 'Geste en haut', 'Trick nach oben', 'Trick su'],
+ 'Skill down': ['Drible para baixo', 'Regate abajo', 'Geste en bas', 'Trick nach unten', 'Trick giù'],
+ 'Skill left': ['Drible para a esquerda', 'Regate a la izquierda', 'Geste à gauche', 'Trick nach links', 'Trick a sinistra'],
+ 'Skill right': ['Drible para a direita', 'Regate a la derecha', 'Geste à droite', 'Trick nach rechts', 'Trick a destra'],
+ 'Stand on the ball / neck stall': ['Pisar na bola / bola no pescoço', 'Pisar el balón / balón en la nuca', 'Pied sur le ballon / ballon sur la nuque',
+ 'Fuß auf den Ball / Ball im Nacken', 'Piede sulla palla / palla sul collo'],
+ 'Pass (tap twice for a one-two)': ['Passe (toque duas vezes para tabela)', 'Pase (pulsa dos veces para una pared)', 'Passe (deux fois pour un une-deux)',
+ 'Pass (zweimal tippen für Doppelpass)', 'Passaggio (premi due volte per un uno-due)'],
+ 'Shoot': ['Chutar', 'Tirar', 'Tirer', 'Schießen', 'Tira'],
+ 'Lob pass': ['Lançamento', 'Pase alto', 'Passe lobée', 'Lupfer', 'Pallonetto'],
+ 'Manual pass': ['Passe manual', 'Pase manual', 'Passe manuelle', 'Manueller Pass', 'Passaggio manuale'],
+ 'Hold: Street Ball Control / jockey': ['Segurar: controle de bola / marcação', 'Mantener: control del balón / marcar', 'Maintenir : contrôle du ballon / jockey',
+ 'Halten: Ballkontrolle / Stellen', 'Tieni: controllo palla / jockey'],
+ 'Sprint / Panna': ['Correr / Caneta', 'Esprint / Caño', 'Sprint / Petit pont', 'Sprint / Tunnel', 'Scatto / Tunnel'],
+ 'Hold: flair pass or shot': ['Segurar: passe ou chute de efeito', 'Mantener: pase o tiro de fantasía', 'Maintenir : passe ou tir de fantaisie',
+ 'Halten: Flair-Pass oder -Schuss', 'Tieni: passaggio o tiro di fantasia'],
+ 'Juggle (hold: knees)': ['Embaixadinha (segurar: joelhos)', 'Toques (mantener: rodillas)', 'Jonglage (maintenir : genoux)', 'Jonglieren (halten: Knie)', 'Palleggio (tieni: ginocchia)'],
+ 'Pause': ['Pausa', 'Pausa', 'Pause', 'Pause', 'Pausa'],
+ 'Back': ['Voltar', 'Atrás', 'Retour', 'Zurück', 'Indietro'],
+ 'D-pad up': ['Direcional para cima', 'Cruceta arriba', 'Croix haut', 'Steuerkreuz oben', 'Croce su'],
+ 'D-pad down': ['Direcional para baixo', 'Cruceta abajo', 'Croix bas', 'Steuerkreuz unten', 'Croce giù'],
+ 'D-pad left': ['Direcional para a esquerda', 'Cruceta izquierda', 'Croix gauche', 'Steuerkreuz links', 'Croce sinistra'],
+ 'D-pad right': ['Direcional para a direita', 'Cruceta derecha', 'Croix droite', 'Steuerkreuz rechts', 'Croce destra'],
+
+ 'Game files and renderer options for textures, lighting, black screens and stutter.': [
+ 'Arquivos do jogo e opções do renderizador para texturas, iluminação, telas pretas e travamentos.',
+ 'Archivos del juego y opciones del renderizador para texturas, iluminación, pantallas negras y tirones.',
+ "Fichiers du jeu et options du rendu pour les textures, l'éclairage, les écrans noirs et les saccades.",
+ 'Spieldateien und Renderer-Optionen für Texturen, Beleuchtung, schwarze Bildschirme und Ruckler.',
+ 'File di gioco e opzioni del renderer per texture, illuminazione, schermate nere e scatti.'],
+ 'GAME FILES': ['ARQUIVOS DO JOGO', 'ARCHIVOS DEL JUEGO', 'FICHIERS DU JEU', 'SPIELDATEIEN', 'FILE DI GIOCO'],
+ 'GAME EXECUTABLE': ['EXECUTÁVEL DO JOGO', 'EJECUTABLE DEL JUEGO', 'EXÉCUTABLE DU JEU', 'SPIEL-EXE', 'ESEGUIBILE DEL GIOCO'],
+ 'GAME DATA FOLDER': ['PASTA DE DADOS DO JOGO', 'CARPETA DE DATOS DEL JUEGO', 'DOSSIER DES DONNÉES DU JEU', 'SPIELDATENORDNER', 'CARTELLA DATI DEL GIOCO'],
+ 'Browse': ['Procurar', 'Examinar', 'Parcourir', 'Durchsuchen', 'Sfoglia'],
+ 'COMPATIBILITY': ['COMPATIBILIDADE', 'COMPATIBILIDAD', 'COMPATIBILITÉ', 'KOMPATIBILITÄT', 'COMPATIBILITÀ'],
+ 'Full (compatible)': ['Completo (compatível)', 'Completo (compatible)', 'Complet (compatible)', 'Voll (kompatibel)', 'Completo (compatibile)'],
+ 'Some (recommended)': ['Parcial (recomendado)', 'Parcial (recomendado)', 'Partiel (recommandé)', 'Teilweise (empfohlen)', 'Parziale (consigliato)'],
+ 'Fast (more FPS, may glitch)': ['Rápido (mais FPS, pode dar falhas)', 'Rápido (más FPS, puede fallar)', 'Rapide (plus de FPS, peut buguer)',
+ 'Schnell (mehr FPS, evtl. Fehler)', 'Veloce (più FPS, può avere difetti)'],
+ 'None (experimental)': ['Nenhum (experimental)', 'Ninguno (experimental)', 'Aucun (expérimental)', 'Keins (experimentell)', 'Nessuno (sperimentale)'],
+ 'Frame stats log': ['Log de estatísticas de quadros', 'Registro de estadísticas de fotogramas', "Journal des statistiques d'images", 'Bildstatistik-Log', 'Log statistiche fotogrammi'],
+ 'Open logs': ['Abrir logs', 'Abrir registros', 'Ouvrir les journaux', 'Logs öffnen', 'Apri log'],
+ 'Open game folder': ['Abrir pasta do jogo', 'Abrir carpeta del juego', 'Ouvrir le dossier du jeu', 'Spielordner öffnen', 'Apri cartella del gioco'],
+ 'Desktop shortcut': ['Atalho na área de trabalho', 'Acceso directo en el escritorio', 'Raccourci sur le bureau', 'Desktop-Verknüpfung', 'Collegamento sul desktop'],
+ 'Could not create the shortcut': ['Não foi possível criar o atalho', 'No se pudo crear el acceso directo', 'Impossible de créer le raccourci',
+ 'Verknüpfung konnte nicht erstellt werden', 'Impossibile creare il collegamento'],
+ };
+ // Texts with a name or a number inside: $1 is the captured part as is, $T1 the captured part translated.
+ const PATTERNS = [
+ [/^ReStreet (.+) is available$/, ['ReStreet $1 está disponível', 'ReStreet $1 está disponible', 'ReStreet $1 est disponible', 'ReStreet $1 ist verfügbar', 'ReStreet $1 è disponibile']],
+ [/^Downloading the update\.\.\. (\d+)%$/, ['Baixando a atualização... $1%', 'Descargando la actualización... $1%', 'Téléchargement de la mise à jour... $1%',
+ 'Update wird heruntergeladen... $1%', "Download dell'aggiornamento... $1%"]],
+ [/^Ready to play online as (.+)$/, ['Pronto para jogar online como $1', 'Listo para jugar en línea como $1', 'Prêt à jouer en ligne en tant que $1',
+ 'Bereit, online als $1 zu spielen', 'Pronto per giocare online come $1']],
+ [/^Loading your match with (.+)\.\.\.$/, ['Carregando sua partida com $1...', 'Cargando tu partida con $1...', 'Chargement de votre match avec $1...',
+ 'Dein Spiel mit $1 wird geladen...', 'Caricamento della partita con $1...']],
+ [/^(\d+) players online$/, ['$1 jogadores online', '$1 jugadores en línea', '$1 joueurs en ligne', '$1 Spieler online', '$1 giocatori online']],
+ [/^(.+) server$/, ['Servidor $1', 'Servidor $1', 'Serveur $1', 'Server $1', 'Server $1']],
+ [/^(.+) keys set\.$/, ['Teclas de $1 definidas.', 'Teclas de $1 configuradas.', 'Touches $1 définies.', '$1-Tasten gesetzt.', 'Tasti $1 impostati.']],
+ [/^(.+) moved here from (.+)\.$/, ['$1 foi movida de "$T2" para cá.', '$1 se movió aquí desde "$T2".', '$1 a été déplacée ici depuis « $T2 ».',
+ '$1 wurde von „$T2" hierher verschoben.', '$1 è stato spostato qui da "$T2".']],
+ [/^(.+) opens a ReStreet menu in the game\. Pick another key\.$/, ['$1 abre um menu do ReStreet no jogo. Escolha outra tecla.',
+ '$1 abre un menú de ReStreet en el juego. Elige otra tecla.', '$1 ouvre un menu ReStreet dans le jeu. Choisissez une autre touche.',
+ '$1 öffnet ein ReStreet-Menü im Spiel. Wähle eine andere Taste.', '$1 apre un menu di ReStreet nel gioco. Scegli un altro tasto.']],
+ [/^Matches ran at (\S+) FPS, below your (\S+) Hz\. Try the$/, ['As partidas rodaram a $1 FPS, abaixo dos seus $2 Hz. Tente o perfil',
+ 'Los partidos fueron a $1 FPS, por debajo de tus $2 Hz. Prueba el perfil', 'Les matchs tournaient à $1 FPS, sous vos $2 Hz. Essayez le profil',
+ 'Spiele liefen mit $1 FPS, unter deinen $2 Hz. Probier das Profil', 'Le partite andavano a $1 FPS, sotto i tuoi $2 Hz. Prova il profilo']],
+ [/^Your (.+) game at (.+) is open, waiting for a player\.\.\.$/, ['Sua partida de $T1 em $2 está aberta, esperando um jogador...',
+ 'Tu partida de $T1 en $2 está abierta, esperando a un jugador...', 'Votre match $T1 à $2 est ouvert, en attente d\'un joueur...',
+ 'Dein $T1-Spiel in $2 ist offen und wartet auf einen Spieler...', 'La tua partita $T1 a $2 è aperta, in attesa di un giocatore...']],
+ [/^Game ready with (.+?)! (.*)$/, ['Partida pronta com $1! $T2', '¡Partida lista con $1! $T2', 'Match prêt avec $1 ! $T2', 'Spiel bereit mit $1! $T2', 'Partita pronta con $1! $T2']],
+ [/^(Your game is restarting so it can open the match by itself\. )?ReStreet is opening straight into your (.+) match lobby\.$/, [
+ '$T1O ReStreet está abrindo direto no lobby da sua partida de $T2.', '$T1ReStreet se está abriendo directamente en la sala de tu partida de $T2.',
+ "$T1ReStreet s'ouvre directement dans le salon de votre match $T2.", '$T1ReStreet öffnet sich direkt in der Lobby deines $T2-Spiels.',
+ '$T1ReStreet si sta aprendo direttamente nella lobby della tua partita $T2.']],
+ [/^Could not change the server: (.*)$/, ['Não foi possível trocar de servidor: $1', 'No se pudo cambiar de servidor: $1', 'Impossible de changer de serveur : $1',
+ 'Server konnte nicht gewechselt werden: $1', 'Impossibile cambiare server: $1']],
+ [/^Update failed: (.*)$/, ['Falha na atualização: $1', 'Error en la actualización: $1', 'Échec de la mise à jour : $1', 'Update fehlgeschlagen: $1', 'Aggiornamento non riuscito: $1']],
+ ];
+
+ let lang = null;
+ try { lang = localStorage.getItem('restreet.uiLang'); } catch (e) { /* no storage: the Windows language below */ }
+ if (!LANGS.some(l => l[0] === lang)) {
+ const n = (navigator.language || 'en').toLowerCase();
+ lang = n.startsWith('pt') ? 'pt-BR' : (['es', 'fr', 'de', 'it'].find(c => n.startsWith(c)) || 'en');
+ }
+
+ function tr(text) {
+ if (lang === 'en' || !text) return text;
+ const m = text.match(/^(\s*)([\s\S]*?)(\s*)$/);
+ const core = m[2], col = COL[lang];
+ let out = D[core] && D[core][col];
+ if (!out) {
+ for (const [re, row] of PATTERNS) {
+ const g = core.match(re);
+ if (!g) continue;
+ out = row[col].replace(/\$T(\d)/g, (_, i) => tr(g[i] || '')).replace(/\$(\d)/g, (_, i) => g[i] || '');
+ break;
+ }
+ }
+ return out ? m[1] + out + m[3] : text;
+ }
+
+ // English source of each text node, so a later language change (or a text the page rewrites) starts from it.
+ const source = new WeakMap(), shown = new WeakMap();
+ function doText(node) {
+ const now = node.nodeValue;
+ const en = shown.get(node) === now ? source.get(node) : now;
+ const out = tr(en);
+ source.set(node, en); shown.set(node, out);
+ if (out !== now) node.nodeValue = out;
+ }
+ function doAttrs(el) {
+ for (const a of ['title', 'placeholder', 'aria-label']) {
+ if (!el.hasAttribute(a)) continue;
+ const key = 'en' + a.replace('-', '');
+ if (el.dataset[key] === undefined || el.getAttribute(a) !== el.dataset[key + 'Out']) el.dataset[key] = el.getAttribute(a);
+ const out = tr(el.dataset[key]);
+ el.dataset[key + 'Out'] = out;
+ if (out !== el.getAttribute(a)) el.setAttribute(a, out);
+ }
+ }
+ function walk(root) {
+ if (root.nodeType === 3) { doText(root); return; }
+ if (root.nodeType !== 1 || root.closest('script,style,textarea')) return;
+ doAttrs(root);
+ root.querySelectorAll('[title],[placeholder],[aria-label]').forEach(doAttrs);
+ const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
+ acceptNode: n => n.parentElement && n.parentElement.closest('script,style,textarea') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT,
+ });
+ for (let n = w.nextNode(); n; n = w.nextNode()) doText(n);
+ }
+ new MutationObserver(list => {
+ for (const m of list) {
+ if (m.type === 'characterData') doText(m.target);
+ else m.addedNodes.forEach(walk);
+ }
+ }).observe(document.body, {childList: true, subtree: true, characterData: true});
+
+ // The status box is an input: its value comes from the launcher in English on every refresh.
+ if (typeof window.render === 'function') {
+ const base = window.render;
+ window.render = s => { base(s); const st = document.getElementById('ostatus'); if (st) st.value = tr(st.value); };
+ }
+
+ // LAUNCHER LANGUAGE (Display page).
+ const dd = document.querySelector('.dd[data-id="uiLang"]');
+ function fillLang() {
+ if (!dd) return;
+ dd.querySelector('.dd-btn span').textContent = LANGS.find(l => l[0] === lang)[1];
+ const listEl = dd.querySelector('.dd-list'); listEl.innerHTML = '';
+ for (const [code, label] of LANGS) {
+ const o = document.createElement('div'); o.className = 'dd-opt' + (code === lang ? ' sel' : ''); o.textContent = label;
+ o.onclick = e => { e.stopPropagation(); dd.classList.remove('open'); setLang(code); };
+ listEl.appendChild(o);
+ }
+ }
+ function setLang(code) {
+ lang = code;
+ try { localStorage.setItem('restreet.uiLang', code); } catch (e) { /* this session only */ }
+ document.documentElement.lang = code;
+ walk(document.body);
+ fillLang();
+ }
+ document.documentElement.lang = lang;
+ walk(document.body);
+ fillLang();
+})();
diff --git a/Launcher/FifaStreetLauncher/ui/launcher.html b/Launcher/FifaStreetLauncher/ui/launcher.html
new file mode 100644
index 0000000..c465b39
--- /dev/null
+++ b/Launcher/FifaStreetLauncher/ui/launcher.html
@@ -0,0 +1,727 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><title>ReStreet</title>
+<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
+<style>
+:root{
+ --glass: rgba(255,255,255,.05);
+ --glass-strong: rgba(255,255,255,.09);
+ --edge: rgba(255,255,255,.28);
+ --ink: #fff; --muted: rgba(255,255,255,.66);
+ --accent: #ffcf2e; --accent-2: #ff7a2e;
+}
+*{box-sizing:border-box;margin:0}
+html,body{height:100%}body{font-family:Inter,"Segoe UI",system-ui,sans-serif;color:var(--ink);background:#0b0c12;overflow:hidden;user-select:none}
+
+/* Living background: game art drifting under coloured light blobs */
+.glow{position:absolute;inset:0;z-index:0;pointer-events:none}
+.win>*:not(.glow){position:relative;z-index:1}
+.blob{position:absolute;border-radius:50%;filter:blur(110px) saturate(.75);opacity:.32;mix-blend-mode:screen}
+.b1{width:520px;height:520px;background:#c4561a;left:-160px;top:-180px;animation:float1 18s ease-in-out infinite alternate}
+.b2{width:480px;height:480px;background:#3a4fb8;right:-120px;bottom:-200px;animation:float2 22s ease-in-out infinite alternate}
+.b3{width:380px;height:380px;background:#8a3a6a;right:260px;top:-160px;animation:float1 24s ease-in-out infinite alternate-reverse}
+@keyframes drift{to{transform:scale(1.08) translate(-2%,1%)}}
+@keyframes float1{to{transform:translate(120px,140px) scale(1.15)}}
+@keyframes float2{to{transform:translate(-140px,-110px) scale(1.1)}}
+
+/* Liquid glass surface */
+.glass{position:relative;background:linear-gradient(135deg,var(--glass-strong),var(--glass) 60%);
+ backdrop-filter:blur(28px) saturate(180%);-webkit-backdrop-filter:blur(28px) saturate(180%);
+ border-radius:28px;box-shadow:0 30px 80px rgba(0,0,0,.45), inset 0 1px 0 rgba(255,255,255,.35), inset 0 -1px 0 rgba(255,255,255,.06)}
+.glass::before{content:"";position:absolute;inset:0;border-radius:inherit;padding:1px;pointer-events:none;
+ background:linear-gradient(140deg,var(--edge),rgba(255,255,255,.04) 40%,rgba(255,255,255,.18));
+ -webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask-composite:exclude}
+/* moving specular sheen */
+.glass::after{content:"";position:absolute;inset:0;border-radius:inherit;pointer-events:none;
+ background:radial-gradient(600px 220px at var(--mx,30%) -10%,rgba(255,255,255,.22),transparent 60%)}
+
+.win{position:relative;overflow:hidden;border-radius:30px;background:#0b0c12;box-shadow:0 40px 120px rgba(0,0,0,.6),inset 0 0 0 1px rgba(255,255,255,.08);
+ width:100vw;height:100vh;border-radius:0;display:grid;grid-template-columns:250px 1fr;gap:18px;padding:18px;
+ animation:rise .9s cubic-bezier(.2,.8,.2,1) both}
+@keyframes rise{from{opacity:0;transform:translateY(24px) scale(.98)}}
+
+/* Sidebar */
+.side{padding:22px 16px;border-radius:24px;background:linear-gradient(160deg,rgba(255,255,255,.06),rgba(255,255,255,.02));backdrop-filter:blur(24px) saturate(170%);box-shadow:inset 0 1px 0 rgba(255,255,255,.25),inset 0 0 0 1px rgba(255,255,255,.08);display:flex;flex-direction:column;gap:6px}
+.logo{font-weight:800;font-size:28px;letter-spacing:-.5px;padding:4px 10px 18px}
+.logo b{color:var(--accent)}
+.tag{display:inline-block;white-space:nowrap;align-self:flex-start;margin:0 10px 18px;font-size:11px;font-weight:700;letter-spacing:1.6px;padding:6px 10px;border-radius:999px;
+ background:linear-gradient(90deg,var(--accent),var(--accent-2));color:#1a1200}
+.nav{display:flex;align-items:center;gap:12px;padding:12px 14px;border-radius:16px;color:var(--muted);font-weight:600;cursor:pointer;transition:.25s}
+.nav:hover{background:rgba(255,255,255,.07);color:#fff}
+.nav.on{background:rgba(255,255,255,.14);color:#fff;box-shadow:inset 0 1px 0 rgba(255,255,255,.25)}
+.nav svg{width:20px;height:20px;opacity:.9}
+.spacer{flex:1}
+.credits{padding:4px 12px 10px;font-size:12px;line-height:1.7;color:var(--muted)}
+.credits h4{font-size:10px;letter-spacing:1.6px;font-weight:700;margin-bottom:2px}
+.credits b{color:var(--ink);font-weight:700}
+body.deck .old-only,body:not(.deck) .deck-only{display:none!important}
+.side .tg.side-tg{margin:0 0 10px;padding:10px 12px;font-size:13px;font-weight:600}
+.me{display:flex;align-items:center;gap:12px;padding:12px;border-radius:18px;background:rgba(0,0,0,.18)}
+.av{width:38px;height:38px;border-radius:50%;background:linear-gradient(135deg,var(--accent),#ff3d6e);display:grid;place-items:center;font-weight:800;color:#1a1200}
+.me small{display:block;color:var(--muted);font-size:12px}
+.dot{width:8px;height:8px;border-radius:50%;background:#4ade80;display:inline-block;margin-right:6px;box-shadow:0 0 10px #4ade80}
+
+/* Main */
+.main{display:grid;grid-template-rows:1fr auto;gap:18px;min-height:0}
+.hero{overflow:hidden;padding:38px;display:flex;flex-direction:column;justify-content:flex-end}
+.hero .shot{position:absolute;inset:0;border-radius:inherit;background:url(bg.jpg) 85% 70%/150% auto;opacity:.38;filter:saturate(.7);mask-image:linear-gradient(180deg,transparent,#000 60%)}
+.hero h1{position:relative;font-size:clamp(34px,5vw,64px);font-weight:800;line-height:1;letter-spacing:-1.5px}
+.hero h1 span{background:linear-gradient(90deg,var(--accent),var(--accent-2));-webkit-background-clip:text;color:transparent}
+.hero p{position:relative;color:var(--muted);max-width:520px;margin:14px 0 26px;font-size:15px}
+.row{position:relative;display:flex;gap:14px;align-items:center;flex-wrap:wrap}
+.play{position:relative;border:0;cursor:pointer;font:800 18px Inter;letter-spacing:2px;color:#1a1200;padding:18px 54px;border-radius:999px;
+ background:linear-gradient(90deg,var(--accent),var(--accent-2));box-shadow:0 12px 40px rgba(255,140,40,.45),inset 0 1px 0 rgba(255,255,255,.6);
+ overflow:hidden;transition:transform .2s}
+.play:hover{transform:translateY(-2px) scale(1.02)}
+.play::after{content:"";position:absolute;top:0;left:-60%;width:40%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.7),transparent);
+ transform:skewX(-20deg);animation:shine 3.2s ease-in-out infinite}
+@keyframes shine{0%,60%{left:-60%}100%{left:130%}}
+.chip{padding:12px 18px;border-radius:999px;font-weight:600;font-size:14px}
+
+.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:18px}
+.card{padding:20px 22px;transition:transform .3s}
+.card:hover{transform:translateY(-4px)}
+.card h3{font-size:12px;letter-spacing:1.6px;color:var(--muted);font-weight:700;margin-bottom:10px}
+.big{font-size:34px;font-weight:800}
+.card small{color:var(--muted)}
+.bar{height:6px;border-radius:9px;background:rgba(255,255,255,.12);margin-top:12px;overflow:hidden}
+.bar i{display:block;height:100%;width:72%;border-radius:9px;background:linear-gradient(90deg,var(--accent),var(--accent-2));animation:fill 1.6s .4s cubic-bezier(.2,.8,.2,1) both}
+@keyframes fill{from{width:0}}
+
+/* Update pop-up: over the launcher, the rest dimmed and blurred */
+.veil{position:absolute!important;inset:0;z-index:5!important;display:grid;place-items:center;border-radius:inherit;
+ background:rgba(5,6,12,.45);backdrop-filter:blur(10px);animation:fade .5s 1.2s both;transition:opacity .35s}
+.veil.gone{opacity:0;pointer-events:none}
+.browser [data-win]{display:none}
+#perfAsk,#perfAsk .toast,#updAsk,#updAsk .toast{animation-delay:0s}
+.upbar{height:8px;border-radius:8px;background:rgba(255,255,255,.12);overflow:hidden;margin:4px 0 18px;display:none}.upbar i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--accent),var(--accent-2));transition:width .3s}
+@keyframes fade{from{opacity:0}}
+.toast{width:420px;padding:28px 28px 24px;text-align:center;animation:pop .7s 1.3s cubic-bezier(.2,1.2,.3,1) both}
+@keyframes pop{from{opacity:0;transform:translateY(24px) scale(.92)}}
+.toast .ico{width:56px;height:56px;margin:0 auto 14px;border-radius:18px;display:grid;place-items:center;font-size:26px;
+ background:linear-gradient(135deg,var(--accent),var(--accent-2));color:#1a1200;box-shadow:0 10px 30px rgba(255,140,40,.45)}
+.toast b{display:block;font-size:20px;margin-bottom:8px}.toast p{color:var(--muted);font-size:14px;line-height:1.5;margin-bottom:20px}
+.btns{display:flex;gap:10px}.btns button{flex:1;border:0;border-radius:14px;padding:13px;font:700 13px Inter;cursor:pointer}
+.go{background:linear-gradient(90deg,var(--accent),var(--accent-2));color:#1a1200}.later{background:rgba(255,255,255,.12);color:#fff}
+
+/* Pages */
+.page{display:none;min-height:0}#p-social{position:relative}
+.page.on{display:grid;animation:pagein .45s cubic-bezier(.2,.8,.2,1)}
+@keyframes pagein{from{opacity:0;transform:translateX(18px)}}
+.panel{padding:26px 28px;overflow:auto}
+.panel h2{font-size:26px;font-weight:800;letter-spacing:-.5px}
+.panel .sub{color:var(--muted);margin:6px 0 22px;font-size:14px}
+.sec{font-size:12px;letter-spacing:1.6px;color:var(--accent);font-weight:800;margin:22px 0 12px}
+.grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px 18px}
+.pcards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin-bottom:18px}
+.pcard{padding:16px 18px;border-radius:16px;background:rgba(255,255,255,.06)}.pcard h3{font-size:11px;letter-spacing:1.4px;color:var(--muted);margin-bottom:6px}.pcard .big{font-size:26px}
+.tip{padding:12px 16px;border-radius:14px;margin-bottom:10px;font-size:13.5px;line-height:1.45;background:rgba(255,207,46,.1);border:1px solid rgba(255,207,46,.35)}.tip.bad{background:rgba(255,90,90,.1);border-color:rgba(255,90,90,.4)}
+.ptable{width:100%;border-collapse:collapse;font-size:13px}.ptable th{text-align:left;color:var(--muted);font-weight:700;font-size:11px;letter-spacing:1px;padding:8px 6px;border-bottom:1px solid rgba(255,255,255,.1)}
+.ptable td{padding:9px 6px;border-bottom:1px solid rgba(255,255,255,.06)}.ptable .crash{color:#ff7a7a;font-weight:700}
+#pEmpty{color:var(--muted);font-size:14px;padding:20px 0}
+.post{display:flex;gap:10px;flex-wrap:wrap;margin:6px 0 4px}.post input{flex:1;min-width:220px;background:rgba(255,255,255,.08);color:#fff;border:1px solid rgba(255,255,255,.14);border-radius:12px;padding:11px 14px;font:500 14px Inter}
+.post select{background:rgba(255,255,255,.08);color:#fff;border:1px solid rgba(255,255,255,.14);border-radius:12px;padding:10px;font:600 13px Inter}.post select option{background:#1a1b22}.post .go{border:0;border-radius:12px;padding:0 20px;font:800 14px Inter;cursor:pointer}
+.spics{display:grid;grid-auto-flow:column;grid-auto-columns:168px;gap:10px;overflow-x:auto;overflow-y:hidden;padding:4px 2px 10px;margin:2px 0 10px;scroll-snap-type:x proximity;scrollbar-width:thin}
+.spic{position:relative;aspect-ratio:16/10;border-radius:12px;overflow:hidden;cursor:pointer;border:2px solid transparent;background:rgba(255,255,255,.06);scroll-snap-align:start;outline:none}
+.spic img{width:100%;height:100%;object-fit:cover;display:block}.spic>span{position:absolute;left:0;right:0;bottom:0;padding:16px 8px 6px;font:700 11.5px Inter;text-align:left;background:linear-gradient(transparent,rgba(0,0,0,.85))}
+.spic:hover{border-color:rgba(255,255,255,.35)}.spic.on{border-color:var(--accent)}.spic:focus-visible{outline:2px solid #fff;outline-offset:2px}
+.splay{position:absolute;left:50%;top:40%;transform:translate(-50%,-50%);display:none;align-items:center;gap:6px;border:0;border-radius:999px;padding:8px 14px;font:800 12.5px Inter;cursor:pointer;color:#1a1200;background:linear-gradient(90deg,var(--accent),var(--accent-2));box-shadow:0 4px 14px rgba(0,0,0,.5);white-space:nowrap}
+.spic.on .splay{display:inline-flex}.spic.on img{filter:brightness(.75)}
+.glist{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:12px}.gcard{padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.09);display:flex;flex-direction:column;gap:6px}
+.gcard b{font-size:15px}.gcard small{color:var(--muted);font-size:12.5px}.gcard .row2{display:flex;align-items:center;justify-content:space-between;margin-top:6px}.gcard .full{color:var(--muted);font-size:12px}
+#gMine:not(:empty){padding:12px 16px;border-radius:14px;margin-bottom:12px;background:rgba(255,207,46,.1);border:1px solid rgba(255,207,46,.35);font-size:13.5px;color:var(--accent)}
+.games{padding:10px 12px;margin:0 0 10px;border-radius:16px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08)}
+.games .gh{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:12px;letter-spacing:1.4px;font-weight:800;color:var(--accent)}
+.game{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid rgba(255,255,255,.06);font-size:13.5px}.game:first-of-type{border-top:0}
+.game .gi{flex:1;min-width:0}.game small{display:block;color:var(--muted);font-size:12px}
+.gform{display:none;gap:8px;align-items:center;margin-top:8px;flex-wrap:wrap}.gform.on{display:flex}
+.gform select{background:rgba(255,255,255,.08);color:#fff;border:1px solid rgba(255,255,255,.14);border-radius:10px;padding:8px;font:600 13px Inter}
+.gform select option{background:#1a1b22}.mine{color:var(--accent);font-size:12.5px;margin-top:6px}
+.seek{font-size:12.5px;color:var(--muted);padding:6px 4px 10px;line-height:1.5}.seek b{color:var(--accent)}
+.field label{display:block;font-size:12px;font-weight:700;letter-spacing:.6px;color:var(--muted);margin-bottom:7px}
+.select{position:relative}
+.select select,.field input{width:100%;appearance:none;-webkit-appearance:none;font:600 14px Inter;color:#fff;padding:13px 40px 13px 14px;border-radius:14px;
+ border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.07);backdrop-filter:blur(12px);outline:none;transition:.2s}
+.select select:hover,.field input:hover{background:rgba(255,255,255,.11)}
+.select select:focus,.field input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(255,207,46,.2)}
+.select::after{content:"";position:absolute;right:16px;top:50%;width:8px;height:8px;border-right:2px solid #fff;border-bottom:2px solid #fff;transform:translateY(-70%) rotate(45deg);opacity:.7;pointer-events:none}
+.select option{background:#1a1b22}
+.toggles{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px}
+.tg{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.06);
+ border:1px solid rgba(255,255,255,.08);cursor:pointer;font-weight:600;font-size:14px}
+.tg small{display:block;color:var(--muted);font-weight:500;font-size:12px;margin-top:3px}
+.sw{flex:none;width:46px;height:26px;border-radius:99px;background:rgba(255,255,255,.18);position:relative;transition:.25s}
+.sw::after{content:"";position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:#fff;transition:.25s cubic-bezier(.2,1.2,.3,1);box-shadow:0 2px 6px rgba(0,0,0,.3)}
+.tg.on .sw{background:linear-gradient(90deg,var(--accent),var(--accent-2))}.tg.on .sw::after{left:23px}
+.btn{cursor:pointer;font:700 14px Inter;color:#fff;padding:12px 18px;border-radius:14px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.14)}
+.kpresets{display:grid;grid-template-columns:1fr 1fr;gap:12px}.kpre{text-align:left;cursor:pointer;color:#fff;font:inherit;padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.06);border:2px solid transparent}.kpre:hover{border-color:rgba(255,255,255,.3)}.kpre b{display:block;font-size:15px}.kpre small{display:block;color:var(--muted);font-size:12.5px;margin-top:4px}.kpre:focus-visible{outline:2px solid #fff;outline-offset:2px}
+.ksec{font-size:12px;letter-spacing:1.6px;color:var(--accent);font-weight:800;margin:20px 0 8px}.khelp{color:var(--muted);font-size:13px;margin:16px 0 4px}.khelp b{color:#fff}
+.krow{display:grid;grid-template-columns:1fr 132px 132px;align-items:center;gap:10px;padding:8px 12px;border-radius:12px}.krow:nth-child(even){background:rgba(255,255,255,.04)}
+.krow small{display:block;color:var(--muted);font-size:12px;margin-top:2px}.kkey{font:700 13px Inter;color:#fff;padding:9px 10px;border-radius:10px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.14);cursor:pointer;min-height:38px}
+.kkey:hover{border-color:rgba(255,255,255,.35)}.kkey.empty{color:var(--muted);font-weight:500}.kkey.wait{border-color:var(--accent);color:var(--accent)}.kkey:focus-visible{outline:2px solid #fff;outline-offset:2px}
+.ksens{grid-template-columns:auto 1fr 48px;margin-top:12px;background:rgba(255,255,255,.04)}.ksens input{accent-color:var(--accent)}.knote{color:var(--muted);font-size:13px;margin-left:12px;align-self:center}
+#p-controls.off #kList,#p-controls.off .khelp,#p-controls.off #kSensRow{opacity:.45}
+.btn:hover{background:rgba(255,255,255,.16)}
+.regions{display:grid;grid-template-columns:1fr 1fr;gap:14px}
+.region{padding:18px;border-radius:18px;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);cursor:pointer;transition:.25s}
+.region.on{border-color:var(--accent);background:rgba(255,207,46,.1);box-shadow:0 0 0 3px rgba(255,207,46,.15)}
+.region b{font-size:17px}.region small{display:block;color:var(--muted);margin-top:4px}
+.region .ping{float:right;font-size:12px;font-weight:700;color:#4ade80}
+.pathrow{display:grid;grid-template-columns:1fr auto;gap:10px;align-items:end;margin-bottom:12px}
+
+.dd{position:relative}
+.dd-btn{width:100%;display:flex;justify-content:space-between;align-items:center;font:600 14px Inter;color:#fff;padding:13px 14px;border-radius:14px;cursor:pointer;
+ border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.06);backdrop-filter:blur(12px);transition:.2s;text-align:left}
+.dd-btn:hover{background:rgba(255,255,255,.1)}
+.dd.open .dd-btn{border-color:rgba(255,207,46,.6);box-shadow:0 0 0 3px rgba(255,207,46,.15)}
+.dd-btn i{width:8px;height:8px;border-right:2px solid #fff;border-bottom:2px solid #fff;transform:translateY(-2px) rotate(45deg);opacity:.6;transition:.25s}
+.dd.open .dd-btn i{transform:translateY(2px) rotate(-135deg)}
+.dd-list{position:absolute;left:0;right:0;top:calc(100% + 8px);z-index:20;padding:6px;border-radius:16px;
+ background:rgba(20,21,27,.97);backdrop-filter:blur(30px) saturate(140%);border:1px solid rgba(255,255,255,.12);
+ box-shadow:0 20px 50px rgba(0,0,0,.5),inset 0 1px 0 rgba(255,255,255,.12);
+ opacity:0;transform:translateY(-6px) scale(.98);pointer-events:none;transition:.18s;max-height:240px;overflow:auto}
+.dd.open .dd-list{opacity:1;transform:none;pointer-events:auto}
+.dd-opt{display:flex;justify-content:space-between;align-items:center;padding:11px 12px;border-radius:11px;font:500 14px Inter;color:rgba(255,255,255,.85);cursor:pointer}
+.dd-opt:hover{background:rgba(255,255,255,.08);color:#fff}
+.dd-opt.sel{color:#fff;font-weight:700}
+.dd-opt.sel::after{content:"";width:6px;height:11px;border-right:2px solid var(--accent);border-bottom:2px solid var(--accent);transform:rotate(45deg) translate(-2px,-2px)}
+
+/* Social */
+#p-social{position:relative}
+#p-social.on{grid-template-columns:290px 1fr;gap:18px}
+.people,.chat{display:flex;flex-direction:column;min-height:0;padding:18px}
+.ptabs,.ctabs{display:flex;gap:6px;margin-bottom:12px;flex-wrap:wrap}
+.ptab,.ctab{padding:8px 13px;border-radius:999px;font:700 13px Inter;color:var(--muted);cursor:pointer;background:rgba(255,255,255,.05);border:1px solid transparent;display:flex;align-items:center;gap:7px}
+.ptab.on,.ctab.on{color:#fff;background:rgba(255,255,255,.12);border-color:rgba(255,255,255,.14)}
+.badge{min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--accent);color:#1a1200;font-size:11px;display:grid;place-items:center}
+.search{width:100%;font:500 14px Inter;color:#fff;padding:11px 13px;border-radius:12px;border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.05);outline:none;margin-bottom:10px}
+.plist{flex:1;overflow:auto;display:flex;flex-direction:column;gap:4px}
+.person{display:flex;align-items:center;gap:11px;padding:9px 10px;border-radius:13px;cursor:pointer;transition:.15s}
+.person:hover{background:rgba(255,255,255,.06)}
+.pav{position:relative;width:36px;height:36px;border-radius:50%;display:grid;place-items:center;font-weight:800;color:#fff;flex:none}
+.pav::after{content:"";position:absolute;right:-1px;bottom:-1px;width:11px;height:11px;border-radius:50%;border:2px solid #15161c;background:#6b7280}
+.pav.online::after{background:#4ade80}.pav.game::after{background:var(--accent)}
+.pn{flex:1;min-width:0}.pn b{display:block;font-size:14px}.pn small{color:var(--muted);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block}
+.pact{width:30px;height:30px;border-radius:10px;border:0;background:rgba(255,255,255,.08);color:#fff;cursor:pointer;font-size:16px}
+.pact:hover{background:rgba(255,255,255,.16)}.pact.ok{background:linear-gradient(90deg,var(--accent),var(--accent-2));color:#1a1200}
+.msgs{flex:1;overflow:auto;display:flex;flex-direction:column;gap:12px;padding:6px 4px 10px}
+.msg{display:flex;gap:10px;align-items:flex-start;animation:pagein .3s both}
+.msg .pav{width:32px;height:32px;font-size:13px}.msg .pav::after{display:none}
+.mb{max-width:72%;padding:10px 13px;border-radius:16px 16px 16px 6px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.06);font-size:14px;line-height:1.45}
+.mb .who{font-size:12px;font-weight:700;color:var(--accent);margin-bottom:3px;display:flex;gap:8px;align-items:baseline}
+.mb .who span{color:var(--muted);font-weight:500}
+.msg.me{flex-direction:row-reverse}.msg.me .mb{border-radius:16px 16px 6px 16px;background:linear-gradient(135deg,rgba(255,207,46,.22),rgba(255,122,46,.16));border-color:rgba(255,207,46,.25)}
+.msg.me .who{justify-content:flex-end}
+.sys{align-self:center;font-size:12px;color:var(--muted);padding:5px 12px;border-radius:999px;background:rgba(255,255,255,.05)}
+.compose{display:flex;gap:10px;margin-top:6px}
+.compose input{flex:1;font:500 14px Inter;color:#fff;padding:13px 15px;border-radius:14px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.06);outline:none}
+.compose input:focus{border-color:rgba(255,207,46,.6);box-shadow:0 0 0 3px rgba(255,207,46,.15)}
+.send{border:0;border-radius:14px;padding:0 20px;font:800 14px Inter;color:#1a1200;cursor:pointer;background:linear-gradient(90deg,var(--accent),var(--accent-2))}
+.chathead{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}
+.chathead small{color:var(--muted)}
+.menu{position:absolute;z-index:30;padding:6px;border-radius:14px;background:rgba(20,21,27,.97);border:1px solid rgba(255,255,255,.12);box-shadow:0 20px 50px rgba(0,0,0,.5);display:none}
+.menu.on{display:block}.menu div{padding:9px 14px;border-radius:10px;font:500 14px Inter;cursor:pointer}.menu div:hover{background:rgba(255,255,255,.08)}.menu .bad{color:#f87171}
+
+.status{position:relative;margin-top:14px;font-size:13px;color:var(--muted)}.status.bad{color:#f87171}
+.field input[readonly]{opacity:.85;cursor:default}
+.play[disabled]{filter:grayscale(.6);opacity:.7;cursor:default}
+
+/* Own title bar (the Windows one is hidden): drag anywhere on it, glass buttons on the right */
+.win{padding-top:48px!important}
+/* Resizable window: the layout always fits it; a short window scrolls the sidebar instead of cutting the page */
+.win{grid-template-rows:minmax(0,1fr)}
+.side{min-height:0;overflow-y:auto;scrollbar-width:none}
+.side::-webkit-scrollbar{display:none}
+@media (max-height:860px){.side{padding-top:14px;padding-bottom:14px;gap:2px}.logo{padding-bottom:10px}.tag{margin-bottom:10px}.nav{padding:8px 14px}.credits{padding-bottom:6px}}
+.titlebar{position:absolute!important;top:0;left:0;right:0;height:44px;z-index:40!important;display:flex;align-items:center;justify-content:flex-end;gap:6px;padding:0 12px 0 22px}
+.titlebar .ttl{margin-right:auto;font:600 12px Inter;letter-spacing:1.4px;color:rgba(255,255,255,.45);pointer-events:none}
+.tb{width:34px;height:28px;border:0;border-radius:9px;background:transparent;color:rgba(255,255,255,.75);cursor:pointer;display:grid;place-items:center;transition:.15s}
+.tb:hover{background:rgba(255,255,255,.12);color:#fff}
+.tb.x:hover{background:#e5484d;color:#fff}
+.tb svg{width:14px;height:14px}
+</style></head><body>
+<div class="win" id="win">
+ <div class="titlebar" id="titlebar"><span class="ttl">RESTREET LAUNCHER</span>
+ <button class="tb" data-win="min" title="Minimize"><svg viewBox="0 0 14 14"><path d="M2 7h10" stroke="currentColor" stroke-width="1.6"/></svg></button>
+ <button class="tb x" data-win="close" title="Close"><svg viewBox="0 0 14 14"><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" stroke-width="1.6"/></svg></button>
+ </div>
+ <div class="glow"><div class="blob b1"></div><div class="blob b2"></div><div class="blob b3"></div></div>
+ <aside class="side">
+ <div class="logo">Re<b>Street</b></div>
+ <span class="tag" id="ver">V1.5 &middot; ONLINE BETA</span>
+ <div class="nav on" data-p="p-home"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 11l9-8 9 8v10a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1z"/></svg>Home</div><div class="nav" data-p="p-social"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a3 3 0 0 1-3 3H8l-5 4V6a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3z"/></svg>Social<span class="badge" id="navBadge" style="margin-left:auto;display:none"></span></div><div class="nav" data-p="p-matches"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 7l4 3-1.5 5h-5L8 10z"/></svg>Matches<span class="badge" id="matchBadge" style="margin-left:auto;display:none"></span></div><div class="nav" data-p="p-online"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>Online</div><div class="nav" data-p="p-display"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/></svg>Display</div><div class="nav" data-p="p-graphics"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/><circle cx="12" cy="12" r="3"/></svg>Graphics</div><div class="nav" data-p="p-perf"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 20h18M6 16l4-5 3 3 5-7"/></svg>Performance</div><div class="nav" data-p="p-controls"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="6" width="20" height="12" rx="3"/><path d="M6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10"/></svg>Controls</div><div class="nav" data-p="p-advanced"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 6h16M4 12h16M4 18h10"/></svg>Advanced</div>
+ <div class="spacer"></div>
+ <div class="tg side-tg" data-id="onlineMode" title="Off: the game starts offline, with no server, friends or rooms."><div>Play online</div><div class="sw"></div></div>
+ <div class="credits"><h4>CREDITS</h4><div>Performance &middot; <b>AnDr3zF</b></div><div>PT-BR translation &middot; <b>Eze_.</b></div></div>
+ <div class="me"><div class="av" id="meav">?</div><div><b id="mename">Offline</b><small><span class="dot" id="medot"></span><span id="meserver">Not set up</span></small></div></div>
+ </aside>
+
+ <section class="main page on" id="p-home">
+ <div class="hero glass">
+ <div class="shot"></div>
+ <h1>FIFA Street<br><span>is back online.</span></h1>
+ <p>Division Match, weekly Cups and Friend Matches with real players. Pick up where you left off.</p>
+ <div class="row"><button class="play" data-cmd="play" id="play">PLAY</button><div class="chip glass" id="summary"></div></div>
+ <div class="status" id="status"></div>
+ </div>
+ <div class="cards">
+ <div class="card glass"><h3>ONLINE NOW</h3><div class="big" id="cOnline">&ndash;</div><small id="cOnlineSub">on your server</small></div>
+ <div class="card glass"><h3>SERVER</h3><div class="big" id="cServer">&ndash;</div><small id="cPing">&nbsp;</small></div>
+ <div class="card glass"><h3>GRAPHICS</h3><div class="big" id="cApi">&ndash;</div><small id="cProfile">&nbsp;</small></div>
+ <div class="card glass" id="cPerf" style="display:none"><h3>LAST SESSION</h3><div class="big" id="cFps">&ndash;</div><small id="cFpsSub">&nbsp;</small></div>
+ </div>
+ </section>
+
+
+ <section class="page" id="p-social">
+ <div class="people glass">
+ <div class="ptabs"><div class="ptab on" data-t="t-online">Online <span class="badge" id="bOnline">0</span></div><div class="ptab" data-t="t-friends">Friends</div><div class="ptab" data-t="t-req">Requests <span class="badge" id="bReq" style="display:none"></span></div></div>
+ <form id="addForm" style="display:flex;gap:8px"><input class="search" id="addName" maxlength="15" placeholder="Add a friend by name" autocomplete="off"><button class="pact ok" style="height:42px;width:42px">+</button></form>
+ <div class="plist" id="t-online"></div>
+ <div class="plist" id="t-friends" style="display:none"></div>
+ <div class="plist" id="t-req" style="display:none"></div>
+ </div>
+ <div class="chat glass">
+ <div class="chathead"><div class="ctabs" id="ctabs"></div><small id="chatNote">be nice, chat is moderated</small></div>
+ <div class="msgs" id="msgs"></div>
+ <form class="compose" id="compose"><input id="say" maxlength="300" placeholder="Message" autocomplete="off"><button class="send">Send</button></form>
+ </div>
+ <div class="menu" id="pmenu"><div data-a="dm">Send message</div><div data-a="add">Add friend</div><div data-a="remove" class="bad">Remove friend</div><div data-a="block" class="bad">Block</div></div>
+ </section>
+ <section class="page" id="p-matches"><div class="panel glass">
+ <h2>Matches</h2><p class="sub">Post a match or join one. Keep the game closed: when someone joins, ReStreet opens for both of you straight into the match lobby.</p>
+ <div id="games">
+ <div class="mine" id="gMine"></div>
+ <div class="post" id="gPost"><input id="gTitle" maxlength="32" placeholder="Title (optional), e.g. Chill 5-a-side, no skills spam" autocomplete="off">
+ <select id="gMode"><option value="fives">5-a-side</option><option value="sixes">6-a-side</option><option value="futsal">Futsal</option></select>
+ <input type="hidden" id="gStadium"></div>
+ <div class="spics" id="gPics" role="radiogroup" aria-label="Stadium"></div>
+ <div class="sec">OPEN MATCHES</div>
+ <div class="glist" id="gList"></div>
+ <div class="sec">LOOKING FOR A MATCH IN THE GAME</div>
+ <div class="seek" id="seek"></div>
+ </div>
+ </div></section>
+ <section class="page" id="p-online"><div class="panel glass">
+ <h2>Online</h2><p class="sub">Your online name and the server you play on. Each server has its own players, seasons and friends.</p>
+ <div class="sec">SERVER</div>
+ <div class="regions" id="regions"></div>
+ <div class="sec">ACCOUNT</div>
+ <div class="grid2">
+ <div class="field"><label>ONLINE NAME</label><input id="oname" readonly></div>
+ <div class="field"><label>STATUS</label><input id="ostatus" readonly></div>
+ </div>
+ <p class="hint" style="color:var(--muted);font-size:13px;margin-top:10px">To change your online name, run the online patch again.</p>
+
+ </div></section>
+
+ <section class="page" id="p-display"><div class="panel glass">
+ <h2>Display</h2><p class="sub">Screen, refresh rate and language.</p>
+ <div class="grid2"><div class="field"><label>RESOLUTION</label><div class="dd" data-id="resolution"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field old-only"><label>REFRESH RATE</label><div class="dd" data-id="refresh"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>DISPLAY MODE</label><div class="dd" data-id="displayMode"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>MONITOR</label><div class="dd" data-id="monitor"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>GAME LANGUAGE</label><div class="dd" data-id="language"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>LAUNCHER LANGUAGE</label><div class="dd" data-id="uiLang"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field deck-only"><label>FRAME RATE LIMIT</label><div class="dd" data-id="fpsLimit"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div></div>
+ <div class="sec">SYNC</div>
+ <div class="toggles"><div class="tg" data-id="vsync"><div>VSync<small>No tearing, a new frame every refresh</small></div><div class="sw"></div></div><div class="tg old-only" data-id="vrr"><div>VRR / Tearing<small>Direct3D 12 &middot; Adaptive Sync</small></div><div class="sw"></div></div></div>
+ </div></section>
+
+ <section class="page" id="p-graphics"><div class="panel glass">
+ <h2>Graphics</h2><p class="sub">Quality and performance. Weaker PC? Pick the Performance profile.</p>
+ <div class="grid2"><div class="field old-only"><label>PROFILE</label><div class="dd" data-id="profile"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>GRAPHICS API</label><div class="dd" data-id="api"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>GPU</label><div class="dd" data-id="gpu"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>POST-PROCESSING</label><div class="dd" data-id="post"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field"><label>INTERNAL RESOLUTION</label><div class="dd" data-id="internal"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field deck-only"><label>SCALING</label><div class="dd" data-id="scaling"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field deck-only"><label>ASPECT RATIO</label><div class="dd" data-id="aspect"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field deck-only"><label>ANISOTROPIC FILTERING</label><div class="dd" data-id="aniso"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div><div class="field deck-only"><label>AMBIENT OCCLUSION</label><div class="dd" data-id="occlusion"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div></div>
+ <div class="sec">ANTI-ALIASING</div>
+ <div class="toggles"><div class="tg" data-id="msaa"><div><span class="old-only">Native 2x MSAA</span><span class="deck-only">Game MSAA (4x in 3D)</span><small>Smoother edges, costs performance</small></div><div class="sw"></div></div></div>
+ </div></section>
+
+ <section class="page" id="p-perf"><div class="panel glass">
+ <h2>Performance</h2><p class="sub">How ReStreet ran on this PC in your last sessions. Matches, replays and menus are measured separately.</p>
+ <div class="pcards"><div class="pcard"><h3>LAST MATCH FPS</h3><div class="big" id="pLast">&ndash;</div></div><div class="pcard"><h3>AVERAGE (10 SESSIONS)</h3><div class="big" id="pAvg">&ndash;</div></div><div class="pcard"><h3>GRAPHICS CARD USED</h3><div class="big" id="pGpu" style="font-size:17px">&ndash;</div></div><div class="pcard"><h3>CRASHES</h3><div class="big" id="pCrash">&ndash;</div></div></div>
+ <div id="pTips"></div>
+ <div class="sec">SESSIONS</div>
+ <div id="pEmpty">Play a session and your results appear here.</div>
+ <table class="ptable" id="pTable"><thead><tr><th>WHEN</th><th>API</th><th>RESOLUTION</th><th>MATCH</th><th>1% LOW</th><th>REPLAYS</th><th>MENUS</th><th></th></tr></thead><tbody></tbody></table>
+ <div class="sec">THIS PC</div><div id="pPc" class="sub"></div>
+ </div></section>
+ <section class="page" id="p-controls"><div class="panel glass">
+ <h2>Controls</h2><p class="sub">Play without a controller. The keyboard works as an Xbox controller, so menus, matches and online all work; a controller still works too.</p>
+ <div class="toggles"><div class="tg" data-id="kbMode" data-ctl="keyboard"><div>Play with keyboard<small>Turn on to use the keys below</small></div><div class="sw"></div></div><div class="tg old-only" data-id="kbMouse" data-ctl="mouseTricks"><div>Mouse for skill moves<small>The mouse moves the right stick</small></div><div class="sw"></div></div></div>
+ <div class="sec">LAYOUT</div>
+ <div class="kpresets"><button type="button" class="kpre" data-preset="mouse"><b>Keyboard + mouse</b><small>Recommended. WASD to move, the mouse does skill moves; left click pass, right click shoot, middle click lob.</small></button><button type="button" class="kpre" data-preset="keyboard"><b>Keyboard only</b><small>WASD to move, J pass, K shoot, L lob, I manual pass, arrows for skill moves.</small></button></div>
+ <p class="khelp">Both: Shift sprint, Space Street Ball Control (hold), Q flair (hold), E juggle. Menus: Enter select, Backspace back, Esc pause.</p>
+ <div class="krow ksens" id="kSensRow"><span>Mouse sensitivity</span><input type="range" id="kSens" min="0.2" max="3" step="0.1" aria-label="Mouse sensitivity"><b id="kSensVal"></b></div>
+ <p class="khelp">Click a key to change it, then press the new key (or a mouse button). Each action can have two keys. <b>Esc</b> cancels, <b>right-click</b> clears a key.</p>
+ <div id="kList"></div>
+ <span class="knote" id="kNote" role="status"></span>
+ </div></section>
+ <section class="page" id="p-advanced"><div class="panel glass">
+ <h2>Advanced</h2><p class="sub">Game files and renderer options for textures, lighting, black screens and stutter.</p>
+ <div class="sec">GAME FILES</div>
+ <div class="pathrow"><div class="field"><label>GAME EXECUTABLE</label><input id="exe" readonly></div><button class="btn" data-cmd="browseExe">Browse</button></div>
+ <div class="pathrow"><div class="field"><label>GAME DATA FOLDER</label><input id="data" readonly></div><button class="btn" data-cmd="browseData">Browse</button></div>
+ <div class="sec old-only">COMPATIBILITY</div>
+ <div class="grid2 old-only" style="margin-bottom:14px"><div class="field"><label>READBACK RESOLVE</label><div class="dd" data-id="readback"><button class="dd-btn" type="button"><span></span><i></i></button><div class="dd-list"></div></div></div></div>
+ <div class="toggles old-only"><div class="tg" data-id="memexport"><div>Memory Export</div><div class="sw"></div></div><div class="tg" data-id="memexportFast"><div>Fast MemExport</div><div class="sw"></div></div><div class="tg" data-id="pageState"><div>Memory Page State</div><div class="sw"></div></div><div class="tg" data-id="occlusion"><div>Occlusion Queries</div><div class="sw"></div></div><div class="tg" data-id="asyncShaders"><div>Async Shaders</div><div class="sw"></div></div><div class="tg" data-id="frameStats"><div>Frame stats log</div><div class="sw"></div></div><div class="tg" data-id="perfShare"><div>Share performance reports</div><div class="sw"></div></div></div>
+ <div class="row" style="margin-top:20px"><button class="btn" data-cmd="logs">Open logs</button><button class="btn" data-cmd="folder">Open game folder</button><button class="btn" data-cmd="shortcut">Desktop shortcut</button></div>
+ </div></section>
+</div>
+<div class="veil gone" id="perfAsk"><div class="toast glass"><div class="ico">&#9889;</div><b>Help make ReStreet faster</b>
+ <p>After each session, send an anonymous performance report: your graphics card, processor, memory, settings and FPS. No name, no account. You can turn it off in Advanced.</p>
+ <div class="btns"><button class="later" id="perfNo">No thanks</button><button class="go" id="perfYes">Share</button></div></div></div>
+<div class="veil gone" id="updAsk"><div class="toast glass"><div class="ico">&#11015;</div><b id="updTitle">Update available</b>
+ <p id="updText">A new version of ReStreet is ready. The launcher downloads it from GitHub, checks it and installs it for you. Your name, server and saves are kept.</p>
+ <div class="upbar" id="updBar"><i></i></div>
+ <div class="btns" id="updBtns"><button class="later" id="updLater">Later</button><button class="go" id="updGo">Update now</button></div></div></div>
+<div class="veil gone" id="roomReady"><div class="toast glass"><div class="ico">&#9917;</div><b id="rrTitle">Game ready!</b>
+ <p id="rrText">Both players are in. Press PLAY: the game opens and takes you to the match by itself. Don't touch anything until the match set-up appears.</p>
+ <div class="btns"><button class="later" id="rrLeave">Leave game</button><button class="go" id="rrPlay">PLAY</button></div></div></div>
+<script>
+// In WebView2 the launcher is chrome.webview; in a browser (Wine/Proton, no WebView2) the same page talks to the
+// launcher over 127.0.0.1: POST msg, long-poll events (see BrowserUi.cs).
+function browserHost() {
+ const base = location.pathname.replace(/[^/]*$/, ''), listeners = [];
+ (async function poll() {
+ for (;;) {
+ try { const r = await fetch(base + 'events', {cache: 'no-store'}); for (const d of await r.json()) listeners.forEach(cb => cb({data: d})); }
+ catch (e) { await new Promise(r => setTimeout(r, 2000)); }
+ }
+ })();
+ document.documentElement.classList.add('browser');
+ return {postMessage: m => fetch(base + 'msg', {method: 'POST', body: JSON.stringify(m)}).catch(() => {}), addEventListener: (t, cb) => listeners.push(cb)};
+}
+const host = (window.chrome && chrome.webview) || (location.protocol === 'http:' ? browserHost() : null);
+const send = m => host && host.postMessage(m);
+const $ = id => document.getElementById(id);
+const esc = t => String(t ?? '').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
+
+document.querySelectorAll('.nav').forEach(n => n.onclick = () => {
+ document.querySelectorAll('.nav').forEach(x => x.classList.toggle('on', x === n));
+ document.querySelectorAll('.page').forEach(p => p.classList.toggle('on', p.id === n.dataset.p));
+});
+$('titlebar').addEventListener('mousedown', e => { if (e.button === 0 && !e.target.closest('.tb')) send({cmd: e.detail === 2 ? 'maximize' : 'drag'}); });
+document.querySelectorAll('[data-win]').forEach(b => b.onclick = () => send({cmd: b.dataset.win === 'min' ? 'minimize' : 'close'}));
+document.querySelectorAll('[data-cmd]').forEach(b => b.onclick = () => send({cmd: b.dataset.cmd}));
+document.querySelectorAll('.tg').forEach(t => t.onclick = () => { if (t.classList.contains('dis')) return; t.classList.toggle('on');
+ const on = t.classList.contains('on'); send(t.dataset.id === 'perfShare' ? {cmd: 'perfShare', value: on} : t.dataset.ctl ? {cmd: 'controls', value: {[t.dataset.ctl]: on}} : {cmd: 'toggle', id: t.dataset.id, value: on}); });
+const perfAnswer = v => { $('perfAsk').classList.add('gone'); send({cmd: 'perfShare', value: v}); };
+$('perfYes').onclick = () => perfAnswer(true); $('perfNo').onclick = () => perfAnswer(false);
+$('updLater').onclick = () => $('updAsk').classList.add('gone');
+$('updGo').onclick = () => { $('updBtns').style.display = 'none'; $('updBar').style.display = 'block'; $('updText').textContent = 'Downloading the update...'; send({cmd: 'updateGo'}); };
+function renderUpdate(d) {
+ if (d.type === 'update') { $('updTitle').textContent = 'ReStreet ' + d.version + ' is available'; $('updAsk').classList.remove('gone'); }
+ else if (d.type === 'updateProgress') { $('updBar').firstElementChild.style.width = d.percent + '%'; $('updText').textContent = 'Downloading the update... ' + d.percent + '%'; if (d.percent >= 100) $('updText').textContent = 'Checking and installing. The launcher will reopen by itself.'; }
+ else if (d.type === 'updateError') { $('updText').textContent = d.message; $('updBar').style.display = 'none'; $('updBtns').style.display = ''; }
+}
+function renderHistory(d) {
+ const h = d.history || [], f = x => x == null ? '-' : Math.round(x);
+ const sc = (r, k, v = 'fps_avg') => r.scenes && r.scenes[k] ? r.scenes[k][v] : null;
+ const matchOf = r => sc(r, 'gameplay') ?? sc(r, 'menus') ?? sc(r, 'other');
+ $('pEmpty').style.display = h.length ? 'none' : ''; $('pTable').style.display = h.length ? '' : 'none';
+ $('pTable').querySelector('tbody').innerHTML = h.map(r => { const s = r.settings || {}, t = r.time ? new Date(r.time * 1000) : null;
+ return '<tr><td>' + (t ? t.toLocaleDateString() + ' ' + t.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}) : '-') + '</td><td>' + esc(s.api) + '</td><td>' + esc(s.resolution) + ' x' + esc(s.internal_scale) +
+ '</td><td>' + f(sc(r, 'gameplay')) + '</td><td>' + f(sc(r, 'gameplay', 'fps_1_low')) + '</td><td>' + f(sc(r, 'replays')) + '</td><td>' + f(sc(r, 'menus')) +
+ '</td><td>' + (r.exit_code ? '<span class="crash">crash</span>' : '') + '</td></tr>'; }).join('');
+ const last = h[0], recent = h.slice(0, 10).map(matchOf).filter(x => x != null);
+ $('pLast').textContent = last ? f(matchOf(last)) : '-';
+ $('pAvg').textContent = recent.length ? f(recent.reduce((a, b) => a + b, 0) / recent.length) : '-';
+ $('pGpu').textContent = last && last.gpu_used ? last.gpu_used : '-';
+ $('pCrash').textContent = h.filter(r => r.exit_code).length + ' / ' + h.length;
+ const tips = [];
+ if (last && last.integrated_gpu) tips.push(['bad', 'The game ran on your <b>integrated graphics</b> while this PC has a faster card. In Graphics, pick the dedicated card, or in Windows Settings > Display > Graphics set FifaStreet to High performance.']);
+ const refresh = last && last.settings ? Number(last.settings.refresh) || 60 : 60, m = last ? sc(last, 'gameplay') ?? matchOf(last) : null;
+ if (m != null && m < refresh * 0.9) tips.push(['', 'Matches ran at ' + f(m) + ' FPS, below your ' + refresh + ' Hz. Try the <b>Performance</b> profile, a lower internal resolution, or the other graphics API.']);
+ if (last && sc(last, 'gameplay', 'stutters_50ms') > 20) tips.push(['', 'Many stutters in matches. Keep <b>Async Shaders</b> on; the first matches on a new PC stutter while shaders are built.']);
+ if (h.slice(0, 5).filter(r => r.exit_code).length >= 2) tips.push(['bad', 'The game closed with an error in several recent sessions. Update your graphics driver, or open the logs in Advanced and send them to us on Discord.']);
+ $('pTips').innerHTML = tips.map(([c, t]) => '<div class="tip ' + c + '">' + t + '</div>').join('');
+ $('pPc').textContent = (d.adapters || []).map(a => a.name + ' (' + a.vram_mb + ' MB)').join(' · ') +
+ (last && last.pc ? ' · ' + (last.pc.cpu || '') + ' · ' + last.pc.threads + ' threads · ' + last.pc.ram_gb + ' GB RAM' : '');
+}
+function renderPerf(d) {
+ const sc = d.report.scenes || {}, main = sc.gameplay || sc.menus || sc.other || sc.replays; if (!main) return;
+ $('cPerf').style.display = ''; $('cFps').textContent = Math.round(main.fps_avg) + ' FPS';
+ $('cFpsSub').textContent = (sc.gameplay ? 'in matches' : 'average') + ' · 1% low ' + Math.round(main.fps_1_low) +
+ (sc.replays ? ' · replays ' + Math.round(sc.replays.fps_avg) : '');
+ if (d.ask) $('perfAsk').classList.remove('gone');
+}
+document.querySelectorAll('.dd').forEach(d => {
+ d.querySelector('.dd-btn').onclick = e => { e.stopPropagation(); const was = d.classList.contains('open');
+ document.querySelectorAll('.dd.open').forEach(x => x.classList.remove('open')); d.classList.toggle('open', !was); };
+});
+addEventListener('click', () => document.querySelectorAll('.dd.open').forEach(x => x.classList.remove('open')));
+
+function fillDD(id, f) {
+ const d = document.querySelector('.dd[data-id="' + id + '"]'); if (!d || !f) return;
+ d.querySelector('.dd-btn span').textContent = f.items[f.index] ?? '';
+ d.style.opacity = f.enabled === false ? .5 : 1; d.style.pointerEvents = f.enabled === false ? 'none' : '';
+ const list = d.querySelector('.dd-list'); list.innerHTML = '';
+ f.items.forEach((t, i) => { const o = document.createElement('div'); o.className = 'dd-opt' + (i === f.index ? ' sel' : ''); o.textContent = t;
+ o.onclick = e => { e.stopPropagation(); d.classList.remove('open'); send({cmd: 'set', id, index: i}); }; list.appendChild(o); });
+}
+
+// ---------- Controls: keyboard as an Xbox controller (runtime keybind_* names, comma separated alternatives) ----------
+const KACTIONS = [
+ ['MOVEMENT (LEFT STICK)', [['lstick_up', 'Move up'], ['lstick_down', 'Move down'], ['lstick_left', 'Move left'], ['lstick_right', 'Move right'], ['lstick_press', 'L3', 'Left stick click']]],
+ ['SKILL MOVES (RIGHT STICK)', [['rstick_up', 'Skill up'], ['rstick_down', 'Skill down'], ['rstick_left', 'Skill left'], ['rstick_right', 'Skill right'], ['rstick_press', 'R3', 'Stand on the ball / neck stall']]],
+ ['BUTTONS', [['a', 'A', 'Pass (tap twice for a one-two)'], ['b', 'B', 'Shoot'], ['x', 'X', 'Lob pass'], ['y', 'Y', 'Manual pass'], ['left_trigger', 'LT', 'Hold: Street Ball Control / jockey'], ['right_trigger', 'RT', 'Sprint / Panna'], ['left_shoulder', 'LB', 'Hold: flair pass or shot'], ['right_shoulder', 'RB', 'Juggle (hold: knees)']]],
+ ['MENUS', [['start', 'Start', 'Pause'], ['back', 'Back'], ['dpad_up', 'D-pad up'], ['dpad_down', 'D-pad down'], ['dpad_left', 'D-pad left'], ['dpad_right', 'D-pad right']]],
+];
+const KLABEL = Object.fromEntries(KACTIONS.flatMap(([, rows]) => rows.map(([id, name]) => [id, name])));
+// The runtime's own overlays use these keys (settings F4, lobby F6, achievements F7, statistics Home, console `).
+const KRESERVED = ['F4', 'F6', 'F7', 'Home', 'Backtick'];
+const KMODS = {ShiftLeft: 'Shift', ShiftRight: 'Shift', ControlLeft: 'Control', ControlRight: 'Control', AltLeft: 'Alt', AltRight: 'Alt'};
+const KCODES = {Space: 'Space', Enter: 'Return', NumpadEnter: 'NumpadEnter', Tab: 'Tab', Backspace: 'Backspace', Delete: 'Delete', Insert: 'Insert', Home: 'Home', End: 'End',
+ PageUp: 'PageUp', PageDown: 'PageDown', ArrowLeft: 'Left', ArrowRight: 'Right', ArrowUp: 'Up', ArrowDown: 'Down', Backquote: 'Backtick', Minus: 'Minus', Equal: 'Plus',
+ Comma: 'Comma', Period: 'Period', Semicolon: 'Semicolon', Slash: 'Slash', Backslash: 'Backslash', BracketLeft: 'LBracket', BracketRight: 'RBracket', Quote: 'Quote',
+ NumpadAdd: 'NumpadPlus', NumpadSubtract: 'NumpadMinus', NumpadMultiply: 'NumpadStar', NumpadDivide: 'NumpadSlash', CapsLock: 'CapsLock', Pause: 'Pause', ScrollLock: 'ScrollLock'};
+const keyName = e => /^Key[A-Z]$/.test(e.code) ? e.code.slice(3) : /^Digit\d$/.test(e.code) ? e.code.slice(5) : /^Numpad\d$/.test(e.code) ? e.code : /^F\d{1,2}$/.test(e.code) ? e.code : KCODES[e.code] || '';
+const KTEXT = {Return: 'Enter', Backtick: '`', Semicolon: ';', Quote: "'", LMB: 'Left mouse', RMB: 'Right mouse', MMB: 'Middle mouse', LBracket: '[', RBracket: ']', Control: 'Ctrl',
+ Comma: ',', Period: '.', Slash: '/', Backslash: '\\', Minus: '-', Plus: '='};
+const keyText = k => k.split('+').map(p => KTEXT[p] || p).join(' + ');
+let kState = null, kWait = null; // kWait = {id, slot, el}
+const kSlots = id => (kState.keys[id] || '').split(',').map(x => x.trim()).filter(Boolean);
+function kSave(note) { send({cmd: 'controls', value: {keys: kState.keys}}); $('kNote').textContent = note || 'Saved.'; }
+function kBuild() {
+ $('kList').innerHTML = KACTIONS.map(([title, rows]) => '<div class="ksec">' + title + '</div>' + rows.map(([id, name, hint]) =>
+ '<div class="krow"><div>' + esc(name) + (hint ? '<small>' + esc(hint) + '</small>' : '') + '</div>' +
+ [0, 1].map(slot => '<button type="button" class="kkey" data-id="' + id + '" data-slot="' + slot + '"></button>').join('') + '</div>').join('')).join('');
+}
+function kPaint() {
+ document.querySelectorAll('.kkey').forEach(b => {
+ const k = kSlots(b.dataset.id)[b.dataset.slot], waiting = kWait && kWait.el === b;
+ b.textContent = waiting ? 'Press a key...' : k ? keyText(k) : 'none';
+ b.classList.toggle('empty', !k && !waiting); b.classList.toggle('wait', !!waiting);
+ b.setAttribute('aria-label', KLABEL[b.dataset.id] + ' key ' + (+b.dataset.slot + 1) + ': ' + (k ? keyText(k) : 'none'));
+ });
+}
+function renderControls(c) {
+ if (kWait) return; // the player is choosing a key: keep the page as it is
+ const first = !kState;
+ kState = JSON.parse(JSON.stringify(c));
+ if (first) kBuild();
+ $('p-controls').classList.toggle('off', !kState.keyboard);
+ $('kSens').value = kState.sensitivity; $('kSensVal').textContent = (+kState.sensitivity).toFixed(1);
+ $('kSensRow').style.display = kState.mouseTricks ? '' : 'none';
+ document.querySelector('.tg[data-id="kbMode"]').classList.toggle('on', !!kState.keyboard);
+ document.querySelector('.tg[data-id="kbMouse"]').classList.toggle('on', !!kState.mouseTricks);
+ kPaint();
+}
+function kSet(id, slot, key) {
+ let note = 'Saved.';
+ if (key) for (const other of Object.keys(kState.keys)) { // a key does one thing: take it off any other action
+ const list = kSlots(other), at = list.indexOf(key);
+ if (at >= 0 && !(other === id && at === slot)) { list.splice(at, 1); kState.keys[other] = list.join(','); if (other !== id) note = keyText(key) + ' moved here from ' + KLABEL[other] + '.'; }
+ }
+ const list = kSlots(id);
+ if (key) list[Math.min(slot, list.length)] = key; else list.splice(slot, 1);
+ kState.keys[id] = list.filter(Boolean).join(',');
+ kWait = null; kPaint(); kSave(note);
+}
+function kCapture(name, e) {
+ e.preventDefault(); e.stopPropagation();
+ if (!name) { $('kNote').textContent = 'That key cannot be used.'; return; }
+ if (KRESERVED.includes(name)) { $('kNote').textContent = keyText(name) + ' opens a ReStreet menu in the game. Pick another key.'; return; }
+ kSet(kWait.id, +kWait.slot, name);
+}
+$('kList').addEventListener('click', e => {
+ const b = e.target.closest('.kkey'); if (!b || kWait) return;
+ kWait = {id: b.dataset.id, slot: b.dataset.slot, el: b}; $('kNote').textContent = ''; kPaint();
+});
+$('kList').addEventListener('contextmenu', e => {
+ const b = e.target.closest('.kkey'); if (!b) return; e.preventDefault(); kWait = null;
+ if (kSlots(b.dataset.id)[b.dataset.slot]) kSet(b.dataset.id, +b.dataset.slot, ''); else kPaint();
+});
+document.addEventListener('keydown', e => {
+ if (!kWait) return;
+ if (e.code === 'Escape') { e.preventDefault(); kWait = null; kPaint(); $('kNote').textContent = 'Cancelled.'; return; }
+ if (KMODS[e.code]) return kCapture(KMODS[e.code], e);
+ const base = keyName(e);
+ kCapture(base, e); // Shift / Ctrl / Alt are keys of their own (the runtime lets them be held while moving)
+}, true);
+// Mouse buttons can be keys too; the click that started the wait does not count.
+document.addEventListener('mousedown', e => { if (!kWait || (e.target === kWait.el && e.button === 0)) return; kCapture(['LMB', 'MMB', 'RMB'][e.button] || '', e); }, true);
+$('kSens').oninput = () => { kState.sensitivity = +$('kSens').value; $('kSensVal').textContent = kState.sensitivity.toFixed(1); };
+$('kSens').onchange = () => send({cmd: 'controls', value: {sensitivity: kState.sensitivity}});
+document.querySelectorAll('.kpre').forEach(b => b.onclick = () => {
+ kWait = null; send({cmd: 'controls', value: {preset: b.dataset.preset, keyboard: true}});
+ $('kNote').textContent = b.querySelector('b').textContent + ' keys set.';
+});
+function render(s) {
+ if (s.controls) renderControls(s.controls);
+ for (const [id, f] of Object.entries(s.fields || {})) fillDD(id, f);
+ for (const [id, t] of Object.entries(s.toggles || {})) { const el = document.querySelector('.tg[data-id="' + id + '"]'); if (!el) continue;
+ el.classList.toggle('on', !!t.on); el.classList.toggle('dis', t.enabled === false); el.style.opacity = t.enabled === false ? .5 : 1; }
+ $('exe').value = s.exe || ''; $('data').value = s.data || '';
+ $('summary').textContent = s.summary || ''; $('status').textContent = s.status || ''; $('status').classList.toggle('bad', s.statusOk === false);
+ gameIsRunning = !!s.running; document.body.classList.toggle('deck', !!s.deck);
+ $('play').disabled = !!s.running; $('play').textContent = s.running ? 'PLAYING' : 'PLAY';
+ $('cApi').textContent = s.api || '–'; $('cProfile').textContent = s.profile || '';
+ if (s.version) $('ver').textContent = s.version;
+ const o = s.online;
+ if (o) {
+ $('mename').textContent = o.name; $('meav').textContent = (o.name || '?')[0].toUpperCase(); $('oname').value = o.name;
+ const cur = (o.servers || []).find(x => x.address === o.server);
+ $('meserver').textContent = (cur ? cur.name : o.server) + ' server'; $('cServer').textContent = cur ? cur.name : o.server;
+ $('ostatus').value = o.status || '';
+ $('regions').innerHTML = (o.servers || []).map(x => '<div class="region' + (x.address === o.server ? ' on' : '') + '" data-a="' + esc(x.address) + '">' +
+ '<span class="ping">' + (x.ping >= 0 ? '&#9679; ' + x.ping + ' ms' : 'offline') + '</span><b>' + esc(x.name) + '</b><small>' +
+ (x.online >= 0 ? x.online + ' players online' : '&nbsp;') + '</small></div>').join('');
+ document.querySelectorAll('.region').forEach(r => r.onclick = () => send({cmd: 'server', address: r.dataset.a}));
+ if (cur) { $('cOnline').textContent = cur.online >= 0 ? cur.online : '–'; $('cPing').textContent = cur.ping >= 0 ? cur.ping + ' ms ping' : 'server offline'; }
+ } else {
+ $('mename').textContent = 'Offline'; $('meserver').textContent = 'Online patch not installed'; $('medot').style.background = '#6b7280';
+ }
+}
+
+// ---------- Social: players, friends, requests, server chat and private chats (data comes from the launcher) ----------
+let social = {server: '', me: '', players: [], friends: [], requests: [], messages: {}, convos: {}};
+let channel = 'general', openTabs = ['general'], lastId = {}, seen = JSON.parse(localStorage.getItem('rs_seen') || '{}');
+const COL = ['#e0663a', '#5b6bd6', '#b0457a', '#3a9e7a', '#c58a2a', '#6d5bd0', '#2f8fb5'];
+const avatar = (n, st) => '<div class="pav ' + (st || '') + '" style="background:' + COL[[...n].reduce((a, c) => a + c.charCodeAt(0), 0) % COL.length] + '">' + esc((n || '?')[0].toUpperCase()) + '</div>';
+const socialOpen = () => $('p-social').classList.contains('on') || $('p-matches').classList.contains('on');
+function pollSocial() { send({cmd: 'social', channel, since: lastId[channel] || 0}); }
+setInterval(() => { if (socialOpen()) pollSocial(); else send({cmd: 'social', channel: '', since: 0}); }, socialOpen() ? 3000 : 3000);
+// Messages that arrived while the page was hidden could not scroll it: open Social at the newest one.
+document.querySelector('[data-p=p-social]').addEventListener('click', () => { $('msgs').scrollTop = $('msgs').scrollHeight; setTimeout(pollSocial, 50); });
+document.querySelector('[data-p=p-matches]').addEventListener('click', () => setTimeout(pollSocial, 50));
+document.querySelectorAll('.ptab').forEach(t => t.onclick = () => { document.querySelectorAll('.ptab').forEach(x => x.classList.toggle('on', x === t));
+ document.querySelectorAll('.plist').forEach(l => l.style.display = l.id === t.dataset.t ? 'flex' : 'none'); });
+$('addForm').onsubmit = e => { e.preventDefault(); const n = $('addName').value.trim(); if (n) { send({cmd: 'friend', action: 'add', other: n}); $('addName').value = ''; } };
+$('compose').onsubmit = e => { e.preventDefault(); const v = $('say').value.trim(); if (!v) return; send({cmd: 'chatSend', channel, text: v}); $('say').value = ''; };
+
+function person(name, note, st, actions) {
+ return '<div class="person" data-n="' + esc(name) + '">' + avatar(name, st) + '<div class="pn"><b>' + esc(name) + '</b><small>' + esc(note) + '</small></div>' + actions + '</div>';
+}
+const STADIUMS = {1047: 'Venice Canal', 1000: 'Tokyo Futsal Stadium', 1001: 'Shanghai Rooftop', 1005: 'Dubai', 1046: 'Paris: Notre Dame', 1048: 'Plaça de Catalunya', 1049: 'London',
+ 1051: 'Amsterdam Stadium', 1054: 'Rio Stadium', 1055: 'New York Stadium', 1040: 'The Dome', 1034: 'The Hangar', 1022: 'Goals Centre', 1028: 'Futsal Centre', 1010: 'Underpass 1', 1016: 'Underpass 2', 1068: 'Basketball Court'};
+const MODE = {fives: '5-a-side', sixes: '6-a-side', futsal: 'Futsal'};
+// Stadium strip: photos made from the player's own game files on the first PLAY (a tile without one shows the name).
+// Picking a stadium shows its Post match button right on the photo.
+const postMatch = () => { send({cmd: 'room', action: 'create', title: $('gTitle').value, mode: $('gMode').value, stadium: Number($('gStadium').value), channel}); $('gTitle').value = ''; };
+const pickStadium = id => { $('gStadium').value = id; document.querySelectorAll('.spic').forEach(t => { const on = t.dataset.id === String(id); t.classList.toggle('on', on); t.setAttribute('aria-checked', on); t.tabIndex = on ? 0 : -1; }); };
+$('gPics').innerHTML = Object.entries(STADIUMS).map(([id, n]) => '<div class="spic" role="radio" data-id="' + id + '" title="' + esc(n) + '"><img alt="" loading="lazy" src="https://restreet.thumbs/' + id + '.png" onerror="this.remove()"><span>' + esc(n) + '</span><button type="button" class="splay">&#9654; Post match</button></div>').join('');
+$('gPics').onclick = e => { if (e.target.closest('.splay')) return postMatch(); const t = e.target.closest('.spic'); if (t) pickStadium(t.dataset.id); };
+$('gPics').onkeydown = e => {
+ const tiles = [...document.querySelectorAll('.spic')], i = tiles.findIndex(t => t.classList.contains('on'));
+ const step = {ArrowRight: 1, ArrowLeft: -1}[e.key];
+ if (step) { e.preventDefault(); const t = tiles[Math.max(0, Math.min(tiles.length - 1, i + step))]; pickStadium(t.dataset.id); t.focus(); t.scrollIntoView({block: 'nearest', inline: 'nearest'}); }
+ else if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('spic')) { e.preventDefault(); postMatch(); }
+};
+// The mouse wheel scrolls the strip sideways.
+$('gPics').addEventListener('wheel', e => { if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) { e.preventDefault(); $('gPics').scrollLeft += e.deltaY; } }, {passive: false});
+pickStadium(1047); // Venice Canal, the server's default
+// The names the game itself shows (names.json, written with the pictures) replace the built-in English list.
+fetch('https://restreet.thumbs/names.json').then(r => r.ok ? r.json() : {}).then(names => {
+ for (const id of Object.keys(STADIUMS)) if (names[id]) STADIUMS[id] = names[id];
+ document.querySelectorAll('.spic').forEach(t => { t.title = STADIUMS[t.dataset.id]; t.querySelector('span').textContent = STADIUMS[t.dataset.id]; });
+}).catch(() => {});
+// One click handler on the panel: the list below is rebuilt by the 3 s refresh, the panel itself never is.
+$('games').addEventListener('click', e => {
+ const j = e.target.closest('[data-join]'); if (j) { j.disabled = true; send({cmd: 'room', action: 'join', room: Number(j.dataset.join), channel}); }
+ if (e.target.closest('#gLeave')) send({cmd: 'room', action: 'leave', channel});
+});
+let gamesHtml = '', readyShown = 0, gameIsRunning = false;
+$('rrPlay').onclick = () => { $('roomReady').classList.add('gone'); send({cmd: 'play'}); };
+$('rrLeave').onclick = () => { $('roomReady').classList.add('gone'); send({cmd: 'room', action: 'leave', channel}); };
+// Both games go to the friend match set-up by themselves; the launcher shows the game once both are in the lobby.
+function roomSteps(room, me) {
+ return (gameIsRunning ? 'Your game is restarting so it can open the match by itself. ' : '') +
+ 'ReStreet is opening straight into your ' + (MODE[room.mode] || room.mode) + ' match lobby.';
+}
+function renderGames(d) {
+ const me = (d.me || '').toLowerCase(), mine = d.myRoom;
+ const rooms = (d.rooms || []).filter(r => !mine || r.id !== mine.id);
+ const listHtml = rooms.map(r => '<div class="gcard"><b>' + esc(r.name) + '</b><small>by ' + esc(r.host) + ' · ' + esc(MODE[r.mode] || r.mode) + ' · ' + esc(r.stadium_name) + '</small>' +
+ '<div class="row2"><small>' + r.players.length + '/' + r.seats + ' players</small>' +
+ (r.players.length < r.seats && !mine ? '<button class="pact ok" data-join="' + r.id + '" style="width:auto;padding:0 16px;height:34px">Join</button>' : '<span class="full">' + (r.players.length >= r.seats ? 'Full' : '') + '</span>') + '</div></div>').join('') ||
+ '<div class="seek">No open matches right now. Post one and anyone on your server can join.</div>';
+ const mineHtml = mine ? (mine.players.length < mine.seats
+ ? 'Your ' + esc(MODE[mine.mode] || mine.mode) + ' game at ' + esc(mine.stadium_name) + ' is open, waiting for a player... '
+ : 'Game ready with ' + esc(mine.players.filter(p => p.toLowerCase() !== me).join(', ')) + '! ' + esc(roomSteps(mine, me)) + ' ') +
+ '<button class="pact" id="gLeave" style="width:auto;padding:0 12px;height:28px">Leave</button>' : '';
+ // The room just filled up: tell both players, once per room, wherever they are in the launcher.
+ if (mine && mine.players.length >= mine.seats && readyShown !== mine.id) {
+ readyShown = mine.id;
+ $('rrTitle').textContent = 'Loading your match with ' + mine.players.filter(p => p.toLowerCase() !== me).join(', ') + '...';
+ $('rrPlay').style.display = 'none'; // the launcher starts the game by itself
+ $('rrText').textContent = roomSteps(mine, me);
+ $('roomReady').classList.remove('gone');
+ }
+ if (!mine || mine.players.length < mine.seats || mine.joined) { $('roomReady').classList.add('gone'); if (!mine) readyShown = 0; }
+ if (listHtml + mineHtml !== gamesHtml) { gamesHtml = listHtml + mineHtml; $('gList').innerHTML = listHtml; $('gMine').innerHTML = mineHtml; }
+ $('gPost').style.display = mine ? 'none' : '';
+ $('gPics').style.display = mine ? 'none' : '';
+ const open = rooms.filter(r => r.players.length < r.seats).length;
+ $('matchBadge').style.display = open && !mine ? '' : 'none'; $('matchBadge').textContent = open;
+ const sm = Object.entries(d.searchingModes || {});
+ $('seek').innerHTML = sm.length ? sm.map(([m, n]) => '<b>' + n + '</b> ' + esc(m)).join(' · ') + '<br>Search the same mode in the game (Xbox LIVE) to be paired with them.' : 'Nobody is searching in the game right now.';
+}
+function renderSocial(d) {
+ social = Object.assign(social, d);
+ if (d.rooms !== undefined || d.myRoom !== undefined) renderGames(d);
+ const friendNames = new Set((d.friends || []).map(f => f.name.toLowerCase()));
+ const pendingNames = new Set((d.pending || []).map(n => n.toLowerCase()));
+ const sentBtn = '<button class="pact" disabled title="Request sent">&#10003;</button>';
+ $('bOnline').textContent = (d.players || []).length;
+ $('t-online').innerHTML = (d.players || []).map(p => person(p.name, p.note, p.state === 'in_game' ? 'game' : 'online',
+ p.name.toLowerCase() === (d.me || '').toLowerCase() ? '' : friendNames.has(p.name.toLowerCase()) ? '<button class="pact" data-dm="' + esc(p.name) + '">&#9993;</button>' : pendingNames.has(p.name.toLowerCase()) ? sentBtn : '<button class="pact" data-add="' + esc(p.name) + '">+</button>')).join('') || '<div class="sys">Nobody online</div>';
+ $('t-friends').innerHTML = (d.friends || []).map(f => person(f.name, f.online ? 'Online' : 'Offline', f.online ? 'online' : '', '<button class="pact" data-dm="' + esc(f.name) + '">&#9993;</button>')).join('') || '<div class="sys">Add friends from the Online list</div>';
+ const req = d.requests || [];
+ $('bReq').style.display = req.length ? '' : 'none'; $('bReq').textContent = req.length;
+ $('t-req').innerHTML = req.map(n => person(n, 'Wants to be your friend', 'online', '<button class="pact ok" data-acc="' + esc(n) + '">&#10003;</button><button class="pact" data-dec="' + esc(n) + '">&#10005;</button>')).join('') +
+ (d.pending || []).map(n => person(n, 'Request sent', '', '')).join('') || '<div class="sys">No requests</div>';
+ document.querySelectorAll('[data-add]').forEach(b => b.onclick = () => { b.outerHTML = sentBtn; send({cmd: 'friend', action: 'add', other: b.dataset.add}); });
+ document.querySelectorAll('[data-acc]').forEach(b => b.onclick = () => send({cmd: 'friend', action: 'add', other: b.dataset.acc}));
+ document.querySelectorAll('[data-dec]').forEach(b => b.onclick = () => send({cmd: 'friend', action: 'decline', other: b.dataset.dec}));
+ document.querySelectorAll('[data-dm]').forEach(b => b.onclick = () => openChat(b.dataset.dm));
+ document.querySelectorAll('.person').forEach(p => p.oncontextmenu = e => showMenu(e, p.dataset.n, friendNames.has(p.dataset.n.toLowerCase())));
+ // messages for the open channel
+ if (d.channel !== undefined && d.channel === channel && d.messages) {
+ const box = $('msgs'); let added = 0;
+ for (const m of d.messages) {
+ if (m.id <= (lastId[channel] || 0)) continue;
+ added++;
+ lastId[channel] = m.id;
+ const mine = m.from.toLowerCase() === (d.me || '').toLowerCase();
+ const el = document.createElement('div'); el.className = 'msg' + (mine ? ' me' : '');
+ el.innerHTML = avatar(m.from) + '<div class="mb"><div class="who">' + esc(m.from) + '<span>' + new Date(m.t * 1000).toTimeString().slice(0, 5) + '</span></div></div>';
+ el.querySelector('.mb').append(document.createTextNode(m.text));
+ if (!mine) el.oncontextmenu = e => showMenu(e, m.from, friendNames.has(m.from.toLowerCase()), m.id);
+ box.append(el);
+ }
+ if (added) box.scrollTop = box.scrollHeight; // always show the newest messages
+ seen[channel] = lastId[channel] || 0; localStorage.setItem('rs_seen', JSON.stringify(seen));
+ }
+ if (d.error) { $('chatNote').textContent = d.error; $('chatNote').style.color = '#f87171'; setTimeout(() => { $('chatNote').textContent = 'be nice, chat is moderated'; $('chatNote').style.color = ''; }, 5000); }
+ if (d.chatOff) { $('chatNote').textContent = 'Chat is not available on this server yet'; }
+ // unread private chats
+ let unread = 0;
+ for (const [name, id] of Object.entries(d.convos || {})) { if (id > (seen[name] || 0) && name !== channel) { unread++; if (!openTabs.includes(name)) openTabs.push(name); } }
+ renderTabs(d.convos || {});
+ const total = unread + req.length; $('navBadge').style.display = total ? '' : 'none'; $('navBadge').textContent = total;
+}
+function renderTabs(convos) {
+ $('ctabs').innerHTML = openTabs.map(t => '<div class="ctab' + (t === channel ? ' on' : '') + '" data-c="' + esc(t) + '">' + (t === 'general' ? '# ' + esc(social.server || 'Server') : esc(t)) +
+ ((convos[t] || 0) > (seen[t] || 0) && t !== channel ? ' <span class="badge">&bull;</span>' : '') + '</div>').join('');
+ document.querySelectorAll('.ctab').forEach(c => c.onclick = () => openChat(c.dataset.c));
+ $('say').placeholder = 'Message ' + (channel === 'general' ? '#' + (social.server || 'Server') : channel);
+}
+function openChat(name) {
+ if (!openTabs.includes(name)) openTabs.push(name);
+ channel = name; $('msgs').innerHTML = ''; lastId[channel] = 0; renderTabs(social.convos || {}); pollSocial();
+}
+const pm = $('pmenu'); let menuFor = null, menuMsg = null;
+function showMenu(e, name, isFriend, msgId) {
+ e.preventDefault(); if (name.toLowerCase() === (social.me || '').toLowerCase()) return;
+ menuFor = name; menuMsg = msgId || null;
+ pm.querySelector('[data-a=dm]').style.display = isFriend ? '' : 'none';
+ pm.querySelector('[data-a=add]').style.display = isFriend ? 'none' : '';
+ pm.querySelector('[data-a=remove]').style.display = isFriend ? '' : 'none';
+ let rep = pm.querySelector('[data-a=report]'); if (rep) rep.remove();
+ if (menuMsg) { rep = document.createElement('div'); rep.dataset.a = 'report'; rep.className = 'bad'; rep.textContent = 'Report message'; pm.append(rep); }
+ const r = $('p-social').getBoundingClientRect(); pm.style.left = (e.clientX - r.left) + 'px'; pm.style.top = (e.clientY - r.top) + 'px'; pm.classList.add('on');
+}
+pm.onclick = e => { const a = e.target.dataset.a; if (!a || !menuFor) return;
+ if (a === 'dm') openChat(menuFor);
+ else if (a === 'add' || a === 'remove') send({cmd: 'friend', action: a, other: menuFor});
+ else if (a === 'block') { send({cmd: 'chatAction', action: 'block', other: menuFor}); $('msgs').innerHTML = ''; lastId[channel] = 0; }
+ else if (a === 'report') send({cmd: 'chatAction', action: 'report', id: menuMsg});
+ pm.classList.remove('on'); };
+addEventListener('click', () => pm.classList.remove('on'));
+
+if (host) { host.addEventListener('message', e => !e.data ? 0 : e.data.type === 'social' ? renderSocial(e.data) : e.data.type === 'perf' ? renderPerf(e.data) : e.data.type === 'perfHistory' ? renderHistory(e.data) : String(e.data.type).startsWith('update') ? renderUpdate(e.data) : render(e.data)); send({cmd: 'state'}); }
+addEventListener('mousemove', e => { for (const g of document.querySelectorAll('.glass')) { const r = g.getBoundingClientRect(); g.style.setProperty('--mx', ((e.clientX - r.left) / r.width * 100) + '%'); } });
+</script>
+<script src="lang.js"></script></body></html>
\ No newline at end of file