Files
grass-cutters/Assets/Scripts/UI/UIRoot.Settings.cs
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

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

349 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UIElements;
namespace GrassCutter
{
/// <summary>
/// Settings the way a PC game lays them out: a tab per subject (game, display, graphics, audio, controls, keys), one
/// row per setting with its control on the right, what the row does in the footer while the mouse is over it, and a
/// button that puts the tab back as it came.
/// </summary>
public partial class UIRoot
{
VisualElement _settingsLayer;
static int s_settingsTab;
ScrollView _setScroll;
VisualElement _setBody;
Label _setDesc;
string _setDefaultDesc = "";
int _setRow;
readonly List<Button> _setTabs = new List<Button>();
readonly List<Action> _setRefresh = new List<Action>();
class KeyCapture { public Act act; public int slot; public Button button; public float since; }
KeyCapture _capture;
float _captureEnd = -10f;
/// <summary>A key is being captured, or the click that ended one is still coming up: buttons don't act on it.</summary>
bool SetBusy => _capture != null || Time.unscaledTime - _captureEnd < 0.4f;
static readonly string[] SetTabNames = { Loc.N("Game"), Loc.N("Display"), Loc.N("Graphics"), Loc.N("Audio"), Loc.N("Controls"), Loc.N("Key bindings") };
static readonly string KeysHelp = Loc.N("Click a key, then press the new one. Right-click clears it, Esc cancels.");
public void OpenSettings()
{
_capture = null;
_settingsLayer = OpenModal(layer =>
{
var card = UIK.El("card set-card", layer);
card.pickingMode = PickingMode.Position;
UIK.Text(Loc.T("SETTINGS"), "t-h1 t-dark set-title", card);
var tabs = UIK.El("set-tabs", card);
_setTabs.Clear();
for (int i = 0; i < SetTabNames.Length; i++)
{
int t = i;
_setTabs.Add(UIK.Btn(Loc.T(SetTabNames[i]), () => { if (!SetBusy) SettingsTab(t); }, "set-tab", tabs));
}
_setScroll = new ScrollView(ScrollViewMode.Vertical) { horizontalScrollerVisibility = ScrollerVisibility.Hidden };
_setScroll.mouseWheelScrollSize = 120f;
_setScroll.AddToClassList("set-scroll");
card.Add(_setScroll);
_setBody = _setScroll.contentContainer;
var foot = UIK.El("set-foot", card);
UIK.Btn(Loc.T("DEFAULTS"), () =>
{
if (SetBusy) return;
Confirm(Loc.T("Back to defaults?"), Loc.F("Everything on the \"{0}\" tab goes back to how it came.", Loc.T(SetTabNames[s_settingsTab])), () =>
{
GameSettings.Defaults(s_settingsTab);
Hud?.RefreshHints();
SettingsTab(s_settingsTab);
});
}, "btn btn-white btn-small", foot);
_setDesc = UIK.Text("", "set-desc", foot, false);
UIK.Btn(Loc.T("DONE"), () => { if (!SetBusy) CloseModal(layer); }, "btn btn-small", foot);
SettingsTab(s_settingsTab);
return card;
});
}
/// <summary>Show one tab of the open settings (0 game … 5 keys).</summary>
public void SettingsTab(int tab)
{
if (_setBody == null) return;
s_settingsTab = Mathf.Clamp(tab, 0, SetTabNames.Length - 1);
for (int i = 0; i < _setTabs.Count; i++) _setTabs[i].EnableInClassList("set-tab-on", i == s_settingsTab);
_setBody.Clear();
_setRefresh.Clear();
_setRow = 0;
_setDefaultDesc = s_settingsTab == 5 ? Loc.T(KeysHelp) : "";
_setDesc.text = _setDefaultDesc;
switch (s_settingsTab)
{
case 0: GameTab(); break;
case 1: DisplayTab(); break;
case 2: GraphicsTab(); break;
case 3: AudioTab(); break;
case 4: ControlsTab(); break;
default: KeysTab(); break;
}
_setScroll.scrollOffset = Vector2.zero;
}
/// <summary>The open tab scrolled to its end (the bots' shots of the long keys list).</summary>
internal void SettingsScrollEnd()
{
if (_setScroll != null) _setScroll.verticalScroller.value = _setScroll.verticalScroller.highValue;
}
void RefreshRows()
{
foreach (var r in _setRefresh) r();
}
// ───────────────────────── tabs ─────────────────────────
void GameTab()
{
var lang = SetRow(Loc.T("Language"), Loc.T("The language of the menus, captions and tips."));
var b = UIK.Btn(Loc.Current.native, () => { if (!SetBusy) OpenLanguages(); }, "sel-wide", lang);
SetLangFont(b, Loc.Current);
SetSlider(Loc.T("Screen shake"), Loc.T("How hard the camera shakes on bumps, hits and blasts."), 0f, 1.5f, () => GameSettings.Shake, v => GameSettings.Shake = v, UIK.Pct);
SetToggle(Loc.T("Assistant tips"), Loc.T("The assistant pops up on screen when there's something new to learn."), () => GameSettings.Tips, v => GameSettings.Tips = v);
SetToggle(Loc.T("Key hints"), Loc.T("The keys down the right side of the screen."), () => GameSettings.KeyHints, v => { GameSettings.KeyHints = v; Hud?.RefreshHints(); });
if (!_inGame)
{
var row = SetRow(Loc.T("Progress"), Loc.T("Your base, cash, tools and upgrades will be wiped."));
UIK.Btn(Loc.T("RESET PROGRESS"), () =>
{
if (SetBusy) return;
Confirm(Loc.T("Reset progress?"), Loc.T("Your base, cash, tools and upgrades will be wiped."), () => { TeamState.DeleteSave(); Hud.Toast(Loc.T("Progress reset"), Hud.ToastKind.Warn); });
}, "btn btn-red btn-small set-danger", row);
}
}
void DisplayTab()
{
SetChoice(Loc.T("Display mode"), Loc.T("Fullscreen is the fastest. A borderless window lets you switch to other programs at once."),
new[] { Loc.T("Fullscreen"), Loc.T("Borderless window"), Loc.T("Window") }, () => GameSettings.DisplayMode, v => GameSettings.DisplayMode = v);
var sizes = GameSettings.Resolutions();
var names = new string[sizes.Count];
for (int i = 0; i < sizes.Count; i++) names[i] = sizes[i].x + " × " + sizes[i].y;
SetChoice(Loc.T("Resolution"), Loc.T("The size of the picture in fullscreen and in a window. A borderless window always takes the desktop's."),
names, () =>
{
var r = GameSettings.Resolution;
if (r.x <= 0) r = new Vector2Int(Display.main.systemWidth, Display.main.systemHeight);
int i = sizes.IndexOf(r);
return i >= 0 ? i : sizes.IndexOf(new Vector2Int(Screen.width, Screen.height));
}, v => GameSettings.Resolution = sizes[v]);
SetToggle(Loc.T("V-Sync"), Loc.T("Draws in step with the monitor, so the picture never tears. Adds a little delay to the mouse."), () => GameSettings.VSync, v => { GameSettings.VSync = v; RefreshRows(); });
var caps = new string[GameSettings.FpsCaps.Length];
for (int i = 0; i < caps.Length; i++) caps[i] = GameSettings.FpsCaps[i] > 0 ? GameSettings.FpsCaps[i].ToString() : Loc.T("No limit");
SetChoice(Loc.T("Frame rate limit"), Loc.T("The most frames a second with V-Sync off. A lower limit keeps the computer cooler and quieter."),
caps, () => GameSettings.FpsCap, v => GameSettings.FpsCap = v);
SetSlider(Loc.T("Field of view"), Loc.T("How wide you see. Wider shows more, and everything looks further away."), 60, 100, () => GameSettings.Fov, v => GameSettings.Fov = Mathf.Round(v), v => Mathf.RoundToInt(v) + "°");
SetSlider(Loc.T("Brightness"), Loc.T("Lighter or darker than the planet's own light."), -1f, 1f, () => GameSettings.Brightness, v => GameSettings.Brightness = Mathf.Round(v * 20f) / 20f, v => Loc.Num(v, "+0.00;-0.00;0"));
}
void GraphicsTab()
{
SetChoice(Loc.T("Quality"), Loc.T("Sets every row below at once. Change any of them and it becomes your own mix."),
new[] { Loc.T("Low"), Loc.T("Medium"), Loc.T("High"), Loc.T("Ultra"), Loc.T("Own") }, () => GameSettings.Quality, v => { GameSettings.Quality = v; RefreshRows(); });
SetSlider(Loc.T("Render scale"), Loc.T("Draws the world smaller and scales it up. Lower runs faster but looks softer; the interface stays sharp."),
0.5f, 1f, () => GameSettings.RenderScale, v => { GameSettings.RenderScale = Mathf.Round(v * 20f) / 20f; RefreshRows(); }, UIK.Pct);
SetChoice(Loc.T("Shadows"), Loc.T("How far shadows reach and how sharp they are. One of the heaviest settings."),
new[] { Loc.T("Off"), Loc.T("Low"), Loc.T("Medium"), Loc.T("High"), Loc.T("Ultra") }, () => GameSettings.Shadows, v => { GameSettings.Shadows = v; RefreshRows(); });
SetChoice(Loc.T("Anti-aliasing"), Loc.T("Smooths jagged edges (MSAA). Each step costs the graphics card more."),
new[] { Loc.T("Off"), "2×", "4×", "8×" }, () => GameSettings.Antialias, v => { GameSettings.Antialias = v; RefreshRows(); });
SetChoice(Loc.T("Grass density"), Loc.T("How many blades are drawn. There is just as much to cut either way."),
new[] { Loc.T("Low"), Loc.T("Medium"), Loc.T("High") }, () => GameSettings.GrassDetail, v => { GameSettings.GrassDetail = v; RefreshRows(); });
SetToggle(Loc.T("Bloom"), Loc.T("A soft glow around the sun, lamps and anything bright."), () => GameSettings.Bloom, v => { GameSettings.Bloom = v; RefreshRows(); });
}
void AudioTab()
{
SetSlider(Loc.T("Master volume"), Loc.T("Every sound at once."), 0, 1, () => GameSettings.Master, v => GameSettings.Master = v, UIK.Pct);
SetSlider(Loc.T("Music"), Loc.T("The tunes in the menu and on the planet."), 0, 1, () => GameSettings.Music, v => GameSettings.Music = v, UIK.Pct);
SetSlider(Loc.T("Voices"), Loc.T("The Director on the phone and the assistant."), 0, 1, () => GameSettings.Voices, v => GameSettings.Voices = v, UIK.Pct);
SetSlider(Loc.T("Effects"), Loc.T("Machines, tools, grass and the interface."), 0, 1, () => GameSettings.Effects, v => { GameSettings.Effects = v; Sfx.Play("gulp", 0.6f, 1f, 0.1f, 0.12f); }, UIK.Pct);
SetSlider(Loc.T("Phone"), Loc.T("The phone: its ring, its apps and its videos."), 0, 1, () => GameSettings.PhoneVolume, v => GameSettings.PhoneVolume = v, UIK.Pct);
SetToggle(Loc.T("Sound in the background"), Loc.T("Keep playing sound while another window is in front of the game."), () => GameSettings.BackgroundSound, v => GameSettings.BackgroundSound = v);
}
void ControlsTab()
{
SetSlider(Loc.T("Mouse sensitivity"), Loc.T("How far the view turns as the mouse moves."), 0.2f, 3f, () => GameSettings.Sensitivity, v => GameSettings.Sensitivity = v, v => Loc.Num(v, "0.00"));
SetSlider(Loc.T("Gamepad sensitivity"), Loc.T("How fast the right stick turns the view."), 0.2f, 3f, () => GameSettings.PadSensitivity, v => GameSettings.PadSensitivity = v, v => Loc.Num(v, "0.00"));
SetToggle(Loc.T("Invert mouse Y"), Loc.T("Mouse forward looks down, like the stick of a plane."), () => GameSettings.InvertY, v => GameSettings.InvertY = v);
SetChoice(Loc.T("Run"), Loc.T("Hold the key to run, or press it once and run until you stop."),
new[] { Loc.T("Hold"), Loc.T("Press once") }, () => GameSettings.SprintToggle ? 1 : 0, v => GameSettings.SprintToggle = v == 1);
}
void KeysTab()
{
var cols = UIK.El("set-cols", _setBody);
UIK.Text(Loc.T("Main"), "set-colname", cols, false);
UIK.Text(Loc.T("Spare"), "set-colname", cols, false);
foreach (var g in Binds.Groups)
{
UIK.Text(Loc.T(g.title), "set-head", _setBody, false);
_setRow = 0;
foreach (var a in g.acts)
{
var ctl = SetRow(Binds.Name(a), Loc.T(KeysHelp));
for (int s = 0; s < 2; s++) KeyButton(ctl, a, s);
}
}
}
// ───────────────────────── rows ─────────────────────────
/// <summary>A row: the setting's name on the left, the returned box for its control on the right.</summary>
VisualElement SetRow(string label, string desc)
{
var row = UIK.El("set-row", _setBody);
if ((_setRow++ & 1) == 1) row.AddToClassList("set-row-alt");
row.pickingMode = PickingMode.Position;
UIK.Text(label, "set-label", row, false);
var ctl = UIK.El("set-ctl", row);
row.RegisterCallback<PointerEnterEvent>(_ => { if (_capture == null) _setDesc.text = desc; });
row.RegisterCallback<PointerLeaveEvent>(_ => { if (_capture == null) _setDesc.text = _setDefaultDesc; });
return ctl;
}
/// <summary>‹ value › : the arrows step through the options (round and round); a click on the value steps on.</summary>
void SetChoice(string label, string desc, string[] options, Func<int> get, Action<int> set)
{
var ctl = SetRow(label, desc);
int n = options.Length;
var val = UIK.Text("", "sel-value", ctl, false);
void Show() { int i = get(); val.text = i >= 0 && i < n ? options[i] : "—"; }
void Step(int d)
{
if (SetBusy || n == 0) return;
int i = get();
set(((i < 0 ? 0 : i) + d + n) % n);
Show();
}
var prev = Arrow(true, () => Step(-1));
var next = Arrow(false, () => Step(1));
ctl.Insert(0, prev);
ctl.Add(next);
val.pickingMode = PickingMode.Position;
val.RegisterCallback<ClickEvent>(_ => { Sfx.Play("ui_click", 0.8f, 1f, 0.04f); Step(1); });
_setRefresh.Add(Show);
Show();
}
void SetToggle(string label, string desc, Func<bool> get, Action<bool> set) =>
SetChoice(label, desc, new[] { Loc.T("Off"), Loc.T("On") }, () => get() ? 1 : 0, v => set(v == 1));
void SetSlider(string label, string desc, float min, float max, Func<float> get, Action<float> set, Func<float, string> fmt)
{
var ctl = SetRow(label, desc);
var show = UIK.Slider(ctl, "", get(), min, max, fmt, v => { if (_capture == null) set(v); });
var inner = ctl[ctl.childCount - 1];
inner.AddToClassList("set-slider");
inner[0].style.display = DisplayStyle.None;
_setRefresh.Add(() => show(get()));
}
Button Arrow(bool left, Action click)
{
var b = UIK.Btn("", click, "sel-arrow");
b.generateVisualContent += ctx =>
{
var r = b.contentRect;
var p = ctx.painter2D;
float cx = r.center.x, cy = r.center.y, s = 8f, d = left ? 1f : -1f;
p.strokeColor = new Color32(0x2A, 0x21, 0x14, 0xFF);
p.lineWidth = 4f;
p.lineCap = LineCap.Round;
p.lineJoin = LineJoin.Round;
p.BeginPath();
p.MoveTo(new Vector2(cx + d * s * 0.5f, cy - s));
p.LineTo(new Vector2(cx - d * s * 0.5f, cy));
p.LineTo(new Vector2(cx + d * s * 0.5f, cy + s));
p.Stroke();
};
return b;
}
// ───────────────────────── keys ─────────────────────────
void KeyButton(VisualElement ctl, Act a, int slot)
{
Button b = null;
b = UIK.Btn("", () =>
{
if (SetBusy) return;
_capture = new KeyCapture { act = a, slot = slot, button = b, since = Time.unscaledTime };
b.AddToClassList("key-wait");
b.text = Loc.T("Press a key…");
_setDesc.text = Loc.F("{0}: press a key or a mouse button. Esc cancels.", Binds.Name(a));
}, "key-btn", ctl);
UIK.SetFont(b, false);
b.RegisterCallback<PointerDownEvent>(e =>
{
if (e.button != 1 || SetBusy) return;
Binds.Set(a, slot, 0);
Sfx.Play("ui_click", 0.6f, 0.9f);
AfterKeys();
});
void Show() { b.text = Binds.KeyName(Binds.Get(a, slot)); b.EnableInClassList("key-empty", Binds.Get(a, slot) == 0); }
_setRefresh.Add(Show);
Show();
}
/// <summary>Runs every frame while a key is being captured (instead of Esc closing the window).</summary>
void PollCapture()
{
var c = _capture;
if (_settingsLayer == null || !_modalStack.Contains(_settingsLayer) || c.button.panel == null) { EndCapture(); return; }
var k = Keyboard.current;
if (k != null && k.escapeKey.wasPressedThisFrame) { EndCapture(); _setDesc.text = _setDefaultDesc; return; }
if (Time.unscaledTime - c.since < 0.15f) return;
int code = Binds.Pressed();
if (code == 0) return;
Binds.Set(c.act, c.slot, code);
Sfx.Play("ui_click", 0.8f, 1.1f);
EndCapture();
// the same key elsewhere is allowed (the defaults share some), but the player hears about it
var also = new List<string>();
for (int i = 0; i < Binds.Count; i++)
if ((Act)i != c.act && (Binds.Get((Act)i, 0) == code || Binds.Get((Act)i, 1) == code)) also.Add(Binds.Name((Act)i));
_setDesc.text = also.Count > 0 ? Loc.F("{0} also does: {1}", Binds.KeyName(code), string.Join(", ", also)) : _setDefaultDesc;
}
void EndCapture()
{
if (_capture != null) _capture.button.RemoveFromClassList("key-wait");
_capture = null;
_captureEnd = Time.unscaledTime;
AfterKeys();
}
void AfterKeys()
{
RefreshRows();
Hud?.RefreshHints();
}
// ───────────────────────── language ─────────────────────────
/// <summary>Each language written in itself, so each button needs the font that has its letters.</summary>
static void SetLangFont(VisualElement e, Loc.Lang l)
{
Font f = null;
var bank = AssetBank.I;
if (l.cjkFont != null) foreach (var x in bank.fonts) if (x && x.name.Contains(l.cjkFont)) f = x;
if (!f && l.latinDisplayOnly) f = bank.Font("Nunito-Black");
if (f) e.style.unityFontDefinition = FontDefinition.FromFont(f);
}
}
}