Files
grass-cutters/Assets/Scripts/UI/UIRoot.cs
NiemandKG ad2154b38c Release checklist: no cheat console for players, Steam required, Steam's language wins when changed, menu links, head bob toggle
- The cheat console opens only in the editor, a development build, or with -gcdev
- Without steam_appid.txt next to the exe, a failed Steam start says so and quits instead of running offline; -nosteam only works in our own builds
- A language picked in the game's Steam properties overrides the one saved in the game, if it changed since
- Main menu: language button, Steam page (overlay, else browser), feedback (Steam discussions); "early build" and the AppID gone from the footer
- Settings > Game: head bob on/off
- The cursor stays inside the window while it's free
- -resetsettings puts every setting back as it comes out of the box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:45:17 +06:00

811 lines
38 KiB
C#

using System;
using System.Collections.Generic;
using Steamworks;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
/// <summary>Owns the UI Toolkit document: main menu, modals (browser, settings, pause, messages), HUD and shop.</summary>
[RequireComponent(typeof(UIDocument))]
public partial class UIRoot : MonoBehaviour
{
public static UIRoot I { get; private set; }
public StyleSheet style;
VisualElement _root, _world, _hud, _screens, _modals, _cinema, _fade;
/// <summary>Over the HUD and the screens, under the fade: the opening film's black and the call's captions.</summary>
public VisualElement Cinema => _cinema;
bool _hudHidden;
/// <summary>The opening film hides the HUD while it runs.</summary>
public void HideHud(bool hide) { _hudHidden = hide; if (_inGame) _hud.style.display = hide ? DisplayStyle.None : DisplayStyle.Flex; }
VisualElement _menu, _connecting;
Label _connectingText;
readonly List<VisualElement> _modalStack = new List<VisualElement>();
public Hud Hud { get; private set; }
ShopScreen _shop;
public ShopScreen Shop => _shop;
bool _inGame;
public bool InGame => _inGame;
public bool AnyModal => _modalStack.Count > 0;
VisualElement _consoleLayer;
public CheatConsole Console { get; private set; }
/// <summary>~ / F1: drop the cheat console down (or put it away).</summary>
public void ToggleConsole()
{
if (_consoleLayer != null) { CloseModal(_consoleLayer); return; }
if (!_inGame || !Cheats.Allowed) return;
_consoleLayer = OpenModal(layer => { Console = new CheatConsole(layer); return null; }, dim: false);
UIK.SlideIn(Console.Panel, new Vector2(0f, -400f), 0f, 0.25f);
}
void Awake()
{
I = this;
var bank = AssetBank.I;
Loc.Init();
Loc.Fonts(bank, out UIK.Display, out UIK.Body);
}
void Start()
{
var doc = GetComponent<UIDocument>();
_root = doc.rootVisualElement;
if (style) _root.styleSheets.Add(style);
_root.AddToClassList("root");
UIK.SetFont(_root, false);
_world = UIK.El("layer", _root);
_hud = UIK.El("layer", _root);
_screens = UIK.El("layer", _root);
_modals = UIK.El("layer", _root);
_cinema = UIK.El("layer", _root);
_cinema.pickingMode = PickingMode.Ignore;
_fade = UIK.El("layer fade", _root);
_fade.style.opacity = 1f;
Hud = new Hud(_hud, _world);
_hud.style.display = DisplayStyle.None;
gameObject.AddComponent<DirectorCall>();
gameObject.AddComponent<IntroCinematic>();
gameObject.AddComponent<Assistant>();
BuildMenu();
BuildConnecting();
var ns = NetSession.Instance;
ns.Started += OnGameStarted;
ns.Ended += OnGameEnded;
ns.Failed += msg => Message(Loc.T("Whoops!"), Loc.Unpack(msg));
ns.JoinAsked += lobby => Confirm(Loc.T("Join your friend?"), Loc.T("You'll leave this game. It's saved first."), () => ns.JoinLobby(lobby));
ns.StatusChanged += s =>
{
bool show = ns.Current == NetSession.State.Connecting;
_connecting.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
if (show) { _connectingText.text = Loc.Unpack(s); UIK.PopIn(_connecting.Q(className: "card")); }
};
GameSettings.Apply();
GameSettings.ApplyDisplay();
Sfx.Music("music_menu_loop", 2f);
UIK.Fade(_fade, 0f, 0.8f);
_fade.pickingMode = PickingMode.Ignore;
Loc.Changed += Relocalize;
SteamManager.OverlayChanged += active => { if (active && _inGame && !AnyModal && !CommandLine.Has("-autodemo")) OpenPause(); };
}
void Update()
{
if (_holdSince >= 0f && Time.unscaledTime - _holdSince > 15f) ReleaseFade(0.6f);
// a test bot runs on the same desktop: Esc pressed elsewhere is not for it
if (_capture != null) PollCapture();
else if (Ctl.PausePressed && !CommandLine.Has("-autodemo"))
{
if (_modalStack.Count > 0) CloseTopModal();
else if (Phone.Back()) { }
else if (_inGame) OpenPause();
}
if (Ctl.ConsolePressed) ToggleConsole();
if (Ctl.MapPressed && _inGame && _consoleLayer == null)
{
if (_mapLayer != null && _modalStack.Count > 0 && _modalStack[_modalStack.Count - 1] == _mapLayer) CloseModal(_mapLayer);
else if (!AnyModal) OpenMap();
}
if (Ctl.NotebookPressed && _inGame && _consoleLayer == null)
{
if (_notebookLayer != null && _modalStack.Count > 0 && _modalStack[_modalStack.Count - 1] == _notebookLayer) CloseModal(_notebookLayer);
else if (!AnyModal) OpenNotebook();
}
Ctl.UIOpen = _modalStack.Count > 0 || !_inGame;
if (_inGame) Ctl.SetCursor(!AnyModal && !Phone.Focused && !SteamManager.OverlayActive);
Hud?.Tick(_inGame && !AnyModal);
Hud?.SetTabList(_inGame && !AnyModal && Ctl.TabHeld);
_spinAngle += Time.unscaledDeltaTime * 360f;
var sp = _connecting?.Q(className: "spinner");
if (sp != null) sp.style.rotate = new Rotate(_spinAngle);
}
float _spinAngle;
// ───────────────────────── menu ─────────────────────────
void BuildMenu()
{
var bank = AssetBank.I;
_menu = UIK.El("layer", _screens);
// soft vignette panel behind the buttons
var shade = UIK.El("layer", _menu);
shade.style.backgroundImage = new StyleBackground(GradientTex());
shade.style.unityBackgroundScaleMode = ScaleMode.StretchToFill;
var logo = UIK.Img(bank.Tex("logo_grasscutter"), "menu-logo", _menu);
var tag = UIK.Text(Loc.T("Earth has run out of grass. Herbaria-7 has too much."), "menu-tagline t-outline", _menu);
var side = UIK.El("menu-side", _menu);
side.pickingMode = PickingMode.Ignore;
var buttons = new List<VisualElement>
{
UIK.Btn(Loc.T("PLAY"), OpenSlots, "btn btn-wide", side),
UIK.Btn(Loc.T("FIND GAMES"), OpenBrowser, "btn btn-blue btn-wide", side),
UIK.Btn(Loc.T("CHARACTER"), OpenCharacter, "btn btn-white btn-wide", side),
UIK.Btn(Loc.T("SETTINGS"), OpenSettings, "btn btn-white btn-wide", side),
UIK.Btn(Loc.T("QUIT"), Quit, "btn btn-red btn-wide", side),
};
var hint = UIK.Text(Loc.T(SteamManager.Initialized ? Loc.N("PLAY alone, on your LAN, or in a Steam lobby: invite friends with Shift+Tab.") : Loc.N("Steam not running: play alone or on your LAN.")), "t-small t-outline", side, false);
hint.style.marginTop = 14;
// the language in a click (Chinese above all), the store page and where to tell us what's wrong
var links = UIK.El("menu-links", side);
links.style.flexDirection = FlexDirection.Row;
links.style.flexWrap = Wrap.Wrap;
links.style.marginTop = 18;
var langBtn = UIK.Btn(Loc.T("Language") + ": " + Loc.Current.native, OpenLanguages, "btn btn-white btn-small", links);
SetLangFont(langBtn, Loc.Current);
UIK.Btn(Loc.T("STEAM PAGE"), () => SteamManager.OpenStore(), "btn btn-blue btn-small", links).style.marginLeft = 10;
UIK.Btn(Loc.T("FEEDBACK"), () => SteamManager.OpenWeb(SteamManager.FeedbackUrl), "btn btn-green btn-small", links).style.marginLeft = 10;
var footer = UIK.El("menu-footer", _menu);
var pill = UIK.El("pill", footer);
var av = UIK.El("avatar", pill);
var avatarTex = SteamManager.Initialized ? SteamManager.GetAvatar(SteamManager.MySteamId) : null;
if (avatarTex) av.style.backgroundImage = new StyleBackground(avatarTex);
UIK.Text(SteamManager.MyName, "t-body", pill);
var dot = UIK.El("status-dot", pill);
dot.style.backgroundColor = SteamManager.Initialized ? new Color(0.22f, 0.85f, 0.54f) : new Color(1f, 0.55f, 0.24f);
UIK.Text(SteamManager.Initialized ? "Steam" : Loc.T("Offline"), "t-small t-muted", pill, false);
UIK.Text("v" + NetSession.Version, "version", _menu, false);
// entrance animation + idle logo bob
UIK.PopIn(logo, 0.25f, 0.7f);
UIK.SlideIn(tag, new Vector2(0, 30), 0.6f);
for (int i = 0; i < buttons.Count; i++) UIK.SlideIn(buttons[i], new Vector2(-420, 0), 0.15f + i * 0.07f);
logo.schedule.Execute(() =>
{
float t = Time.unscaledTime;
logo.style.rotate = new Rotate(Mathf.Sin(t * 1.3f) * 2f);
logo.style.translate = new Translate(0, Mathf.Sin(t * 1.9f) * 10f);
}).Every(16).StartingIn(1000);
}
static Texture2D _grad;
static Texture2D GradientTex()
{
if (_grad) return _grad;
_grad = new Texture2D(256, 1, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp };
for (int x = 0; x < 256; x++)
{
float k = x / 255f;
float a = Mathf.Clamp01(1f - k * 1.6f) * 0.72f;
_grad.SetPixel(x, 0, new Color(0.08f, 0.12f, 0.05f, a));
}
_grad.Apply();
return _grad;
}
void BuildConnecting()
{
_connecting = UIK.El("layer dim", _screens);
_connecting.pickingMode = PickingMode.Position;
_connecting.style.alignItems = Align.Center;
_connecting.style.justifyContent = Justify.Center;
var card = UIK.El("card", _connecting);
card.style.alignItems = Align.Center;
card.style.minWidth = 520;
UIK.El("spinner", card);
_connectingText = UIK.Text(Loc.T("Connecting…"), "t-h2 t-dark t-center", card);
UIK.Btn(Loc.T("CANCEL"), () => NetSession.Instance.Leave(), "btn btn-red btn-small", card).style.marginTop = 16;
_connecting.style.display = DisplayStyle.None;
}
float _holdSince = -1f;
/// <summary>The opening film decides when the black lifts: at once under its own black, or a normal fade.</summary>
public void ReleaseFade(float seconds)
{
if (_holdSince < 0f) return;
_holdSince = -1f;
Tween.Kill(_fade);
if (seconds <= 0f) _fade.style.opacity = 0f;
else UIK.Fade(_fade, 0f, seconds);
}
void OnGameStarted()
{
_inGame = true;
_fade.style.opacity = 1f;
// a new game may open on the film: stay black until it says, so the world never flashes up first
if (IntroCinematic.MightRun) { Tween.Kill(_fade); _holdSince = Time.unscaledTime; }
else UIK.Fade(_fade, 0f, 0.6f);
_menu.style.display = DisplayStyle.None;
_connecting.style.display = DisplayStyle.None;
_hud.style.display = _hudHidden ? DisplayStyle.None : DisplayStyle.Flex;
Hud.OnGameStarted();
CloseAllModals();
Sfx.Music("music_game_loop", 1.5f);
Ctl.SetCursor(true);
}
void OnGameEnded()
{
_inGame = false;
CloseAllModals();
_hud.style.display = DisplayStyle.None;
Hud.OnGameEnded();
_menu.style.display = DisplayStyle.Flex;
_fade.style.opacity = 1f;
UIK.Fade(_fade, 0f, 0.6f);
foreach (var b in _menu.Query<Button>().ToList()) UIK.PopIn(b, UnityEngine.Random.Range(0f, 0.2f));
Sfx.Music("music_menu_loop", 1.5f);
Ctl.SetCursor(false);
}
void Quit()
{
UIK.Fade(_fade, 1f, 0.35f, () =>
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
});
}
// ───────────────────────── modals ─────────────────────────
public VisualElement OpenModal(Func<VisualElement, VisualElement> build, bool dim = true)
{
var layer = UIK.El(dim ? "layer dim" : "layer", _modals);
layer.pickingMode = PickingMode.Position;
layer.style.alignItems = Align.Center;
layer.style.justifyContent = Justify.Center;
var content = build(layer);
_modalStack.Add(layer);
layer.style.opacity = 0f;
UIK.Fade(layer, 1f, 0.15f);
if (content != null) UIK.PopIn(content);
Sfx.Play("ui_open", 0.6f);
Ctl.SetCursor(false);
return layer;
}
public void CloseModal(VisualElement layer)
{
if (layer == null || !_modalStack.Contains(layer)) return;
_modalStack.Remove(layer);
layer.pickingMode = PickingMode.Ignore;
Sfx.Play("ui_close", 0.5f);
UIK.Fade(layer, 0f, 0.14f, () => layer.RemoveFromHierarchy());
if (layer == _shopLayer) { _shopLayer = null; _shop = null; }
if (layer == _garageLayer) _garageLayer = null;
if (layer == _stationLayer) _stationLayer = null;
if (layer == _mapLayer) _mapLayer = null;
if (layer == _pieceLayer) _pieceLayer = null;
if (layer == _supplyLayer) _supplyLayer = null;
if (layer == _consoleLayer) { _consoleLayer = null; Console = null; }
}
public void CloseTopModal()
{
if (_modalStack.Count > 0) CloseModal(_modalStack[_modalStack.Count - 1]);
}
void CloseAllModals()
{
foreach (var m in _modalStack.ToArray()) CloseModal(m);
}
public void Message(string title, string body)
{
OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.style.width = 640;
card.style.alignItems = Align.Center;
UIK.Text(title, "t-h1 t-dark t-center", card);
var b = UIK.Text(body, "t-body t-dark t-center", card, false);
b.style.whiteSpace = WhiteSpace.Normal;
b.style.marginTop = 8; b.style.marginBottom = 18;
UIK.Btn(Loc.T("OK"), () => CloseModal(layer), "btn btn-small", card);
return card;
});
Sfx.Play("error", 0.6f);
}
internal void OpenPause()
{
OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.style.width = 560;
card.style.alignItems = Align.Stretch;
UIK.Text(Loc.T("PAUSED"), "t-h1 t-dark t-center", card);
var ns = NetSession.Instance;
var sub = ns.InLobby ? LobbyName(ns.Kind) : ns.Kind == NetSession.LobbyKind.Lan && ns.LanPort != 0 ? Loc.F("LAN game · {0} port {1}", LanBeacon.MyAddresses(), ns.LanPort) : ns.Kind == NetSession.LobbyKind.Lan ? Loc.T("LAN game") : Loc.T("Solo game");
UIK.Text(sub + " · " + Loc.F("{0}/{1} crew", PlayerAgent.All.Count, NetSession.MaxPlayers), "t-small t-muted t-center", card, false).style.marginBottom = 14;
UIK.Btn(Loc.T("RESUME"), () => CloseModal(layer), "btn", card);
if (ns.InLobby) UIK.Btn(Loc.T("INVITE FRIENDS"), () => ns.InviteFriends(), "btn btn-blue", card);
if (PlayerAgent.All.Count > 1 && Unity.Netcode.NetworkManager.Singleton.IsHost) UIK.Btn(Loc.T("CREW"), OpenCrew, "btn btn-blue", card);
UIK.Btn(Loc.T("CHARACTER"), OpenCharacter, "btn btn-white", card);
UIK.Btn(Loc.T("ACHIEVEMENTS"), OpenAwards, "btn btn-white", card);
UIK.Btn(Loc.T("SETTINGS"), OpenSettings, "btn btn-white", card);
UIK.Btn(Loc.T("LEAVE TO MENU"), () => { CloseModal(layer); ns.Leave(); }, "btn btn-red", card);
return card;
});
}
internal void OpenBrowser()
{
VisualElement list = null, lan = null;
Label status = null, lanStatus = null;
Action<List<LobbyInfo>> onList = null;
var layer = OpenModal(l =>
{
var card = UIK.El("card", l);
card.style.width = 860;
var header = UIK.El("card-header", card);
UIK.Text(Loc.T("FIND A FARM"), "t-h1 t-dark", header);
UIK.Btn(Loc.T("REFRESH"), () => { status.text = Loc.T("Looking for lobbies…"); list.Clear(); NetSession.Instance.RequestLobbyList(); }, "btn btn-blue btn-small", header);
status = UIK.Text(Loc.T("Looking for lobbies…"), "t-body t-muted wrap", card, false);
var scroll = new ScrollView(ScrollViewMode.Vertical);
scroll.AddToClassList("list");
scroll.style.maxHeight = 300;
card.Add(scroll);
list = scroll.contentContainer;
UIK.Text(Loc.T("ON YOUR NETWORK"), "t-h2 t-dark", card).style.marginTop = 12;
lan = UIK.El(null, card);
lanStatus = UIK.Text(Loc.T("Listening for LAN games…"), "t-body t-muted wrap", card, false);
var byIp = UIK.El(null, card);
byIp.style.flexDirection = FlexDirection.Row;
byIp.style.alignItems = Align.Center;
byIp.style.marginTop = 10;
UIK.Text(Loc.T("Address"), "t-body t-dark", byIp, false).style.marginRight = 12;
var field = new TextField { value = PlayerPrefs.GetString("lan_address", "") };
field.AddToClassList("console-input");
field.AddToClassList("address-input");
UIK.SetFont(field, false);
byIp.Add(field);
void JoinTyped()
{
if (!NetSession.ParseAddress(field.value, out var ip, out var port)) { Message(Loc.T("Which address?"), Loc.T("Type the host's address from their pause screen, like 192.168.1.20 or 192.168.1.20:7778.")); return; }
PlayerPrefs.SetString("lan_address", field.value.Trim());
CloseModal(l);
NetSession.Instance.JoinLocal(ip, port);
}
field.RegisterCallback<KeyDownEvent>(e => { if (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter) JoinTyped(); }, TrickleDown.TrickleDown);
UIK.Btn(Loc.T("JOIN"), JoinTyped, "btn btn-green btn-small", byIp).style.marginLeft = 12;
UIK.Text(Loc.T("Tip: friends can also join you straight from the Steam friends list."), "t-small t-muted wrap", card, false).style.marginTop = 10;
UIK.Btn(Loc.T("BACK"), () => CloseModal(l), "btn btn-white btn-small", card).style.alignSelf = Align.FlexStart;
return card;
});
// LAN games are heard, not asked for: the list is redrawn from what came in during the last seconds
LanBeacon.Listen();
string shown = null;
layer.schedule.Execute(() =>
{
if (layer.panel == null) return;
var games = LanBeacon.Found();
var key = string.Join(";", games.ConvertAll(g => $"{g.ip}:{g.port}:{g.members}:{g.name}"));
if (key == shown) return;
shown = key;
lan.Clear();
lanStatus.text = games.Count == 0 ? Loc.T("No LAN games heard yet. The host picks LAN under PLAY.") : "";
lanStatus.style.display = games.Count == 0 ? DisplayStyle.Flex : DisplayStyle.None;
foreach (var g in games)
{
var row = UIK.El("lobby-row", lan);
row.pickingMode = PickingMode.Position;
UIK.Text(g.name, "t-h2 t-dark", row);
var right = UIK.El(null, row);
right.style.flexDirection = FlexDirection.Row;
right.style.alignItems = Align.Center;
UIK.Text($"{g.ip} {g.members}/{g.max}", "t-body t-muted", right, false).style.marginRight = 16;
var game = g;
UIK.Btn(Loc.T("JOIN"), () => { CloseModal(layer); NetSession.Instance.JoinLocal(game.ip, game.port); }, "btn btn-green btn-small", right);
}
}).Every(500);
layer.RegisterCallback<DetachFromPanelEvent>(_ => LanBeacon.StopListening());
onList = lobbies =>
{
if (layer.panel == null) { NetSession.Instance.LobbyListReceived -= onList; return; }
list.Clear();
status.text = lobbies.Count == 0 ? Loc.T(SteamManager.Initialized ? Loc.N("No public bases right now — host one!") : Loc.N("Steam isn't running, so there's nothing to browse.")) : Loc.F("{0} base(s) found", lobbies.Count);
int i = 0;
foreach (var lb in lobbies)
{
var row = UIK.El("lobby-row", list);
row.pickingMode = PickingMode.Position;
UIK.Text(string.IsNullOrEmpty(lb.name) ? Loc.T("Mow Base") : lb.name, "t-h2 t-dark", row);
var right = UIK.El(null, row);
right.style.flexDirection = FlexDirection.Row;
right.style.alignItems = Align.Center;
UIK.Text($"{lb.members}/{lb.max}", "t-body t-muted", right, false).style.marginRight = 16;
var id = lb.id;
UIK.Btn(Loc.T("JOIN"), () => { CloseModal(layer); NetSession.Instance.JoinLobby(id); }, "btn btn-green btn-small", right);
UIK.SlideIn(row, new Vector2(60, 0), i++ * 0.05f, 0.35f);
}
};
NetSession.Instance.LobbyListReceived += onList;
NetSession.Instance.RequestLobbyList();
}
internal void OpenLanguages()
{
VisualElement modal = null;
modal = OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.pickingMode = PickingMode.Position;
card.style.width = 760;
var header = UIK.El("card-header", card);
UIK.Text(Loc.T("Language"), "t-h1 t-dark", header);
UIK.Btn("X", () => CloseModal(modal), "btn btn-red btn-small", header);
var grid = UIK.El(null, card);
grid.style.flexDirection = FlexDirection.Row;
grid.style.flexWrap = Wrap.Wrap;
grid.style.justifyContent = Justify.SpaceBetween;
foreach (var l in Loc.All)
{
var lang = l;
var b = UIK.Btn(l.native, () =>
{
CloseModal(modal);
if (lang != Loc.Current) Loc.Set(lang.code);
}, l == Loc.Current ? "btn btn-small" : "btn btn-white btn-small", grid);
b.style.width = Length.Percent(32);
b.style.marginBottom = 10;
b.style.fontSize = 21;
b.style.paddingLeft = b.style.paddingRight = 8;
SetLangFont(b, l);
}
return card;
});
}
/// <summary>A new language: new fonts, and every screen built again in it. Open dialogs close, settings reopen.</summary>
void Relocalize()
{
var oldDisplay = UIK.Display;
var oldBody = UIK.Body;
Loc.Fonts(AssetBank.I, out UIK.Display, out UIK.Body);
bool settings = _settingsLayer != null && _modalStack.Contains(_settingsLayer);
foreach (var m in _modalStack.ToArray()) { _modalStack.Remove(m); m.RemoveFromHierarchy(); }
_shopLayer = _garageLayer = _stationLayer = _mapLayer = _pieceLayer = _supplyLayer = _notebookLayer = _consoleLayer = _settingsLayer = null;
_shop = null;
Console = null;
// what stays on screen (the phone, a call, captions) keeps its text but takes the new letters
SwapFonts(_root, oldDisplay, oldBody);
UIK.SetFont(_root, false);
bool menuShown = _menu.style.display != DisplayStyle.None;
_menu.RemoveFromHierarchy();
BuildMenu();
_menu.SendToBack();
_menu.style.display = menuShown ? DisplayStyle.Flex : DisplayStyle.None;
bool connShown = _connecting.style.display == DisplayStyle.Flex;
_connecting.RemoveFromHierarchy();
BuildConnecting();
_connecting.style.display = connShown ? DisplayStyle.Flex : DisplayStyle.None;
Hud.Detach();
_hud.Clear();
Hud = new Hud(_hud, _world);
if (_inGame)
{
if (PlayerAgent.Local) Hud.OnLocalPlayerSpawned(PlayerAgent.Local);
OpenPause();
}
if (settings) OpenSettings();
}
static void SwapFonts(VisualElement root, Font oldDisplay, Font oldBody)
{
root.Query<VisualElement>().ForEach(e =>
{
var f = e.style.unityFontDefinition;
if (f.keyword != StyleKeyword.Undefined) return;
var font = f.value.font;
if (!font) return;
if (font == oldDisplay) UIK.SetFont(e, true);
else if (font == oldBody) UIK.SetFont(e, false);
});
}
public void Confirm(string title, string body, Action yes)
{
OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.style.width = 640;
card.style.alignItems = Align.Center;
UIK.Text(title, "t-h1 t-dark t-center", card);
var b = UIK.Text(body, "t-body t-dark t-center", card, false);
b.style.whiteSpace = WhiteSpace.Normal;
b.style.marginBottom = 18;
var row = UIK.El(null, card);
row.style.flexDirection = FlexDirection.Row;
UIK.Btn(Loc.T("CANCEL"), () => CloseModal(layer), "btn btn-white btn-small", row).style.marginRight = 14;
UIK.Btn(Loc.T("YES"), () => { CloseModal(layer); yes(); }, "btn btn-red btn-small", row);
return card;
});
}
// ───────────────────────── shop, supply wall, map ─────────────────────────
VisualElement _shopLayer;
VisualElement _garageLayer, _stationLayer;
NetSession.LobbyKind _lobby;
static string LobbyName(NetSession.LobbyKind k) => k switch
{
NetSession.LobbyKind.Public => Loc.T("Public lobby"),
NetSession.LobbyKind.Invite => Loc.T("Invite-only lobby"),
NetSession.LobbyKind.Solo => Loc.T("Solo: just me"),
NetSession.LobbyKind.Lan => Loc.T("LAN: local network"),
_ => Loc.T("Friends-only lobby"),
};
/// <summary>Who may join, in the order the button steps through them. Without Steam only the two that need no Steam.</summary>
static NetSession.LobbyKind[] Kinds => SteamManager.Initialized
? new[] { NetSession.LobbyKind.Friends, NetSession.LobbyKind.Invite, NetSession.LobbyKind.Public, NetSession.LobbyKind.Lan, NetSession.LobbyKind.Solo }
: new[] { NetSession.LobbyKind.Solo, NetSession.LobbyKind.Lan };
/// <summary>Five saves, and who may join the one you pick.</summary>
public void OpenSlots()
{
VisualElement modal = null;
modal = OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.pickingMode = PickingMode.Position;
card.style.width = 760;
var header = UIK.El("card-header", card);
UIK.Text(Loc.T("CHOOSE A SAVE"), "t-h1 t-dark", header);
UIK.Btn("X", () => CloseModal(modal), "btn btn-red btn-small", header);
var kinds = Kinds;
if (Array.IndexOf(kinds, _lobby) < 0) _lobby = kinds[0];
Button kind = null;
kind = UIK.Btn(LobbyName(_lobby), () =>
{
_lobby = kinds[(Array.IndexOf(kinds, _lobby) + 1) % kinds.Length];
kind.text = LobbyName(_lobby);
}, "btn btn-blue btn-small", card);
var list = UIK.El(null, card);
SlotRows(list, modal);
return card;
});
}
void SlotRows(VisualElement list, VisualElement modal)
{
list.Clear();
for (int i = 0; i < SaveSlots.Count; i++)
{
int slot = i;
var info = SaveSlots.Info(i);
var row = UIK.El("tune-row", list);
var names = UIK.El("tune-names", row);
UIK.Text(Loc.F("Save {0}", i + 1), "t-small t-dark", names, false);
UIK.Text(info.used ? Loc.F("{0} · {1} · {2} shipped · {3}", Difficulties.Name(info.level), UIK.Money(info.money), GameDefs.Kilos((float)info.shipped), info.when.ToString("g", Loc.Culture)) : Loc.T("Empty"), "tune-effect", names, false);
UIK.Btn(info.used ? Loc.T("PLAY") : Loc.T("NEW GAME"), () =>
{
void Go()
{
SaveSlots.Current = slot;
CloseModal(modal);
NetSession.Instance.Host(_lobby);
}
if (info.used) Go();
else OpenDifficulty(level => { Difficulties.Chosen = level; Go(); });
}, "btn btn-green btn-small", row);
if (info.used)
UIK.Btn(Loc.T("DELETE"), () => Confirm(Loc.T("Delete this save?"), Loc.F("Save {0} and its backups go for good.", slot + 1), () =>
{
SaveSlots.Delete(slot);
SlotRows(list, modal);
}), "btn btn-red btn-small", row).style.marginLeft = 8;
}
}
/// <summary>How big a planet a new save gets: asked once, before it starts, and kept with the save.</summary>
internal void OpenDifficulty(Action<Difficulty> start)
{
VisualElement modal = null;
modal = OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.pickingMode = PickingMode.Position;
card.style.width = 820;
var header = UIK.El("card-header", card);
UIK.Text(Loc.T("HOW MUCH LAWN?"), "t-h1 t-dark", header);
UIK.Btn("X", () => CloseModal(modal), "btn btn-red btn-small", header);
foreach (var d in Difficulties.Order)
{
var level = d;
var row = UIK.El("tune-row", card);
var names = UIK.El("tune-names", row);
UIK.Text($"{Difficulties.Name(level)} · {Difficulties.Tag(level)}", "t-small t-dark", names, false);
UIK.Text(Difficulties.Blurb(level), "tune-effect", names, false);
UIK.Btn(Loc.T("START"), () =>
{
CloseModal(modal);
start(level);
}, level == Difficulty.Hazard ? "btn btn-red btn-small" : level == Difficulty.HoldMyBeer ? "btn btn-blue btn-small" : "btn btn-green btn-small", row);
}
return card;
});
}
public void OpenStations()
{
if (_stationLayer != null) return;
_stationLayer = OpenModal(layer => new StationScreen(layer, () => CloseModal(_stationLayer)).Card);
}
public void OpenAwards()
{
VisualElement modal = null;
modal = OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.pickingMode = PickingMode.Position;
card.style.width = 720;
card.style.height = 720;
var header = UIK.El("card-header", card);
UIK.Text(Loc.T("ACHIEVEMENTS") + $" {Achievements.Earned}/{Achievements.All.Count}", "t-h1 t-dark", header);
UIK.Btn("X", () => CloseModal(modal), "btn btn-red btn-small", header);
var list = new ScrollView(ScrollViewMode.Vertical);
list.AddToClassList("tune-list");
card.Add(list);
foreach (var a in Achievements.All)
{
bool got = Achievements.Has(a);
var row = UIK.El("tune-row", list.contentContainer);
row.style.opacity = got ? 1f : 0.45f;
var names = UIK.El("tune-names", row);
UIK.Text(a.name, "t-small t-dark", names, false);
UIK.Text(a.desc, "tune-effect", names, false);
if (got) UIK.Img(AssetBank.I.Tex("icon_star"), "check-icon", row);
}
return card;
});
}
/// <summary>Who you go as: taken up at once if you're already on the planet.</summary>
public void OpenCharacter()
{
VisualElement modal = null;
modal = OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.pickingMode = PickingMode.Position;
card.style.width = 1120;
var header = UIK.El("card-header", card);
UIK.Text(Loc.T("CHARACTER"), "t-h1 t-dark", header);
UIK.Btn("X", () => CloseModal(modal), "btn btn-red btn-small", header);
var grid = UIK.El("crew-grid", card);
var tiles = new List<VisualElement>();
for (int i = 0; i < Roster.All.Length; i++)
{
int who = i;
var m = Roster.All[i];
var tile = UIK.El("crew-tile", grid);
tile.pickingMode = PickingMode.Position;
tile.EnableInClassList("crew-on", i == GameSettings.Character);
UIK.Img(AssetBank.I.Tex(m.icon), "crew-face", tile);
UIK.Text(m.name, "t-body t-dark t-center", tile, false);
UIK.Text(Loc.T(m.line), "t-small t-muted t-center crew-line", tile, false);
tile.RegisterCallback<ClickEvent>(_ =>
{
GameSettings.Character = who;
if (PlayerAgent.Local) PlayerAgent.Local.Character.Value = (byte)who;
for (int k = 0; k < tiles.Count; k++) tiles[k].EnableInClassList("crew-on", k == who);
Sfx.Play("ui_click", 0.5f);
});
tiles.Add(tile);
}
return card;
});
}
/// <summary>Host: everyone aboard, and the door.</summary>
void OpenCrew()
{
VisualElement modal = null;
modal = OpenModal(layer =>
{
var card = UIK.El("card", layer);
card.pickingMode = PickingMode.Position;
card.style.width = 620;
var header = UIK.El("card-header", card);
UIK.Text(Loc.T("CREW"), "t-h1 t-dark", header);
UIK.Btn("X", () => CloseModal(modal), "btn btn-red btn-small", header);
var ts = TeamState.Instance;
foreach (var p in PlayerAgent.All)
{
if (!p || p.IsOwner) continue;
ulong id = p.OwnerClientId;
var row = UIK.El("tune-row", card);
UIK.Text(p.DisplayName, "t-small t-dark", row, false);
UIK.Btn(Loc.T("KICK"), () => { ts.ServerKick(id, false); CloseModal(modal); }, "btn btn-white btn-small", row);
UIK.Btn(Loc.T("BAN"), () => Confirm(Loc.T("Ban this player?"), Loc.F("{0} won't get back into this save.", p.DisplayName), () => { ts.ServerKick(id, true); CloseModal(modal); }), "btn btn-red btn-small", row).style.marginLeft = 8;
}
return card;
});
}
/// <summary>The garage that was opened: machines it sells or calls land on its pad.</summary>
public void OpenGarage(Garage garage, VehicleKind? select = null)
{
if (_garageLayer != null) return;
_garageLayer = OpenModal(layer => new GarageScreen(layer, () => CloseModal(_garageLayer), garage, select).Card);
}
public void OpenShop()
{
if (_shopLayer != null) return;
_shopLayer = OpenModal(layer =>
{
_shop = new ShopScreen(layer, () => CloseModal(_shopLayer));
return _shop.Card;
});
}
VisualElement _mapLayer;
VisualElement _supplyLayer;
public void OpenSupply()
{
if (_supplyLayer != null) return;
_supplyLayer = OpenModal(layer => new SupplyScreen(layer, () => CloseModal(_supplyLayer)).Card);
}
public void OpenMap(float zoom = 1f)
{
if (_mapLayer != null) return;
_mapLayer = OpenModal(layer => new MapScreen(layer, () => CloseModal(_mapLayer), zoom).Card);
}
VisualElement _pieceLayer;
/// <summary>T on something built: its upgrades and switches.</summary>
public void OpenPiece(BuildPiece piece)
{
if (_pieceLayer != null || !piece) return;
_pieceLayer = OpenModal(layer => new PieceScreen(layer, () => CloseModal(_pieceLayer), piece).Card);
}
VisualElement _notebookLayer;
public void OpenNotebook()
{
if (_notebookLayer != null) return;
_notebookLayer = OpenModal(layer => new NotebookScreen(layer, () => CloseModal(_notebookLayer)).Card);
}
}
}