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>
This commit is contained in:
257
Assets/Scripts/UI/Assistant.cs
Normal file
257
Assets/Scripts/UI/Assistant.cs
Normal file
@ -0,0 +1,257 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The Director's assistant, in your ear the whole game: she says the hints out loud (what to do next, the weather
|
||||
/// coming, a twister, the saucer, a full container, no money) from a little video window at the side of the view,
|
||||
/// talking the same South Park way he does. She waits while he's on the phone or a film is playing, says nothing stale,
|
||||
/// and doesn't nag: each line has its own rest before it may come again.
|
||||
/// </summary>
|
||||
public class Assistant : MonoBehaviour
|
||||
{
|
||||
public static Assistant I { get; private set; }
|
||||
/// <summary>She's talking.</summary>
|
||||
public static bool Busy => I && I._on;
|
||||
|
||||
// the words as recorded; the caption is the same with the tags taken out
|
||||
static readonly Dictionary<string, string> Lines = new Dictionary<string, string>
|
||||
{
|
||||
["asst_hello"] = "[deadpan] Hi. I'm the Director's assistant. I'll be in your ear the whole time. [pause] He shouts. I explain.",
|
||||
["asst_tools"] = "Your hands are empty. Walk to the supply wall on the west side of the deck and take the nail scissors. Press E.",
|
||||
["asst_mow"] = "Hop down to the meadow, space at the railing. Then hold left click and sweep the blade over the grass. [deadpan] Every blade counts. Apparently.",
|
||||
["asst_full"] = "Your container's full. Press E at the depot to hand it all in. Or Q to tie a bundle you can carry and throw.",
|
||||
["asst_spend"] = "You've got cash. Better tools at the supply wall, upgrades at the console. Mowers come from a garage. [pause] Build one with the hammer.",
|
||||
["asst_nocash"] = "[sighs] Not enough money. Mow more.",
|
||||
["asst_drive"] = "W A S D to drive. Shift to boost. R for the chase view. E to hop off.",
|
||||
["asst_hopper"] = "That machine's hopper is full. Unload it at the base yard or a garage pad.",
|
||||
["asst_rain"] = "Rain's coming. The solar panels will give less for a while.",
|
||||
["asst_acid"] = "[concerned] Acid rain. It burns patches of the meadow. That grass is gone, and it pays nothing.",
|
||||
["asst_wind"] = "The wind is picking up. Keep an eye out for twisters.",
|
||||
["asst_storm"] = "Thunderstorm. Dark skies, weak sun, and twisters about. [pause] Stay sharp.",
|
||||
["asst_meteors"] = "[softly] Meteor shower tonight. Look up. [pause] It's actually pretty.",
|
||||
["asst_twister"] = "[alarmed] Twister incoming! It rips up the grass in its path and it will throw you around!",
|
||||
["asst_thrown"] = "[deadpan] You got thrown by a twister. [pause] Noted.",
|
||||
["asst_ufo"] = "[nervous] Something is coming down out of the sky. [pause] I'm sure it's fine.",
|
||||
};
|
||||
|
||||
// how long before a line may be said again, seconds (the rest: three minutes)
|
||||
static readonly Dictionary<string, float> Rest = new Dictionary<string, float>
|
||||
{
|
||||
["asst_hello"] = 1e9f, ["asst_drive"] = 1e9f, ["asst_nocash"] = 60f, ["asst_thrown"] = 90f, ["asst_full"] = 240f, ["asst_hopper"] = 240f,
|
||||
};
|
||||
const float StaleAfter = 25f;
|
||||
const int PicW = 300, PicH = 380;
|
||||
|
||||
readonly Queue<(string line, float at)> _queue = new Queue<(string, float)>();
|
||||
readonly Dictionary<string, float> _said = new Dictionary<string, float>();
|
||||
readonly float[] _mood = new float[7];
|
||||
AudioSource _voice;
|
||||
VisualElement _panel, _picture;
|
||||
Label _caption;
|
||||
Booth _booth;
|
||||
// the user's filmed loops of her, one per mood
|
||||
TalkVideo _talk;
|
||||
bool _on;
|
||||
float _open, _openVel;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
I = this;
|
||||
_voice = gameObject.AddComponent<AudioSource>();
|
||||
_voice.playOnAwake = false;
|
||||
_voice.spatialBlend = 0f;
|
||||
_voice.priority = 0;
|
||||
}
|
||||
|
||||
/// <summary>She says this line when she can (unless she said it lately).</summary>
|
||||
public static void Say(string line)
|
||||
{
|
||||
if (!I || !Lines.ContainsKey(line) || !GameSettings.Tips) return;
|
||||
if (I._said.TryGetValue(line, out var at) && Time.time - at < (Rest.TryGetValue(line, out var r) ? r : 180f)) return;
|
||||
foreach (var q in I._queue) if (q.line == line) return;
|
||||
// the greeting goes first, whatever was asked before it
|
||||
if (line == "asst_hello" && I._queue.Count > 0)
|
||||
{
|
||||
var rest = I._queue.ToArray();
|
||||
I._queue.Clear();
|
||||
I._queue.Enqueue((line, Time.time));
|
||||
foreach (var q in rest) I._queue.Enqueue(q);
|
||||
return;
|
||||
}
|
||||
I._queue.Enqueue((line, Time.time));
|
||||
}
|
||||
|
||||
/// <summary>The trailer: she may say anything again.</summary>
|
||||
public static void Forget()
|
||||
{
|
||||
if (I) I._said.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Stops her mid-sentence (the game is ending, a film starts).</summary>
|
||||
public static void Hush()
|
||||
{
|
||||
if (!I) return;
|
||||
I.StopAllCoroutines();
|
||||
I._voice.Stop();
|
||||
I._queue.Clear();
|
||||
I.Panel(false);
|
||||
I._on = false;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
// she lives on the cinema layer, above the windows: a window opened mid-line hides her till it closes
|
||||
if (_panel != null) _panel.style.visibility = UIRoot.I && UIRoot.I.AnyModal ? Visibility.Hidden : Visibility.Visible;
|
||||
if (_on || _queue.Count == 0) return;
|
||||
if (!Ready()) return;
|
||||
var (line, at) = _queue.Dequeue();
|
||||
// what's no longer news isn't said
|
||||
if (Time.time - at > StaleAfter) return;
|
||||
_said[line] = Time.time;
|
||||
StartCoroutine(Talk(line));
|
||||
}
|
||||
|
||||
static bool Ready()
|
||||
{
|
||||
var me = PlayerAgent.Local;
|
||||
return me && me.IsSpawned && IntroCinematic.Settled && !IntroCinematic.Running && !Ctl.Cinematic && !Ctl.UIOpen && !DirectorCall.Busy && UIRoot.I;
|
||||
}
|
||||
|
||||
IEnumerator Talk(string line)
|
||||
{
|
||||
_on = true;
|
||||
Panel(true);
|
||||
var clip = AssetBank.I.Clip(line);
|
||||
var words = DirectorCall.Captions(Lines[line]);
|
||||
var moods = DirectorCall.Moods(Lines[line]);
|
||||
var env = clip ? DirectorCall.Envelope(clip) : null;
|
||||
Sfx.Play("call_connect", 0.25f, 1.4f, 0f);
|
||||
yield return new WaitForSeconds(0.25f);
|
||||
if (clip)
|
||||
{
|
||||
_voice.clip = clip;
|
||||
_voice.volume = DirectorCall.VoiceGain(env);
|
||||
_voice.Play();
|
||||
Sfx.Heard?.Invoke(clip.name, 1f, 1f, null);
|
||||
}
|
||||
float length = clip ? clip.length : 3f, t = 0f;
|
||||
for (int i = 0; i < _mood.Length; i++) _mood[i] = 0f;
|
||||
while (t < length)
|
||||
{
|
||||
// the Director cuts in: she stops
|
||||
if (DirectorCall.Busy || Ctl.Cinematic) break;
|
||||
Sfx.Duck(0.6f);
|
||||
_voice.volume = DirectorCall.VoiceGain(env);
|
||||
float said = 0f, target = 0f;
|
||||
if (env != null && env.level.Length > 0)
|
||||
{
|
||||
int f = Mathf.Clamp((int)(t * DirectorCall.EnvRate), 0, env.level.Length - 1);
|
||||
target = env.level[f];
|
||||
said = env.said[f];
|
||||
}
|
||||
_open = Mathf.SmoothDamp(_open, target, ref _openVel, target > _open ? 0.035f : 0.07f);
|
||||
var mood = DirectorCall.MoodAt(moods, said);
|
||||
float dt = Time.deltaTime;
|
||||
for (int i = 0; i < _mood.Length; i++) _mood[i] = Mathf.MoveTowards(_mood[i], i == (int)mood ? 1f : 0f, dt * 3f);
|
||||
_booth?.Puppet?.Tick(t, _open, _mood);
|
||||
_talk?.Play(TalkVideo.AssistantMood(TalkVideo.Strongest(_mood)));
|
||||
if (_caption != null) _caption.text = DirectorCall.CaptionAt(words, said);
|
||||
t += dt;
|
||||
yield return null;
|
||||
}
|
||||
_voice.Stop();
|
||||
Sfx.Duck(1f);
|
||||
// a breath with the mouth shut before the window goes
|
||||
float shut = 0f;
|
||||
while (shut < 0.5f)
|
||||
{
|
||||
_open = Mathf.SmoothDamp(_open, 0f, ref _openVel, 0.07f);
|
||||
_booth?.Puppet?.Tick(t + shut, _open, _mood);
|
||||
shut += Time.deltaTime;
|
||||
yield return null;
|
||||
}
|
||||
Panel(false);
|
||||
_on = false;
|
||||
}
|
||||
|
||||
/// <summary>The video window: her picture, her name, and what she's saying beside it.</summary>
|
||||
void Panel(bool on)
|
||||
{
|
||||
if (on && (_panel == null || _panel.panel == null)) Build();
|
||||
if (_panel == null) return;
|
||||
_booth?.Show(on);
|
||||
if (on) _talk?.Play(0);
|
||||
else _talk?.Stop();
|
||||
if (on)
|
||||
{
|
||||
_panel.style.display = DisplayStyle.Flex;
|
||||
_panel.BringToFront();
|
||||
UIK.PopIn(_panel, 0f, 0.25f);
|
||||
}
|
||||
else _panel.style.display = DisplayStyle.None;
|
||||
}
|
||||
|
||||
void Build()
|
||||
{
|
||||
var root = UIRoot.I ? UIRoot.I.Cinema : null;
|
||||
if (root == null) return;
|
||||
_talk = new TalkVideo("asst", new[] { "happy", "stern", "fed" }, 400, 406);
|
||||
_panel = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
_panel.style.position = Position.Absolute;
|
||||
_panel.style.left = 22;
|
||||
_panel.style.bottom = 235;
|
||||
_panel.style.flexDirection = FlexDirection.Row;
|
||||
_panel.style.alignItems = Align.FlexEnd;
|
||||
root.Add(_panel);
|
||||
|
||||
var frame = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
frame.style.width = PicW * 0.8f;
|
||||
frame.style.height = PicH * 0.8f;
|
||||
frame.style.borderTopLeftRadius = frame.style.borderTopRightRadius = frame.style.borderBottomLeftRadius = frame.style.borderBottomRightRadius = 14;
|
||||
frame.style.borderLeftWidth = frame.style.borderRightWidth = frame.style.borderTopWidth = frame.style.borderBottomWidth = 3;
|
||||
var edge = new Color(0.55f, 0.85f, 0.95f, 0.9f);
|
||||
frame.style.borderLeftColor = frame.style.borderRightColor = frame.style.borderTopColor = frame.style.borderBottomColor = edge;
|
||||
frame.style.overflow = Overflow.Hidden;
|
||||
frame.style.backgroundColor = new Color(0.08f, 0.12f, 0.22f);
|
||||
var bg = AssetBank.I ? AssetBank.I.Tex("T_Dir_Bg") : null;
|
||||
if (bg)
|
||||
{
|
||||
frame.style.backgroundImage = new StyleBackground(bg);
|
||||
frame.style.unityBackgroundScaleMode = ScaleMode.ScaleAndCrop;
|
||||
frame.style.unityBackgroundImageTintColor = new Color(0.82f, 0.86f, 0.95f);
|
||||
}
|
||||
_panel.Add(frame);
|
||||
_picture = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
_picture.style.flexGrow = 1;
|
||||
_picture.style.unityBackgroundScaleMode = ScaleMode.ScaleAndCrop;
|
||||
_talk.Switched = rt => _picture.style.backgroundImage = new StyleBackground(Background.FromRenderTexture(rt));
|
||||
_talk.Switched(_talk.Rt);
|
||||
frame.Add(_picture);
|
||||
var tag = UIK.Text(Loc.T("ASSISTANT · G.R.A.S.S.A."), "", frame, true);
|
||||
tag.style.position = Position.Absolute;
|
||||
tag.style.left = 0; tag.style.right = 0; tag.style.bottom = 0;
|
||||
tag.style.fontSize = 11;
|
||||
tag.style.unityTextAlign = TextAnchor.MiddleCenter;
|
||||
tag.style.color = new Color(0.86f, 0.95f, 1f);
|
||||
tag.style.backgroundColor = new Color(0.02f, 0.05f, 0.12f, 0.75f);
|
||||
tag.style.paddingTop = tag.style.paddingBottom = 3;
|
||||
|
||||
_caption = UIK.Text("", "", _panel, false);
|
||||
_caption.style.maxWidth = 420;
|
||||
_caption.style.marginLeft = 10;
|
||||
_caption.style.marginBottom = 8;
|
||||
_caption.style.fontSize = 19;
|
||||
_caption.style.whiteSpace = WhiteSpace.Normal;
|
||||
_caption.style.color = Color.white;
|
||||
_caption.style.backgroundColor = new Color(0.02f, 0.05f, 0.12f, 0.78f);
|
||||
_caption.style.paddingLeft = _caption.style.paddingRight = 12;
|
||||
_caption.style.paddingTop = _caption.style.paddingBottom = 8;
|
||||
_caption.style.borderTopLeftRadius = _caption.style.borderTopRightRadius = _caption.style.borderBottomRightRadius = 12;
|
||||
_panel.style.display = DisplayStyle.None;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/Assistant.cs.meta
Normal file
2
Assets/Scripts/UI/Assistant.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7bb9e5fc663b11d4fa4ca2fa530fa4b1
|
||||
157
Assets/Scripts/UI/CheatConsole.cs
Normal file
157
Assets/Scripts/UI/CheatConsole.cs
Normal file
@ -0,0 +1,157 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Drop-down cheat console (~ / Ё / F1). Enter runs a line, Tab completes, ↑↓ walk the history, ~ or Esc closes.
|
||||
/// The log and the history survive closing it.
|
||||
/// </summary>
|
||||
public class CheatConsole
|
||||
{
|
||||
static readonly List<string> s_log = new List<string>();
|
||||
static readonly List<string> s_history = new List<string>();
|
||||
const int MaxLog = 200;
|
||||
public static IReadOnlyList<string> Log => s_log;
|
||||
|
||||
public readonly VisualElement Panel;
|
||||
readonly ScrollView _scroll;
|
||||
readonly TextField _input;
|
||||
readonly Label _hint;
|
||||
int _historyAt;
|
||||
|
||||
public CheatConsole(VisualElement layer)
|
||||
{
|
||||
layer.style.justifyContent = Justify.FlexStart;
|
||||
Panel = UIK.El("console", layer);
|
||||
Panel.pickingMode = PickingMode.Position;
|
||||
var head = UIK.El("console-head", Panel);
|
||||
UIK.Text("CHEAT CONSOLE", "console-title", head);
|
||||
UIK.Text("help · Tab completes · ↑↓ history · ~ closes", "console-sub", head, false);
|
||||
_scroll = new ScrollView(ScrollViewMode.Vertical);
|
||||
_scroll.AddToClassList("console-log");
|
||||
_scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
|
||||
Panel.Add(_scroll);
|
||||
|
||||
var row = UIK.El("console-row", Panel);
|
||||
UIK.Text(">", "console-prompt", row);
|
||||
_input = new TextField();
|
||||
_input.AddToClassList("console-input");
|
||||
UIK.SetFont(_input, false);
|
||||
row.Add(_input);
|
||||
_hint = UIK.Text("", "console-hint", Panel, false);
|
||||
|
||||
if (s_log.Count == 0) Print("Type <b>help</b> for the list of cheats. Most of them only work for the host.");
|
||||
foreach (var l in s_log) AddLine(l);
|
||||
|
||||
_input.RegisterCallback<KeyDownEvent>(OnKey, TrickleDown.TrickleDown);
|
||||
// Tab would move focus away: keep it in the field
|
||||
_input.RegisterCallback<NavigationMoveEvent>(e => e.StopPropagation(), TrickleDown.TrickleDown);
|
||||
_input.RegisterValueChangedCallback(e =>
|
||||
{
|
||||
// the toggle key types itself into the field on the way in/out
|
||||
string clean = e.newValue.Replace("`", "").Replace("~", "").Replace("ё", "").Replace("Ё", "");
|
||||
if (clean != e.newValue) _input.SetValueWithoutNotify(clean);
|
||||
UpdateHint(clean);
|
||||
});
|
||||
_historyAt = s_history.Count;
|
||||
Focus();
|
||||
ScrollToEnd();
|
||||
}
|
||||
|
||||
public void Focus() => _input.schedule.Execute(() => { _input.Focus(); _input.SelectRange(_input.value.Length, _input.value.Length); }).ExecuteLater(30);
|
||||
|
||||
void OnKey(KeyDownEvent e)
|
||||
{
|
||||
switch (e.keyCode)
|
||||
{
|
||||
case KeyCode.Return:
|
||||
case KeyCode.KeypadEnter:
|
||||
Submit(_input.value);
|
||||
e.StopImmediatePropagation();
|
||||
Focus();
|
||||
break;
|
||||
case KeyCode.Tab:
|
||||
{
|
||||
var done = Cheats.Complete(_input.value, out var options);
|
||||
_input.SetValueWithoutNotify(done);
|
||||
_input.SelectRange(done.Length, done.Length);
|
||||
_hint.text = options.Count > 1 ? string.Join(" ", options) : "";
|
||||
e.StopImmediatePropagation();
|
||||
Focus();
|
||||
break;
|
||||
}
|
||||
case KeyCode.UpArrow:
|
||||
if (s_history.Count == 0) break;
|
||||
_historyAt = Mathf.Max(0, _historyAt - 1);
|
||||
SetInput(s_history[_historyAt]);
|
||||
e.StopImmediatePropagation();
|
||||
break;
|
||||
case KeyCode.DownArrow:
|
||||
if (s_history.Count == 0) break;
|
||||
_historyAt = Mathf.Min(s_history.Count, _historyAt + 1);
|
||||
SetInput(_historyAt < s_history.Count ? s_history[_historyAt] : "");
|
||||
e.StopImmediatePropagation();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void SetInput(string s)
|
||||
{
|
||||
_input.SetValueWithoutNotify(s);
|
||||
_input.SelectRange(s.Length, s.Length);
|
||||
UpdateHint(s);
|
||||
}
|
||||
|
||||
void UpdateHint(string line)
|
||||
{
|
||||
var parts = line.Trim().Split(' ');
|
||||
var cmd = parts.Length > 0 ? Cheats.All.Find(c => c.name == parts[0].ToLowerInvariant()) : null;
|
||||
_hint.text = cmd != null ? $"{cmd.name} {cmd.args} — {cmd.desc}" : "";
|
||||
}
|
||||
|
||||
/// <summary>Put text in the input line, as if typed (demo bot).</summary>
|
||||
public void Type(string s) => _input.value = s;
|
||||
|
||||
/// <summary>Run a line as if typed (also used by the demo bot).</summary>
|
||||
public void Submit(string line)
|
||||
{
|
||||
line = (line ?? "").Trim();
|
||||
_input.SetValueWithoutNotify("");
|
||||
_hint.text = "";
|
||||
if (line.Length == 0) return;
|
||||
if (s_history.Count == 0 || s_history[s_history.Count - 1] != line) s_history.Add(line);
|
||||
_historyAt = s_history.Count;
|
||||
Print($"<color=#FFD23F>> {line}</color>");
|
||||
string name = line.Split(' ')[0].ToLowerInvariant();
|
||||
if (name == "clear")
|
||||
{
|
||||
s_log.Clear();
|
||||
_scroll.Clear();
|
||||
return;
|
||||
}
|
||||
string result = Cheats.Run(line);
|
||||
if (!string.IsNullOrEmpty(result)) Print(result);
|
||||
Sfx.Play(result != null && result.Contains("#FF8A7A") ? "error" : "ui_click", 0.5f);
|
||||
}
|
||||
|
||||
void Print(string text)
|
||||
{
|
||||
s_log.Add(text);
|
||||
if (s_log.Count > MaxLog) s_log.RemoveAt(0);
|
||||
AddLine(text);
|
||||
ScrollToEnd();
|
||||
}
|
||||
|
||||
void AddLine(string text)
|
||||
{
|
||||
var l = UIK.Text(text, "console-line", null, false);
|
||||
l.enableRichText = true;
|
||||
_scroll.Add(l);
|
||||
while (_scroll.contentContainer.childCount > MaxLog) _scroll.contentContainer.RemoveAt(0);
|
||||
}
|
||||
|
||||
void ScrollToEnd() => _scroll.schedule.Execute(() => _scroll.scrollOffset = new Vector2(0, float.MaxValue)).ExecuteLater(20);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/CheatConsole.cs.meta
Normal file
2
Assets/Scripts/UI/CheatConsole.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f90bb7cd1c1f06542a2c314ec0bb268a
|
||||
75
Assets/Scripts/UI/Compass.cs
Normal file
75
Assets/Scripts/UI/Compass.cs
Normal file
@ -0,0 +1,75 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The strip across the top of the screen: the eight points turn with your view, and the places worth finding your way
|
||||
/// back to sit on it with their distance along the ground. North is always the pole, and that is where the base stands.
|
||||
/// </summary>
|
||||
public class Compass
|
||||
{
|
||||
const float Width = 640f, Span = 130f;
|
||||
static readonly string[] Names = { Loc.N("N"), Loc.N("NE"), Loc.N("E"), Loc.N("SE"), Loc.N("S"), Loc.N("SW"), Loc.N("W"), Loc.N("NW") };
|
||||
|
||||
class Pin { public string name; public Vector3 dir; public Label label; public int station; }
|
||||
|
||||
readonly VisualElement _strip;
|
||||
readonly Label[] _points = new Label[8];
|
||||
readonly List<Pin> _pins = new List<Pin>();
|
||||
|
||||
public Compass(VisualElement root)
|
||||
{
|
||||
_strip = UIK.El("compass", root);
|
||||
for (int i = 0; i < 8; i++)
|
||||
_points[i] = UIK.Text(Loc.T(Names[i]), i % 2 == 0 ? "compass-point compass-main t-outline" : "compass-point t-outline", _strip);
|
||||
UIK.El("compass-mid", _strip);
|
||||
AddPin(Loc.T("BASE"), Vector3.up);
|
||||
for (int i = 1; i < Stations.Count; i++) AddPin(Stations.Names[i].ToUpper(Loc.Culture), Stations.Dir(i), i);
|
||||
}
|
||||
|
||||
void AddPin(string name, Vector3 dir, int station = 0) => _pins.Add(new Pin { name = name, dir = dir, station = station, label = UIK.Text("", "compass-pin t-outline", _strip, false) });
|
||||
|
||||
/// <summary>Which way a line on the ground runs, in degrees clockwise from north.</summary>
|
||||
public static float Bearing(Vector3 up, Vector3 along)
|
||||
{
|
||||
var north = Vector3.ProjectOnPlane(Vector3.up, up);
|
||||
if (north.sqrMagnitude < 1e-4f) north = Vector3.ProjectOnPlane(Vector3.forward, up);
|
||||
return Vector3.SignedAngle(north, Vector3.ProjectOnPlane(along, up), up);
|
||||
}
|
||||
|
||||
public static string Distance(float metres) => metres < 1000f ? Loc.F("{0:0} m", metres) : Loc.F("{0:0.0} km", metres / 1000f);
|
||||
|
||||
void Set(VisualElement e, float bearing, float heading)
|
||||
{
|
||||
float off = Mathf.DeltaAngle(heading, bearing);
|
||||
bool on = Mathf.Abs(off) < Span * 0.5f;
|
||||
e.style.display = on ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (on) e.style.left = Width * 0.5f + off / Span * Width;
|
||||
}
|
||||
|
||||
public void Tick(PlayerAgent me, bool show)
|
||||
{
|
||||
_strip.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (!show || !me) return;
|
||||
var up = Planet.Up(me.transform.position);
|
||||
float heading = Bearing(up, me.transform.forward);
|
||||
for (int i = 0; i < 8; i++) Set(_points[i], i * 45f, heading);
|
||||
var ts = TeamState.Instance;
|
||||
foreach (var p in _pins)
|
||||
{
|
||||
if (p.station > 0 && !(ts && ts.StationOpen(p.station)))
|
||||
{
|
||||
p.label.style.display = DisplayStyle.None;
|
||||
continue;
|
||||
}
|
||||
float metres = Mathf.Acos(Mathf.Clamp(Vector3.Dot(up, p.dir), -1f, 1f)) * Planet.Radius;
|
||||
// at the pin itself every bearing is as good as another
|
||||
float bearing = metres < 1f ? heading : Bearing(up, p.dir);
|
||||
p.label.text = p.name + " " + Distance(metres);
|
||||
Set(p.label, bearing, heading);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/Compass.cs.meta
Normal file
2
Assets/Scripts/UI/Compass.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d3867c8b5edc919439b31e6c323aa6eb
|
||||
647
Assets/Scripts/UI/DirectorCall.cs
Normal file
647
Assets/Scripts/UI/DirectorCall.cs
Normal file
@ -0,0 +1,647 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
using Random = UnityEngine.Random;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The Director of G.R.A.S.S.A. (Earth's grass agency, which runs the mission) rings the phone: rarely, at milestones of
|
||||
/// the planet and when something big is unlocked. The phone comes out, he shouts from mission control on Earth with his
|
||||
/// head flapping like a cut-out puppet, the words run along the bottom of the view, and the phone goes back where it was.
|
||||
/// V hangs up early.
|
||||
/// </summary>
|
||||
public class DirectorCall : MonoBehaviour
|
||||
{
|
||||
public static DirectorCall I { get; private set; }
|
||||
/// <summary>A call is ringing or on.</summary>
|
||||
public static bool Busy => I && I._on;
|
||||
|
||||
// the words as recorded (the tags steer the voice); the captions are the same with the tags taken out
|
||||
static readonly Dictionary<string, string> Lines = new Dictionary<string, string>
|
||||
{
|
||||
["dir_intro"] = "[angry] Listen up, you incompetent idiots! [shouting] EARTH IS OUT OF GRASS! NO GRASS! NOT A SINGLE DAMN BLADE! [frustrated] And you morons are standing around doing NOTHING?! [stern] That planet is covered in grass. And Earth needs EVERY. SINGLE. BLADE. [shouting] I want it CUT! I want it PACKED! And I want it SHIPPED BACK TO EARTH! [furious] I don't care if you have to use nail scissors! [shouting] NOW GET OUT THERE AND MOW THAT GODDAMN PLANET!",
|
||||
["dir_intro_tag"] = "[deadpan] This is G.R.A.S.S.A. We take grass very seriously.",
|
||||
["dir_m0001"] = "[suspicious] Wait. Is that... progress? [sniffs] Zero point zero zero one percent. [grudging] Earth thanks you. Barely. [shouting] NOW DO THE OTHER NINETY-NINE POINT NINE NINE NINE!",
|
||||
["dir_m1"] = "[excited] ONE PERCENT! [clears throat] [stern] I mean... one percent. Acceptable. My grandmother mowed faster, and she used her teeth. [shouting] KEEP CUTTING!",
|
||||
["dir_m50"] = "[emotional] Fifty percent. Half a planet. [sniffles] Somewhere on Earth, a cow just smiled for the first time in ten years. [shouting] DON'T YOU DARE STOP NOW!",
|
||||
["dir_m100"] = "[voice breaking] One hundred percent. [pause] You did it. You magnificent idiots actually did it. [sobbing] Earth has grass again! [pause] [stern] Now. About the second planet. [pause] [deadpan] I'm kidding. [pause] Unless?",
|
||||
["dir_machine"] = "[impressed] A machine! Finally, somebody down there with a brain! [shouting] Now put it to work before I bill you for the fuel!",
|
||||
["dir_combine"] = "[shouting] A COMBINE HARVESTER?! [laughs maniacally] NOW we're talking! Earth's lawns will be green by Christmas!",
|
||||
["dir_drones"] = "[suspicious] Drones? You bought DRONES? [pause] [grudging] Fine. But if they start a robot uprising, it's coming out of YOUR pay.",
|
||||
["dir_belts"] = "[delighted] Conveyor belts! Grass that moves BY ITSELF! [whispers] This is what peak civilization looks like.",
|
||||
["dir_ufo"] = "[panicked] Was that a UFO?! [whispers] Listen to me. Do NOT let them take the grass. [shouting] THAT GRASS BELONGS TO EARTH!",
|
||||
};
|
||||
|
||||
// the planet's milestones, as fractions
|
||||
static readonly (double at, string line)[] Milestones = { (0.00001d, "dir_m0001"), (0.01d, "dir_m1"), (0.5d, "dir_m50"), (0.99999d, "dir_m100") };
|
||||
|
||||
readonly Queue<string> _queue = new Queue<string>();
|
||||
AudioSource _voice;
|
||||
PhoneCall _view;
|
||||
Label _caption, _ring;
|
||||
bool _on;
|
||||
float _open, _openVel;
|
||||
|
||||
// what the watcher saw last: a call goes when one of these rises past a line while you're playing
|
||||
bool _seeded;
|
||||
float _seedAt = -1f;
|
||||
double _mown;
|
||||
bool _machine, _combine, _drones, _belts, _ufo;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
I = this;
|
||||
_voice = gameObject.AddComponent<AudioSource>();
|
||||
_voice.playOnAwake = false;
|
||||
_voice.spatialBlend = 0f;
|
||||
_voice.priority = 0;
|
||||
}
|
||||
|
||||
/// <summary>Rings with this line. Calls wait their turn.</summary>
|
||||
/// <summary>The trailer: no calls but the ones it asks for.</summary>
|
||||
public static bool Quiet;
|
||||
|
||||
public static void Call(string line)
|
||||
{
|
||||
if (!I || !Lines.ContainsKey(line) || Quiet) return;
|
||||
if (I._queue.Contains(line)) return;
|
||||
I._queue.Enqueue(line);
|
||||
}
|
||||
|
||||
/// <summary>The opening film plays the call itself: no ring, the phone already up.</summary>
|
||||
public static IEnumerator Speak(string line, bool hangUp)
|
||||
{
|
||||
if (!I) yield break;
|
||||
yield return I.Talk(line, false, hangUp);
|
||||
}
|
||||
|
||||
/// <summary>Cuts a call off where it is (the opening film was skipped).</summary>
|
||||
public static void Abort()
|
||||
{
|
||||
if (!I) return;
|
||||
I.StopAllCoroutines();
|
||||
I._voice.Stop();
|
||||
I.Caption("");
|
||||
if (I._ring != null) I._ring.style.display = DisplayStyle.None;
|
||||
I._view?.Show(false);
|
||||
I._on = false;
|
||||
Sfx.Duck(1f);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
Watch();
|
||||
if (!_on && _queue.Count > 0 && Ready()) StartCoroutine(Ring(_queue.Dequeue()));
|
||||
Mouth();
|
||||
}
|
||||
|
||||
/// <summary>Not over a menu, not inside the opening film, in a game with a body to hold the phone.</summary>
|
||||
static bool Ready()
|
||||
{
|
||||
var me = PlayerAgent.Local;
|
||||
return me && me.IsSpawned && Phone.I && !Ctl.Cinematic && !Ctl.UIOpen;
|
||||
}
|
||||
|
||||
IEnumerator Ring(string line)
|
||||
{
|
||||
_on = true;
|
||||
Caption("");
|
||||
var ring = Ensure(ref _ring, "director-ring t-outline");
|
||||
ring.text = Loc.T("G.R.A.S.S.A. IS CALLING");
|
||||
ring.style.display = DisplayStyle.Flex;
|
||||
UIK.PopIn(ring, 0f, 0.3f);
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
Sfx.Play("phone_ring", 0.5f, 1f, 0f);
|
||||
UIK.Punch(ring, 0.12f);
|
||||
yield return new WaitForSeconds(1.5f);
|
||||
}
|
||||
ring.style.display = DisplayStyle.None;
|
||||
yield return Talk(line, true, true);
|
||||
}
|
||||
|
||||
IEnumerator Talk(string line, bool takeOut, bool hangUp)
|
||||
{
|
||||
_on = true;
|
||||
var phone = Phone.I;
|
||||
var was = phone ? phone.Mode : PhoneMode.Away;
|
||||
if (phone && takeOut && was == PhoneMode.Away) phone.Show(PhoneMode.Side);
|
||||
yield return null;
|
||||
if (phone && phone.Screen != null && phone.Mode != PhoneMode.Away)
|
||||
{
|
||||
if (phone.Screen.Wide) phone.Screen.Turn();
|
||||
_view ??= new PhoneCall(phone.Screen.Root);
|
||||
_view.Show(true);
|
||||
}
|
||||
Sfx.Play("call_connect", 0.6f, 1f, 0f);
|
||||
yield return new WaitForSeconds(0.45f);
|
||||
|
||||
var clip = AssetBank.I.Clip(line);
|
||||
var words = Captions(Lines[line]);
|
||||
var moods = Moods(Lines[line]);
|
||||
if (clip)
|
||||
{
|
||||
_voice.clip = clip;
|
||||
_voice.volume = VoiceGain(Envelope(clip));
|
||||
_voice.Play();
|
||||
Sfx.Heard?.Invoke(clip.name, 1f, 1f, null);
|
||||
}
|
||||
float length = clip ? clip.length : 4f, t = 0f;
|
||||
bool hungUp = false;
|
||||
_env = clip ? Envelope(clip) : null;
|
||||
while (t < length)
|
||||
{
|
||||
// V puts the phone away, and that ends the call
|
||||
if (takeOut && phone && phone.Mode == PhoneMode.Away) { hungUp = true; break; }
|
||||
Sfx.Duck(0.35f);
|
||||
_voice.volume = VoiceGain(_env);
|
||||
_talkT = t;
|
||||
Caption(CaptionAt(words, Spoken(t)));
|
||||
_view?.Tick(_open, t, MoodAt(moods, Spoken(t)));
|
||||
t += Time.deltaTime;
|
||||
yield return null;
|
||||
}
|
||||
_env = null;
|
||||
_voice.Stop();
|
||||
Caption("");
|
||||
Sfx.Duck(1f);
|
||||
if (hangUp)
|
||||
{
|
||||
Sfx.Play("call_hangup", 0.3f, 1f, 0f);
|
||||
if (!hungUp) yield return new WaitForSeconds(0.35f);
|
||||
if (phone && takeOut && was == PhoneMode.Away && phone.Mode != PhoneMode.Away) phone.Show(PhoneMode.Away);
|
||||
}
|
||||
_view?.Show(false);
|
||||
_on = false;
|
||||
}
|
||||
|
||||
/// <summary>The jaw follows how loud he is, quick to open and a little slower to shut.</summary>
|
||||
void Mouth()
|
||||
{
|
||||
float target = 0f;
|
||||
if (_env != null)
|
||||
{
|
||||
int i = Mathf.Clamp((int)(_talkT * EnvRate), 0, _env.level.Length - 1);
|
||||
target = _env.level[i];
|
||||
}
|
||||
_open = Mathf.SmoothDamp(_open, target, ref _openVel, target > _open ? 0.035f : 0.07f);
|
||||
}
|
||||
|
||||
// how loud he is through the clip, read from the clip itself (so it works with the sound off, too), and how much
|
||||
// of the talking is done by each moment, which is what the captions follow
|
||||
internal const int EnvRate = 60;
|
||||
internal class Env { public float[] level, said; }
|
||||
|
||||
/// <summary>The volume a line plays at now: the Voices slider. The lines themselves are levelled to one loudness by
|
||||
/// Tools/director/finish_audio.py.</summary>
|
||||
internal static float VoiceGain(Env e) => Sfx.VoiceVolume;
|
||||
Env _env;
|
||||
float _talkT;
|
||||
static readonly Dictionary<AudioClip, Env> s_envs = new Dictionary<AudioClip, Env>();
|
||||
|
||||
internal static Env Envelope(AudioClip clip)
|
||||
{
|
||||
if (s_envs.TryGetValue(clip, out var e)) return e;
|
||||
int frames = Mathf.Max(1, Mathf.CeilToInt(clip.length * EnvRate));
|
||||
e = new Env { level = new float[frames], said = new float[frames] };
|
||||
var data = new float[clip.samples * clip.channels];
|
||||
if (clip.loadState == AudioDataLoadState.Loaded && clip.GetData(data, 0))
|
||||
{
|
||||
int per = Mathf.Max(1, data.Length / frames);
|
||||
var rms = new float[frames];
|
||||
for (int f = 0; f < frames; f++)
|
||||
{
|
||||
double sum = 0;
|
||||
int a = f * per, b = Mathf.Min(data.Length, a + per);
|
||||
for (int k = a; k < b; k++) sum += data[k] * data[k];
|
||||
rms[f] = Mathf.Sqrt((float)(sum / Mathf.Max(1, b - a)));
|
||||
}
|
||||
var sorted = (float[])rms.Clone();
|
||||
System.Array.Sort(sorted);
|
||||
float loud = Mathf.Max(0.02f, sorted[(int)(sorted.Length * 0.92f)]);
|
||||
float run = 0f;
|
||||
for (int f = 0; f < frames; f++)
|
||||
{
|
||||
e.level[f] = Mathf.Clamp01((rms[f] / loud - 0.12f) * 1.25f);
|
||||
if (rms[f] > loud * 0.12f) run += 1f;
|
||||
e.said[f] = run;
|
||||
}
|
||||
for (int f = 0; f < frames; f++) e.said[f] /= Mathf.Max(1f, run);
|
||||
}
|
||||
else
|
||||
{
|
||||
// nothing to read: a steady natter, and captions by the clock
|
||||
for (int f = 0; f < frames; f++) { e.level[f] = 0.35f + 0.35f * Mathf.Sin(f * 0.9f) * Mathf.Sin(f * 0.23f); e.said[f] = f / (float)frames; }
|
||||
}
|
||||
s_envs[clip] = e;
|
||||
return e;
|
||||
}
|
||||
|
||||
/// <summary>How much of the line has been said by this time, 0..1.</summary>
|
||||
float Spoken(float t)
|
||||
{
|
||||
if (_env == null || _env.said.Length == 0) return 0f;
|
||||
return _env.said[Mathf.Clamp((int)(t * EnvRate), 0, _env.said.Length - 1)];
|
||||
}
|
||||
|
||||
// ───────── captions ─────────
|
||||
|
||||
static readonly Regex Tag = new Regex(@"\[[^\]]*\]\s*");
|
||||
|
||||
/// <summary>The line split at its sentences, each with where it starts in the clip (by its share of the letters).</summary>
|
||||
internal static List<(float at, string text)> Captions(string line)
|
||||
{
|
||||
var plain = Tag.Replace(line, "").Trim();
|
||||
var parts = Regex.Split(plain, @"(?<=[\.\!\?])\s+").Where(p => p.Length > 0).ToList();
|
||||
// short bursts ride together so the captions don't flicker
|
||||
var merged = new List<string>();
|
||||
foreach (var p in parts)
|
||||
{
|
||||
if (merged.Count > 0 && (merged[merged.Count - 1].Length < 22 || p.Length < 10) && merged[merged.Count - 1].Length + p.Length < 70) merged[merged.Count - 1] += " " + p;
|
||||
else merged.Add(p);
|
||||
}
|
||||
float total = merged.Sum(p => p.Length + 6f), run = 0f;
|
||||
var outp = new List<(float, string)>();
|
||||
foreach (var p in merged) { outp.Add((run / total, p)); run += p.Length + 6f; }
|
||||
return outp;
|
||||
}
|
||||
|
||||
/// <summary>Each tag in the line, as a mood and where in the spoken text it starts (0..1).</summary>
|
||||
internal static List<(float at, Mood mood)> Moods(string line)
|
||||
{
|
||||
var outp = new List<(float, Mood)>();
|
||||
var plainLen = Tag.Replace(line, "").Trim().Length;
|
||||
int said = 0, i = 0;
|
||||
foreach (Match m in Regex.Matches(line, @"\[([^\]]*)\]"))
|
||||
{
|
||||
said += Tag.Replace(line.Substring(i, m.Index - i), "").Length;
|
||||
i = m.Index + m.Length;
|
||||
outp.Add((said / (float)Mathf.Max(1, plainLen), MoodOf(m.Groups[1].Value)));
|
||||
}
|
||||
return outp;
|
||||
}
|
||||
|
||||
static Mood MoodOf(string tag)
|
||||
{
|
||||
switch (tag.Trim().ToLowerInvariant())
|
||||
{
|
||||
case "angry": case "furious": case "frustrated": case "shouting": return Mood.Angry;
|
||||
case "stern": case "deadpan": case "suspicious": case "grudging": case "clears throat": return Mood.Stern;
|
||||
case "excited": case "delighted": case "impressed": case "laughs maniacally": return Mood.Happy;
|
||||
case "emotional": case "sniffles": case "sobbing": case "voice breaking": return Mood.Sad;
|
||||
case "panicked": case "alarmed": case "nervous": return Mood.Scared;
|
||||
case "concerned": return Mood.Sad;
|
||||
case "sighs": return Mood.Stern;
|
||||
case "whispers": case "softly": return Mood.Whisper;
|
||||
default: return Mood.Calm;
|
||||
}
|
||||
}
|
||||
|
||||
internal static Mood MoodAt(List<(float at, Mood mood)> moods, float k)
|
||||
{
|
||||
var m = Mood.Calm;
|
||||
// a pause or a sniff keeps the mood that came before it
|
||||
foreach (var x in moods) if (x.at <= k + 0.005f && x.mood != Mood.Calm) m = x.mood;
|
||||
return m;
|
||||
}
|
||||
|
||||
internal static string CaptionAt(List<(float at, string text)> words, float k)
|
||||
{
|
||||
string s = "";
|
||||
foreach (var w in words) if (w.at <= k + 0.01f) s = w.text;
|
||||
// timed on the English voice, shown in the interface language (Tools/loc/extract.py lists these pieces)
|
||||
return Loc.T(s);
|
||||
}
|
||||
|
||||
void Caption(string text)
|
||||
{
|
||||
var c = Ensure(ref _caption, "director-caption t-outline");
|
||||
c.text = text;
|
||||
c.style.display = string.IsNullOrEmpty(text) ? DisplayStyle.None : DisplayStyle.Flex;
|
||||
}
|
||||
|
||||
static Label Ensure(ref Label l, string cls)
|
||||
{
|
||||
if (l != null && l.panel != null) return l;
|
||||
var root = UIRoot.I ? UIRoot.I.Cinema : null;
|
||||
l = UIK.Text("", cls, root, false);
|
||||
l.pickingMode = PickingMode.Ignore;
|
||||
l.style.display = DisplayStyle.None;
|
||||
return l;
|
||||
}
|
||||
|
||||
// ───────── what makes him call ─────────
|
||||
|
||||
void Watch()
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
var me = PlayerAgent.Local;
|
||||
if (!ts || !ts.IsSpawned || !me || !me.IsSpawned) { _seeded = false; _seedAt = -1f; return; }
|
||||
// the world comes back from the save first, then whatever is already there doesn't count
|
||||
if (_seedAt < 0f) _seedAt = Time.time + 6f;
|
||||
bool machine = Vehicle.All.Any(v => v && v.Crew.Value.ToString() == me.SaveId);
|
||||
bool combine = Vehicle.All.Any(v => v && v.kind == VehicleKind.Combine);
|
||||
bool drones = BuildPiece.All.Any(p => p && p.piece == PieceId.DronePad);
|
||||
bool belts = BuildPiece.All.Any(p => p && p is BeltRun);
|
||||
bool ufo = ts.UfoOn;
|
||||
double mown = ts.Mown01;
|
||||
if (!_seeded)
|
||||
{
|
||||
if (Time.time < _seedAt) return;
|
||||
_seeded = true;
|
||||
(_mown, _machine, _combine, _drones, _belts, _ufo) = (mown, machine, combine, drones, belts, ufo);
|
||||
return;
|
||||
}
|
||||
foreach (var (at, line) in Milestones)
|
||||
if (_mown < at && mown >= at) Call(line);
|
||||
if (machine && !_machine) Call("dir_machine");
|
||||
if (combine && !_combine) Call("dir_combine");
|
||||
if (drones && !_drones) Call("dir_drones");
|
||||
if (belts && !_belts) Call("dir_belts");
|
||||
// the saucer only the first time it is ever seen
|
||||
if (ufo && !_ufo && PlayerPrefs.GetInt("dir_ufo", 0) == 0) { PlayerPrefs.SetInt("dir_ufo", 1); Call("dir_ufo"); }
|
||||
(_mown, _machine, _combine, _drones, _belts, _ufo) = (mown, machine, combine, drones, belts, ufo);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the Director is feeling, read off the tags in his lines.</summary>
|
||||
public enum Mood { Calm, Angry, Stern, Happy, Sad, Scared, Whisper }
|
||||
|
||||
/// <summary>
|
||||
/// The call on the phone's display: the Director in 3D at mission control on Earth (filmed in his booth in the Studio),
|
||||
/// talking like a South Park cut-out, the top of his head tipping up off one side and then the other over a dark mouth.
|
||||
/// How he feels shows on him and round him: red in the face with steam out of his ears and a throbbing vein when he
|
||||
/// shouts, arms up and sparkles when he's pleased, tears when he's moved, sweat when he panics, leaning in to whisper.
|
||||
/// </summary>
|
||||
public class PhoneCall
|
||||
{
|
||||
const float W = PhoneScreen.W, H = PhoneScreen.H;
|
||||
const int RtW = 540, RtH = 1184; // the screen's shape, at three quarters
|
||||
static readonly Vector2[] SparkRing =
|
||||
{
|
||||
new Vector2(-1f, -0.55f), new Vector2(1f, -0.4f), new Vector2(-1.1f, 0.35f), new Vector2(1.1f, 0.3f), new Vector2(0f, -1.05f),
|
||||
};
|
||||
|
||||
readonly VisualElement _root, _picture, _fx, _vein;
|
||||
readonly VisualElement[] _sparks;
|
||||
readonly Label _timer;
|
||||
readonly Booth _booth;
|
||||
// the user's filmed loops of him, one per mood: they carry his face, so the drawn-on vein, steam and tears stay off
|
||||
readonly TalkVideo _talk;
|
||||
float _lastT, _puffDue, _tearDue, _sweatDue;
|
||||
// where his picture stands on the screen: under the agency's bar, over the red button
|
||||
const float PicTop = 200f, PicBottom = 170f;
|
||||
// how much of each mood is showing, eased in and out
|
||||
readonly float[] _mood = new float[7];
|
||||
|
||||
class Bit { public VisualElement e; public Vector2 at, vel; public float age, life, size; public bool live; public int kind; }
|
||||
readonly List<Bit> _bits = new List<Bit>();
|
||||
|
||||
public PhoneCall(VisualElement screen)
|
||||
{
|
||||
_root = Box(screen, 0f, 0f, W, H);
|
||||
_root.style.backgroundColor = new Color(0.1f, 0.16f, 0.3f);
|
||||
// mission control behind him, and him in front from the hips up, like a video call
|
||||
var bg = AssetBank.I ? AssetBank.I.Tex("T_Dir_Bg") : null;
|
||||
if (bg)
|
||||
{
|
||||
_root.style.backgroundImage = new StyleBackground(bg);
|
||||
_root.style.unityBackgroundScaleMode = ScaleMode.ScaleAndCrop;
|
||||
_root.style.unityBackgroundImageTintColor = new Color(0.82f, 0.86f, 0.95f);
|
||||
}
|
||||
_talk = new TalkVideo("boss", new[] { "calm", "stern", "angry" }, 640, 650);
|
||||
_picture = Box(_root, 0f, PicTop, W, H - PicTop - PicBottom);
|
||||
_picture.style.unityBackgroundScaleMode = ScaleMode.ScaleAndCrop;
|
||||
_talk.Switched = rt => _picture.style.backgroundImage = new StyleBackground(Background.FromRenderTexture(rt));
|
||||
_talk.Switched(_talk.Rt);
|
||||
_fx = Box(_root, 0f, 0f, W, H);
|
||||
|
||||
// the anger vein on his forehead
|
||||
_vein = Box(_fx, 0f, 0f, 76f, 76f);
|
||||
_vein.generateVisualContent += DrawVein;
|
||||
_vein.style.opacity = 0f;
|
||||
// sparkles round him
|
||||
_sparks = new VisualElement[SparkRing.Length];
|
||||
for (int i = 0; i < SparkRing.Length; i++)
|
||||
{
|
||||
_sparks[i] = Box(_fx, 0f, 0f, 64f, 64f);
|
||||
_sparks[i].generateVisualContent += DrawSpark;
|
||||
_sparks[i].style.opacity = 0f;
|
||||
}
|
||||
|
||||
// the agency's bar
|
||||
var bar = Box(_root, 0f, 0f, W, 230f);
|
||||
bar.style.backgroundColor = new Color(0.02f, 0.05f, 0.12f, 0.72f);
|
||||
bar.style.alignItems = Align.Center;
|
||||
bar.style.paddingTop = 78;
|
||||
var name = UIK.Text("G.R.A.S.S.A.", "", bar, true);
|
||||
name.style.fontSize = 64; name.style.color = new Color(1f, 0.86f, 0.4f);
|
||||
var row = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
row.style.flexDirection = FlexDirection.Row;
|
||||
row.style.alignItems = Align.Center;
|
||||
bar.Add(row);
|
||||
var dot = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
dot.style.width = 20; dot.style.height = 20; dot.style.marginRight = 12;
|
||||
dot.style.backgroundColor = new Color(1f, 0.25f, 0.2f);
|
||||
Radius(dot, 10f);
|
||||
row.Add(dot);
|
||||
var who = UIK.Text(Loc.T("THE DIRECTOR · LIVE FROM EARTH"), "", row, false);
|
||||
who.style.fontSize = 28; who.style.color = new Color(0.86f, 0.92f, 1f);
|
||||
_timer = UIK.Text("00:00", "", bar, false);
|
||||
_timer.style.fontSize = 26; _timer.style.color = new Color(0.7f, 0.8f, 0.9f, 0.8f);
|
||||
|
||||
// the red button at the foot
|
||||
var hang = Box(_root, (W - 110f) * 0.5f, H - 160f, 110f, 110f);
|
||||
hang.style.backgroundColor = new Color(0.92f, 0.2f, 0.18f);
|
||||
Radius(hang, 55f);
|
||||
var key = UIK.Text("V", "", hang, true);
|
||||
key.style.fontSize = 48; key.style.color = Color.white;
|
||||
key.style.unityTextAlign = TextAnchor.MiddleCenter;
|
||||
key.style.flexGrow = 1;
|
||||
Show(false);
|
||||
}
|
||||
|
||||
static VisualElement Box(VisualElement parent, float x, float y, float w, float h)
|
||||
{
|
||||
var e = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
e.style.position = Position.Absolute;
|
||||
e.style.left = x; e.style.top = y; e.style.width = w; e.style.height = h;
|
||||
parent.Add(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
static void Radius(VisualElement e, float r)
|
||||
{
|
||||
e.style.borderTopLeftRadius = e.style.borderTopRightRadius = e.style.borderBottomLeftRadius = e.style.borderBottomRightRadius = r;
|
||||
}
|
||||
|
||||
public void Show(bool on)
|
||||
{
|
||||
_root.style.display = on ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_booth?.Show(on);
|
||||
if (!on) { _talk?.Stop(); return; }
|
||||
_root.BringToFront();
|
||||
_lastT = 0f;
|
||||
for (int i = 0; i < _mood.Length; i++) _mood[i] = 0f;
|
||||
foreach (var b in _bits) { b.live = false; b.e.style.display = DisplayStyle.None; }
|
||||
Tick(0f, 0f, Mood.Calm);
|
||||
}
|
||||
|
||||
// with the filmed loops there are no bones to follow: round about where his head is in them
|
||||
Vector2 At(string anchor) => _booth != null && _booth.Puppet != null ? _booth.OnPicture(_booth.Puppet.Anchor(anchor), W, H) : new Vector2(W * 0.5f, PicTop + 330f);
|
||||
|
||||
/// <summary>open 0..1: how far the top of his head is up; t: seconds into the call; mood: what the line says now.</summary>
|
||||
public void Tick(float open, float t, Mood mood)
|
||||
{
|
||||
float dt = Mathf.Clamp(t - _lastT, 0f, 0.1f);
|
||||
_lastT = t;
|
||||
for (int i = 0; i < _mood.Length; i++) _mood[i] = Mathf.MoveTowards(_mood[i], i == (int)mood ? 1f : 0f, dt * 3f);
|
||||
float angry = _mood[(int)Mood.Angry], happy = _mood[(int)Mood.Happy];
|
||||
float sad = _mood[(int)Mood.Sad], scared = _mood[(int)Mood.Scared];
|
||||
|
||||
_booth?.Puppet?.Tick(t, open, _mood);
|
||||
_booth?.Flush(angry * (0.18f + open * 0.14f));
|
||||
_talk?.Play(TalkVideo.BossMood(TalkVideo.Strongest(_mood)));
|
||||
if (_talk != null) angry = sad = scared = 0f;
|
||||
|
||||
// the vein throbs on his forehead while he's angry
|
||||
var brow = At("Forehead");
|
||||
float throb = 1f + Mathf.Max(0f, Mathf.Sin(t * 9f)) * 0.25f * angry;
|
||||
_vein.style.left = brow.x + 22f - 38f;
|
||||
_vein.style.top = brow.y - 30f - 38f;
|
||||
_vein.style.opacity = angry;
|
||||
_vein.style.scale = new Scale(new Vector3(throb, throb, 1f));
|
||||
// sparkles pop in turn round his head while he's pleased
|
||||
var head = At("Forehead");
|
||||
for (int i = 0; i < _sparks.Length; i++)
|
||||
{
|
||||
float ph = Mathf.Repeat(t * 1.3f + i * 0.37f, 1f);
|
||||
float k = Mathf.Sin(ph * Mathf.PI) * happy;
|
||||
var p = head + SparkRing[i] * 230f;
|
||||
_sparks[i].style.left = p.x - 32f;
|
||||
_sparks[i].style.top = p.y - 32f;
|
||||
_sparks[i].style.opacity = k;
|
||||
_sparks[i].style.scale = new Scale(new Vector3(0.4f + k * 0.8f, 0.4f + k * 0.8f, 1f));
|
||||
_sparks[i].style.rotate = new Rotate(t * 90f + i * 40f);
|
||||
}
|
||||
|
||||
// steam out of his ears, tears down his cheeks, sweat on his temple
|
||||
_puffDue += dt * angry * (5f + open * 8f);
|
||||
for (; _puffDue >= 1f; _puffDue -= 1f)
|
||||
{
|
||||
int side = Random.value < 0.5f ? 0 : 1;
|
||||
var ear = At(side == 0 ? "Ear_L" : "Ear_R");
|
||||
float out_ = Mathf.Sign(ear.x - head.x);
|
||||
Spawn(0, ear, new Vector2(out_ * Random.Range(40f, 90f), Random.Range(-170f, -120f)), Random.Range(30f, 46f), 0.9f);
|
||||
}
|
||||
_tearDue += dt * sad * 2.4f;
|
||||
for (; _tearDue >= 1f; _tearDue -= 1f)
|
||||
{
|
||||
var eye = At(Random.value < 0.5f ? "Eye_L" : "Eye_R");
|
||||
Spawn(1, eye + new Vector2(0f, 26f), new Vector2(0f, 70f), Random.Range(16f, 22f), 1.6f);
|
||||
}
|
||||
_sweatDue += dt * scared * 1.6f;
|
||||
for (; _sweatDue >= 1f; _sweatDue -= 1f)
|
||||
Spawn(2, At("Temple") + new Vector2(Random.Range(-12f, 12f), 0f), new Vector2(0f, 50f), Random.Range(16f, 22f), 1.4f);
|
||||
Bits(dt);
|
||||
|
||||
_timer.text = $"{(int)(t / 60f):00}:{(int)t % 60:00}";
|
||||
}
|
||||
|
||||
void Spawn(int kind, Vector2 at, Vector2 vel, float size, float life)
|
||||
{
|
||||
Bit b = null;
|
||||
foreach (var x in _bits) if (!x.live && x.kind == kind) { b = x; break; }
|
||||
if (b == null)
|
||||
{
|
||||
if (_bits.Count > 60) return;
|
||||
var e = Box(_fx, 0f, 0f, 1f, 1f);
|
||||
if (kind == 0) e.style.backgroundColor = new Color(1f, 1f, 1f, 0.85f);
|
||||
else e.style.backgroundColor = kind == 1 ? new Color(0.55f, 0.8f, 1f, 0.95f) : new Color(0.7f, 0.9f, 1f, 0.9f);
|
||||
b = new Bit { e = e, kind = kind };
|
||||
_bits.Add(b);
|
||||
}
|
||||
b.live = true; b.at = at; b.vel = vel; b.age = 0f; b.life = life; b.size = size;
|
||||
b.e.style.display = DisplayStyle.Flex;
|
||||
b.e.BringToFront();
|
||||
}
|
||||
|
||||
void Bits(float dt)
|
||||
{
|
||||
foreach (var b in _bits)
|
||||
{
|
||||
if (!b.live) continue;
|
||||
b.age += dt;
|
||||
if (b.age >= b.life) { b.live = false; b.e.style.display = DisplayStyle.None; continue; }
|
||||
float k = b.age / b.life;
|
||||
b.at += b.vel * dt;
|
||||
float w, h;
|
||||
if (b.kind == 0)
|
||||
{
|
||||
// a puff swells and thins as it rises
|
||||
b.vel *= 1f - dt * 0.8f;
|
||||
w = h = b.size * (0.6f + k * 1.6f);
|
||||
b.e.style.opacity = (1f - k) * 0.9f;
|
||||
Radius(b.e, w * 0.5f);
|
||||
}
|
||||
else
|
||||
{
|
||||
// a drop runs down, picking up speed
|
||||
b.vel.y += 90f * dt;
|
||||
w = b.size * 0.7f; h = b.size;
|
||||
b.e.style.opacity = Mathf.Clamp01((1f - k) * 3f);
|
||||
b.e.style.borderTopLeftRadius = b.e.style.borderTopRightRadius = w * 0.5f;
|
||||
b.e.style.borderBottomLeftRadius = b.e.style.borderBottomRightRadius = w * 0.5f;
|
||||
}
|
||||
b.e.style.left = b.at.x - w * 0.5f;
|
||||
b.e.style.top = b.at.y - h * 0.5f;
|
||||
b.e.style.width = w;
|
||||
b.e.style.height = h;
|
||||
}
|
||||
}
|
||||
|
||||
static void DrawVein(MeshGenerationContext ctx)
|
||||
{
|
||||
// the cartoon cross-popping vein: four little arcs bowing in
|
||||
var p = ctx.painter2D;
|
||||
float s = ctx.visualElement.contentRect.width;
|
||||
var c = new Vector2(s * 0.5f, s * 0.5f);
|
||||
p.strokeColor = new Color(0.86f, 0.12f, 0.12f);
|
||||
p.lineWidth = s * 0.11f;
|
||||
p.lineCap = LineCap.Round;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float a = i * 90f + 45f;
|
||||
var dir = new Vector2(Mathf.Cos(a * Mathf.Deg2Rad), Mathf.Sin(a * Mathf.Deg2Rad));
|
||||
var mid = c + dir * s * 0.3f;
|
||||
p.BeginPath();
|
||||
p.Arc(mid + dir * s * 0.12f, s * 0.2f, a + 180f - 50f, a + 180f + 50f);
|
||||
p.Stroke();
|
||||
}
|
||||
}
|
||||
|
||||
static void DrawSpark(MeshGenerationContext ctx)
|
||||
{
|
||||
// a four-pointed star
|
||||
var p = ctx.painter2D;
|
||||
float s = ctx.visualElement.contentRect.width;
|
||||
var c = new Vector2(s * 0.5f, s * 0.5f);
|
||||
p.fillColor = new Color(1f, 0.9f, 0.35f);
|
||||
p.BeginPath();
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
float a = i * 45f * Mathf.Deg2Rad;
|
||||
float r = i % 2 == 0 ? s * 0.5f : s * 0.13f;
|
||||
var v = c + new Vector2(Mathf.Sin(a), -Mathf.Cos(a)) * r;
|
||||
if (i == 0) p.MoveTo(v); else p.LineTo(v);
|
||||
}
|
||||
p.ClosePath();
|
||||
p.Fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/DirectorCall.cs.meta
Normal file
2
Assets/Scripts/UI/DirectorCall.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b462915977f1e464aab5f6a114f46eec
|
||||
143
Assets/Scripts/UI/GarageScreen.cs
Normal file
143
Assets/Scripts/UI/GarageScreen.cs
Normal file
@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The garage: the five machines down the left, the selected one on the right with what it can do, the button to buy or
|
||||
/// call it, and its upgrades. Machines and their upgrades are personal, paid for from the crew wallet.
|
||||
/// </summary>
|
||||
public class GarageScreen
|
||||
{
|
||||
public VisualElement Card { get; }
|
||||
readonly Label _money;
|
||||
readonly VisualElement _grid, _detail;
|
||||
readonly ulong _garage;
|
||||
VehicleKind _selected = VehicleKind.Push;
|
||||
string _shown;
|
||||
|
||||
TeamState Ts => TeamState.Instance;
|
||||
PlayerAgent Me => PlayerAgent.Local;
|
||||
Vehicle Mine(VehicleKind k) => Me ? Vehicle.Mine(k, Me.SaveId) : null;
|
||||
|
||||
public GarageScreen(VisualElement layer, Action close, Garage garage, VehicleKind? select = null)
|
||||
{
|
||||
_garage = garage ? garage.NetworkObjectId : 0UL;
|
||||
if (select.HasValue) _selected = select.Value;
|
||||
Card = UIK.El("card shop", layer);
|
||||
Card.pickingMode = PickingMode.Position;
|
||||
var header = UIK.El("card-header", Card);
|
||||
UIK.Text(Loc.T("GARAGE"), "t-h1 t-dark", header);
|
||||
var right = UIK.El(null, header);
|
||||
right.style.flexDirection = FlexDirection.Row;
|
||||
right.style.alignItems = Align.Center;
|
||||
var wallet = UIK.El("pill", right);
|
||||
UIK.Img(AssetBank.I.Tex("icon_coin"), "check-icon", wallet);
|
||||
_money = UIK.Text("$0", "t-h2 t-dark", wallet);
|
||||
wallet.style.marginRight = 16;
|
||||
UIK.Btn("X", close, "btn btn-red btn-small", right);
|
||||
|
||||
var body = UIK.El("tree-body", Card);
|
||||
_grid = UIK.El("tree-graph supply-grid", body);
|
||||
_detail = UIK.El("tree-detail", body);
|
||||
|
||||
// a machine or an upgrade arrives a moment after the server says so
|
||||
Card.schedule.Execute(Refresh).Every(250);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
void Refresh()
|
||||
{
|
||||
var ts = Ts;
|
||||
var me = Me;
|
||||
if (!ts || !me) return;
|
||||
_money.text = UIK.Money(ts.Money.Value);
|
||||
var key = $"{_selected} {Math.Floor(ts.Money.Value)}";
|
||||
foreach (var d in GameDefs.Vehicles)
|
||||
{
|
||||
var v = Mine(d.kind);
|
||||
key += v ? "1" : "0";
|
||||
if (!v) continue;
|
||||
for (int i = 0; i < v.Tuned.Count; i++) key += v.Tuned[i];
|
||||
key += v.Tank.Value.ToString("0");
|
||||
}
|
||||
if (key == _shown) return;
|
||||
bool first = _shown == null;
|
||||
_shown = key;
|
||||
_grid.Clear();
|
||||
int n = 0;
|
||||
foreach (var d in GameDefs.Vehicles) Item(d, n++, first);
|
||||
Detail();
|
||||
}
|
||||
|
||||
void Item(VehicleDef d, int index, bool animate)
|
||||
{
|
||||
var v = Mine(d.kind);
|
||||
var e = UIK.El("supply-item", _grid);
|
||||
e.pickingMode = PickingMode.Position;
|
||||
e.EnableInClassList("supply-item-on", d.kind == _selected);
|
||||
UIK.Img(AssetBank.I.Tex(d.icon), "supply-icon", e).pickingMode = PickingMode.Ignore;
|
||||
UIK.Text(d.name, "supply-name", e, false).pickingMode = PickingMode.Ignore;
|
||||
UIK.Text(d.bed > 0 ? Loc.F("{0} bundles", d.bed) : Loc.F("{0:0.##} m · {1:0} kg", d.width, d.hopper), "supply-sub", e, false).pickingMode = PickingMode.Ignore;
|
||||
var t = UIK.Text(v ? Loc.T("OWNED") : UIK.Money(d.price), "supply-tag", e, false);
|
||||
t.pickingMode = PickingMode.Ignore;
|
||||
t.EnableInClassList("supply-tag-afford", !v && Ts.Money.Value >= d.price);
|
||||
e.RegisterCallback<ClickEvent>(_ => { _selected = d.kind; Sfx.Play("ui_click", 0.6f, 1.1f); Refresh(); });
|
||||
e.RegisterCallback<MouseEnterEvent>(_ => Sfx.Play("ui_hover", 0.35f, 1.2f));
|
||||
if (animate) UIK.PopIn(e, 0.03f * index, 0.3f);
|
||||
}
|
||||
|
||||
void Detail()
|
||||
{
|
||||
var ts = Ts;
|
||||
var d = GameDefs.Vehicle(_selected);
|
||||
var v = Mine(_selected);
|
||||
_detail.Clear();
|
||||
var top = UIK.El("detail-top", _detail);
|
||||
top.style.backgroundColor = new Color(0.9f, 0.8f, 0.55f);
|
||||
UIK.Img(AssetBank.I.Tex(d.icon), "detail-icon", top);
|
||||
UIK.Text(d.name, "t-h1 t-dark t-center detail-title", _detail);
|
||||
UIK.Text(d.desc, "item-desc t-center", _detail, false).style.whiteSpace = WhiteSpace.Normal;
|
||||
if (v) UIK.Text(d.bed > 0 ? Loc.F("Bed: {0} of {1}", v.Bed.Count, d.bed) : Loc.F("Strip {0:0.##} m · top speed {1:0} km/h · {2} of {3}", v.CutWidth, v.TopSpeed * 3.6f, GameDefs.Kilos(v.Tank.Value), GameDefs.Kilos(v.Capacity)), "t-small t-dark t-center", _detail, false).style.whiteSpace = WhiteSpace.Normal;
|
||||
if (!v)
|
||||
{
|
||||
bool can = ts.Money.Value >= d.price;
|
||||
var b = UIK.Btn(Loc.F("BUY {0}", UIK.Money(d.price)), () =>
|
||||
{
|
||||
if (!can) { Sfx.Play("error", 0.7f); Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn); return; }
|
||||
ts.BuyVehicleRpc((byte)d.kind, _garage);
|
||||
Sfx.Play("cash_register", 0.9f);
|
||||
}, can ? "btn btn-green" : "btn btn-grey", _detail);
|
||||
b.style.alignSelf = Align.Stretch;
|
||||
return;
|
||||
}
|
||||
var call = UIK.Btn(Loc.T("CALL IT HERE"), () => { ts.CallVehicleRpc(v.NetworkObjectId, _garage); Sfx.Play("ui_click", 0.7f); }, "btn btn-green", _detail);
|
||||
call.style.alignSelf = Align.Stretch;
|
||||
var list = new ScrollView(ScrollViewMode.Vertical);
|
||||
list.AddToClassList("tune-list");
|
||||
_detail.Add(list);
|
||||
for (int i = 0; i < (int)TuneId.Count; i++) Tune(list.contentContainer, v, (TuneId)i);
|
||||
}
|
||||
|
||||
void Tune(VisualElement parent, Vehicle v, TuneId id)
|
||||
{
|
||||
var d = GameDefs.Tune(id);
|
||||
if (!GameDefs.TuneFits(v.kind, id)) return;
|
||||
int level = v.Level(id);
|
||||
bool max = level >= d.prices.Length;
|
||||
double price = max ? 0d : GameDefs.TunePrice(v.kind, id, level);
|
||||
bool can = !max && Ts.Money.Value >= price;
|
||||
var row = UIK.El("tune-row", parent);
|
||||
var names = UIK.El("tune-names", row);
|
||||
UIK.Text($"{d.name} {level}/{d.prices.Length}", "t-small t-dark", names, false);
|
||||
UIK.Text(max ? d.effect(level) : d.effect(level + 1), "tune-effect", names, false);
|
||||
UIK.Btn(max ? Loc.T("MAX") : UIK.Money(price), () =>
|
||||
{
|
||||
if (!can) { Sfx.Play("error", 0.7f); return; }
|
||||
Ts.TuneVehicleRpc(v.NetworkObjectId, (byte)id);
|
||||
Sfx.Play("cash_register", 0.9f);
|
||||
}, (can ? "btn btn-green" : "btn btn-grey") + " btn-small", row);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/GarageScreen.cs.meta
Normal file
2
Assets/Scripts/UI/GarageScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e8268c15e95e88e4387f2509525faacb
|
||||
834
Assets/Scripts/UI/Hud.cs
Normal file
834
Assets/Scripts/UI/Hud.cs
Normal file
@ -0,0 +1,834 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// In-game HUD: compass (top centre), tool plate with its container (bottom left), tool belt (bottom centre), wallet
|
||||
/// (bottom right), the sector underfoot and the planet (top right), key hints (right), build palette, crosshair/prompt,
|
||||
/// floating cash, toasts, banners, name tags and tutorial hints.
|
||||
/// </summary>
|
||||
public class Hud
|
||||
{
|
||||
public enum ToastKind { Info, Good, Warn, Money }
|
||||
|
||||
readonly VisualElement _root, _world;
|
||||
Label _money, _planetPct, _planetSub, _sectorName, _sectorPct;
|
||||
VisualElement _sectorHex, _chips;
|
||||
Label _chipMow, _chipBoost, _chipCruise;
|
||||
Compass _compass;
|
||||
int _hexState = -1;
|
||||
VisualElement _coin;
|
||||
VisualElement _hotbar;
|
||||
readonly Dictionary<ToolId, VisualElement> _slots = new Dictionary<ToolId, VisualElement>();
|
||||
VisualElement _plate, _gauge, _gaugeFill, _buildHint, _bootsHint, _blade, _receipt, _phoneUpHint, _phoneTurnHint;
|
||||
Label _toolName, _toolKg, _toolRate;
|
||||
VisualElement _crosshair, _prompt;
|
||||
Label _promptKey, _promptTitle, _promptText;
|
||||
VisualElement _promptMore;
|
||||
string _promptWas;
|
||||
VisualElement _toasts, _banner, _hint, _players;
|
||||
Label _hintText;
|
||||
VisualElement _build, _buildRow, _buildCats;
|
||||
Label _buildHelp, _buildReason;
|
||||
readonly List<Label> _floatPool = new List<Label>();
|
||||
readonly Dictionary<PlayerAgent, Label> _tags = new Dictionary<PlayerAgent, Label>();
|
||||
|
||||
double _shownMoney, _targetMoney, _slipKg, _slipPay;
|
||||
float _slipAt = -9f;
|
||||
float _lastTick, _tankPunch;
|
||||
PlayerAgent _local;
|
||||
string _beltKey = "";
|
||||
int _buildKey = -1;
|
||||
|
||||
static Hud Instance => UIRoot.I ? UIRoot.I.Hud : null;
|
||||
|
||||
public Hud(VisualElement root, VisualElement world)
|
||||
{
|
||||
_root = root;
|
||||
_world = world;
|
||||
Build();
|
||||
TeamState.MoneyChanged += OnMoney;
|
||||
TeamState.Purchased += OnPurchased;
|
||||
TeamState.Announcement += OnAnnouncement;
|
||||
TeamState.Deposited += OnDeposited;
|
||||
TeamState.SectorClosed += OnSectorClosed;
|
||||
TeamState.MarkFound += OnMarkFound;
|
||||
}
|
||||
|
||||
/// <summary>The language changed and a new HUD takes over: this one lets go of the game's events and the world layer.</summary>
|
||||
public void Detach()
|
||||
{
|
||||
TeamState.MoneyChanged -= OnMoney;
|
||||
TeamState.Purchased -= OnPurchased;
|
||||
TeamState.Announcement -= OnAnnouncement;
|
||||
TeamState.Deposited -= OnDeposited;
|
||||
TeamState.SectorClosed -= OnSectorClosed;
|
||||
TeamState.MarkFound -= OnMarkFound;
|
||||
_treats?.Detach();
|
||||
if (_local != null && _onTool != null) _local.Tools.ToolChanged -= _onTool;
|
||||
foreach (var t in _tags.Values) t.RemoveFromHierarchy();
|
||||
_tags.Clear();
|
||||
foreach (var d in _drops) d.RemoveFromHierarchy();
|
||||
foreach (var f in _floatPool) f.RemoveFromHierarchy();
|
||||
_local = null;
|
||||
}
|
||||
|
||||
System.Action<ToolId> _onTool;
|
||||
|
||||
void OnPurchased(string who, string what)
|
||||
{
|
||||
Toast(Loc.F("{0} bought {1}!", who, Loc.Unpack(what)), ToastKind.Good);
|
||||
Sfx.Play("perk_unlock", 0.8f);
|
||||
Sfx.Play("cash_register", 0.6f);
|
||||
}
|
||||
|
||||
void OnAnnouncement(string a) => Toast(Loc.Unpack(a), ToastKind.Info);
|
||||
|
||||
void OnSectorClosed(int id, double pay)
|
||||
{
|
||||
Toast(Loc.F("Sector {0:N0} mown clean! +{1}", id + 1, UIK.Money(pay)), ToastKind.Money);
|
||||
Sfx.Play("perk_unlock", 0.7f);
|
||||
}
|
||||
|
||||
void OnMarkFound(string who, int id, double pay)
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
bool point = Landmarks.IsPoint(id);
|
||||
Toast(point ? Loc.F("{0} read a survey point +{1} ({2} / {3})", who, UIK.Money(pay), ts ? ts.FoundCount(true) : 0, Landmarks.Points) : Loc.F("{0} untangled a stake +{1} ({2} / {3})", who, UIK.Money(pay), ts ? ts.FoundCount(false) : 0, Landmarks.Stakes), ToastKind.Money);
|
||||
Sfx.Play("cash_register", 0.8f);
|
||||
}
|
||||
|
||||
void Build()
|
||||
{
|
||||
var bank = AssetBank.I;
|
||||
// wallet
|
||||
var m = UIK.El("hud-money", _root);
|
||||
_coin = UIK.Img(bank.Tex("icon_coin"), "coin", m);
|
||||
_money = UIK.Text("$0", "money-text t-outline", m);
|
||||
|
||||
// the planet: how much of Herbaria-7 is mown
|
||||
var s = UIK.El("hud-sector", _root);
|
||||
var head = UIK.El("sector-head", s);
|
||||
var names = UIK.El("sector-names", head);
|
||||
_sectorName = UIK.Text("", "t-h2 t-outline", names);
|
||||
_sectorPct = UIK.Text("", "t-small t-outline", names, false);
|
||||
_sectorHex = UIK.El("sector-hex", head);
|
||||
_sectorHex.generateVisualContent += DrawHex;
|
||||
_planetPct = UIK.Text("", "planet-pct t-outline", s, false);
|
||||
_planetSub = UIK.Text("", "t-small t-outline", s, false);
|
||||
|
||||
// key hints
|
||||
var hints = _hints = UIK.El("hud-hints", _root);
|
||||
HintRow(hints, Act.Stats, Loc.T("Stats"));
|
||||
HintRow(hints, Act.Map, Loc.T("Map"));
|
||||
HintRow(hints, Act.Pack, Loc.T("Bundle"));
|
||||
HintRow(hints, Act.Notebook, Loc.T("Notebook"));
|
||||
_buildHint = HintRow(hints, Act.Build, Loc.T("Build"));
|
||||
_bootsHint = HintRow(hints, Act.Boots, Loc.T("Boots"));
|
||||
HintRow(hints, Act.Lamp, Loc.T("Lamp"));
|
||||
HintRow(hints, Act.Phone, Loc.T("Phone"));
|
||||
_phoneUpHint = HintRow(hints, Act.PhoneTap, Loc.T("Tap the phone"));
|
||||
_phoneTurnHint = HintRow(hints, Act.PhoneTurn, Loc.T("Turn the phone"));
|
||||
RefreshHints();
|
||||
|
||||
// tool belt
|
||||
_hotbar = UIK.El("hotbar", _root);
|
||||
|
||||
// the tool in hand and its container (bottom left)
|
||||
_plate = UIK.El("tool-plate", _root);
|
||||
_gauge = UIK.El("tank-glass tool-gauge", _plate);
|
||||
_gaugeFill = UIK.El("tank-fill", _gauge);
|
||||
var col = UIK.El("tool-col", _plate);
|
||||
_toolRate = UIK.Text("", "tank-rate t-outline", col, false);
|
||||
_toolKg = UIK.Text("", "tool-kg t-outline", col);
|
||||
_toolName = UIK.Text("", "tool-name", col);
|
||||
_chips = UIK.El("drive-chips", col);
|
||||
_chipMow = UIK.Text(Loc.T("MOWING"), "drive-chip", _chips);
|
||||
_chipBoost = UIK.Text(Loc.T("BOOST"), "drive-chip", _chips);
|
||||
_chipCruise = UIK.Text(Loc.T("CRUISE"), "drive-chip", _chips);
|
||||
_chips.style.display = DisplayStyle.None;
|
||||
|
||||
_compass = new Compass(_root);
|
||||
|
||||
// build palette
|
||||
_build = UIK.El("build-panel", _root);
|
||||
_buildCats = UIK.El("build-cats", _build);
|
||||
_buildRow = UIK.El("build-row", _build);
|
||||
_buildReason = UIK.Text("", "t-body t-outline build-reason", _build, false);
|
||||
_buildHelp = UIK.Text(Loc.T("WHEEL piece · LMB place · R rotate · T move · MMB copy · RMB remove · CTRL+WHEEL height · F free"), "t-small t-outline", _build, false);
|
||||
_build.style.display = DisplayStyle.None;
|
||||
|
||||
// how wide the blade in hand cuts, drawn to scale across the aim
|
||||
_blade = UIK.El("blade-bar", _root);
|
||||
_blade.style.display = DisplayStyle.None;
|
||||
|
||||
// the depot's receipt
|
||||
_receipt = UIK.El("receipt", _root);
|
||||
_receipt.style.display = DisplayStyle.None;
|
||||
|
||||
// crosshair & prompt
|
||||
_crosshair = UIK.El("crosshair", _root);
|
||||
// what you look at: a card under the crosshair, out of the way of the thing itself. The name on top, the details
|
||||
// a line each underneath, and the other keys as chips of their own
|
||||
_prompt = UIK.El("prompt", _root);
|
||||
_prompt.pickingMode = PickingMode.Ignore;
|
||||
_promptKey = UIK.Text("E", "key", _prompt);
|
||||
var promptCol = UIK.El("prompt-col", _prompt);
|
||||
_promptTitle = UIK.Text("", "prompt-title", promptCol, false);
|
||||
_promptText = UIK.Text("", "prompt-body", promptCol, false);
|
||||
_promptMore = UIK.El("prompt-more", promptCol);
|
||||
_prompt.style.display = DisplayStyle.None;
|
||||
|
||||
_toasts = UIK.El("toasts", _root);
|
||||
_banner = UIK.El("banner", _root);
|
||||
_hint = UIK.El("hint", _root);
|
||||
_hintText = UIK.Text("", "t-body t-dark", _hint, false);
|
||||
_hint.style.display = DisplayStyle.None;
|
||||
|
||||
_players = UIK.El("card players", _root);
|
||||
_players.style.display = DisplayStyle.None;
|
||||
|
||||
// the boosts from the vending machines, top left, and the flash when one lands
|
||||
_treats = new TreatHud(_root);
|
||||
}
|
||||
|
||||
TreatHud _treats;
|
||||
|
||||
VisualElement _hints;
|
||||
readonly List<(Label cap, Act act)> _caps = new List<(Label, Act)>();
|
||||
|
||||
VisualElement HintRow(VisualElement parent, Act act, string label)
|
||||
{
|
||||
var row = UIK.El("hud-hint", parent);
|
||||
_caps.Add((UIK.Text(Binds.Cap(act), "key", row), act));
|
||||
UIK.Text(label, "t-small t-outline", row);
|
||||
return row;
|
||||
}
|
||||
|
||||
/// <summary>The key caps show the keys as now set, or hide if the player turned them off.</summary>
|
||||
public void RefreshHints()
|
||||
{
|
||||
foreach (var (cap, act) in _caps) cap.text = Binds.Cap(act);
|
||||
if (_hints != null) _hints.style.display = GameSettings.KeyHints ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
}
|
||||
|
||||
// ───────────────────────── static api ─────────────────────────
|
||||
|
||||
/// <summary>Every toast off the screen at once.</summary>
|
||||
public static void ClearToasts()
|
||||
{
|
||||
if (Instance != null) Instance._toasts.Clear();
|
||||
}
|
||||
|
||||
public static void Toast(string text, ToastKind kind = ToastKind.Info)
|
||||
{
|
||||
var h = Instance;
|
||||
if (h == null) return;
|
||||
// don't stack the same message
|
||||
foreach (var c in h._toasts.Children()) if (c is Label l && l.text == text) { UIK.Punch(l, 0.1f); return; }
|
||||
var t = UIK.Text(text, "toast t-body", h._toasts, false);
|
||||
t.AddToClassList(kind switch { ToastKind.Good => "toast-good", ToastKind.Warn => "toast-warn", ToastKind.Money => "toast-money", _ => "" });
|
||||
UIK.SlideIn(t, new Vector2(300, 0), 0f, 0.4f);
|
||||
Tween.Delay(t, 4f, () => UIK.Fade(t, 0f, 0.4f, () => t.RemoveFromHierarchy()));
|
||||
while (h._toasts.childCount > 5) h._toasts.RemoveAt(0);
|
||||
}
|
||||
|
||||
public static void OnLocalPlayerSpawned(PlayerAgent p)
|
||||
{
|
||||
var h = Instance;
|
||||
if (h == null) return;
|
||||
if (h._local != null && h._onTool != null) h._local.Tools.ToolChanged -= h._onTool;
|
||||
h._local = p;
|
||||
h._onTool = _ => h.RefreshHotbar(true);
|
||||
p.Tools.ToolChanged += h._onTool;
|
||||
var vm = Object.FindAnyObjectByType<ViewModel>(FindObjectsInactive.Include);
|
||||
if (vm) vm.Bind(p);
|
||||
}
|
||||
|
||||
public void OnGameStarted()
|
||||
{
|
||||
_shownMoney = _targetMoney = TeamState.Instance ? TeamState.Instance.Money.Value : 0;
|
||||
_beltKey = "";
|
||||
Banner(Loc.T("WELCOME TO HERBARIA-7"), Loc.T("Earth has run out of grass. Cut it, bundle it, ship it home."), 3.2f);
|
||||
}
|
||||
|
||||
public void OnGameEnded()
|
||||
{
|
||||
foreach (var t in _tags.Values) t.RemoveFromHierarchy();
|
||||
_tags.Clear();
|
||||
_local = null;
|
||||
}
|
||||
|
||||
// ───────────────────────── events ─────────────────────────
|
||||
|
||||
void OnMoney(double from, double to)
|
||||
{
|
||||
_targetMoney = to;
|
||||
if (to > from)
|
||||
{
|
||||
if (to - from >= 10d) { UIK.Punch(_money, 0.18f); UIK.Punch(_coin, 0.3f); }
|
||||
else if (Time.unscaledTime - _lastTick > 0.12f) UIK.Punch(_coin, 0.12f, 0.2f);
|
||||
}
|
||||
else if (to < from) UIK.Punch(_money, 0.12f);
|
||||
}
|
||||
|
||||
void OnDeposited(Vector3 at, double pay, double kg)
|
||||
{
|
||||
var ear = CameraFx.Cam ? CameraFx.Cam.transform.position : at;
|
||||
if ((ear - at).sqrMagnitude < 30f * 30f) Sfx.PlayAt("cash_register", at, 0.2f, 1f, 0.08f, 0.35f);
|
||||
FloatText(Loc.F("+{0} · {1} for Earth", UIK.Money(pay), GameDefs.Kilos(kg)), at + Planet.Up(at) * 0.8f, new Color(0.45f, 1f, 0.62f), 0.7f);
|
||||
if (_local != null && (at - _local.transform.position).sqrMagnitude < 196f) Receipt(pay, kg);
|
||||
}
|
||||
|
||||
/// <summary>What the depot took, added up while it keeps arriving.</summary>
|
||||
void Receipt(double pay, double kg)
|
||||
{
|
||||
if (Time.unscaledTime - _slipAt > 3f) _slipKg = _slipPay = 0d;
|
||||
_slipAt = Time.unscaledTime;
|
||||
_slipKg += kg;
|
||||
_slipPay += pay;
|
||||
var ts = TeamState.Instance;
|
||||
_receipt.Clear();
|
||||
UIK.Text(Loc.T("GRASS DEPOT"), "t-h2 t-dark", _receipt);
|
||||
ReceiptRow(Loc.T("Weight"), GameDefs.Kilos(_slipKg));
|
||||
ReceiptRow(Loc.T("Rate"), Loc.F("{0} / kg", UIK.Money(_slipPay / _slipKg)));
|
||||
ReceiptRow(Loc.T("Payout"), UIK.Money(_slipPay));
|
||||
if (ts) ReceiptRow(Loc.T("Shipped"), GameDefs.Kilos(ts.Shipped.Value));
|
||||
Tween.Kill(_receipt);
|
||||
_receipt.style.display = DisplayStyle.Flex;
|
||||
_receipt.style.opacity = 1f;
|
||||
var r = _receipt;
|
||||
Tween.Delay(r, 3.5f, () => UIK.Fade(r, 0f, 0.4f, () => { r.style.display = DisplayStyle.None; r.style.opacity = 1f; }));
|
||||
}
|
||||
|
||||
void ReceiptRow(string name, string value)
|
||||
{
|
||||
var row = UIK.El("receipt-row", _receipt);
|
||||
UIK.Text(name, "t-body t-muted", row, false);
|
||||
UIK.Text(value, "t-body t-dark", row, false);
|
||||
}
|
||||
|
||||
// ───────────────────────── widgets ─────────────────────────
|
||||
|
||||
public void Banner(string title, string sub, float hold)
|
||||
{
|
||||
_banner.Clear();
|
||||
var t = UIK.Text(title, "banner-text t-outline", _banner);
|
||||
UIK.PopIn(t, 0f, 0.5f);
|
||||
if (!string.IsNullOrEmpty(sub))
|
||||
{
|
||||
var s = UIK.Text(sub, "banner-sub t-outline", _banner);
|
||||
UIK.SlideIn(s, new Vector2(0, 30), 0.15f);
|
||||
}
|
||||
var b = _banner;
|
||||
Tween.Kill(b);
|
||||
b.style.opacity = 1f;
|
||||
Tween.Delay(b, hold, () => UIK.Fade(b, 0f, 0.35f, () => { b.Clear(); b.style.opacity = 1f; }));
|
||||
}
|
||||
|
||||
public Label FloatText(string text, Vector3 world, Color color, float scale = 1f)
|
||||
{
|
||||
var cam = CameraFx.Cam;
|
||||
if (!cam || _root.panel == null) return null;
|
||||
var vp = cam.WorldToViewportPoint(world);
|
||||
if (vp.z < 0.1f || vp.z > 80f) return null;
|
||||
Label l = null;
|
||||
foreach (var p in _floatPool) if (p.parent == null) { l = p; break; }
|
||||
if (l == null)
|
||||
{
|
||||
if (_floatPool.Count > 40) return null;
|
||||
l = UIK.Text("", "float-text t-outline");
|
||||
_floatPool.Add(l);
|
||||
}
|
||||
_world.Add(l);
|
||||
l.text = text;
|
||||
l.style.color = color;
|
||||
var start = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, world, cam) + new Vector2(Random.Range(-24f, 24f), Random.Range(-8f, 8f));
|
||||
Tween.Kill(l);
|
||||
Tween.Run(l, 1.1f, k =>
|
||||
{
|
||||
var pos = start + new Vector2(0, -110f * Easing.Apply(Ease.OutCubic, k));
|
||||
l.style.left = pos.x - 40;
|
||||
l.style.top = pos.y - 20;
|
||||
float pop = k < 0.15f ? Easing.Apply(Ease.OutBack, k / 0.15f) : 1f;
|
||||
l.style.scale = new Scale(Vector3.one * scale * pop);
|
||||
l.style.opacity = k < 0.7f ? 1f : 1f - (k - 0.7f) / 0.3f;
|
||||
}, Ease.Linear, 0f, () => l.RemoveFromHierarchy());
|
||||
return l;
|
||||
}
|
||||
|
||||
void RefreshHotbar(bool animate)
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
if (!ts || _local == null) return;
|
||||
var key = new System.Text.StringBuilder();
|
||||
var belt = _local.Tools.Belt;
|
||||
bool rebuilt = false;
|
||||
int slots = _local.BeltSlots.Value;
|
||||
foreach (var t in belt) key.Append((int)t).Append(',');
|
||||
key.Append('/').Append(slots);
|
||||
if (key.ToString() != _beltKey)
|
||||
{
|
||||
_beltKey = key.ToString();
|
||||
rebuilt = true;
|
||||
_hotbar.Clear();
|
||||
_slots.Clear();
|
||||
for (int n = 0; n < slots; n++)
|
||||
{
|
||||
var slot = UIK.El("slot", _hotbar);
|
||||
UIK.Text((n + 1).ToString(), "slot-key t-outline", slot);
|
||||
if (n >= belt.Count) { slot.AddToClassList("slot-empty"); continue; }
|
||||
var d = GameDefs.Tool(belt[n]);
|
||||
UIK.Img(AssetBank.I.Tex(d.icon), "slot-icon", slot);
|
||||
slot.tooltip = d.name;
|
||||
_slots[belt[n]] = slot;
|
||||
if (animate) UIK.PopIn(slot);
|
||||
}
|
||||
}
|
||||
foreach (var kv in _slots) kv.Value.EnableInClassList("slot-on", kv.Key == _local.Tools.Current);
|
||||
if (animate && !rebuilt && _slots.TryGetValue(_local.Tools.Current, out var cur)) UIK.Punch(cur, 0.15f);
|
||||
}
|
||||
|
||||
public void SetTabList(bool show)
|
||||
{
|
||||
bool visible = _players.style.display == DisplayStyle.Flex;
|
||||
if (show == visible) return;
|
||||
_players.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (!show) return;
|
||||
_players.Clear();
|
||||
var ts = TeamState.Instance;
|
||||
UIK.Text(Loc.T("GREENHAUL CREW"), "t-h1 t-dark", _players);
|
||||
if (ts)
|
||||
UIK.Text(Loc.F("{0} shipped to Earth · {1:0.0000}% of Herbaria-7 mown · {2} / {3} upgrades", GameDefs.Kilos(ts.Shipped.Value), ts.Mown01 * 100.0, ts.Installs, TeamState.TotalInstalls), "t-small t-muted wrap", _players, false);
|
||||
if (ts)
|
||||
UIK.Text(Loc.F("{0:N0} sectors clean · {1} / {2} stakes · {3} / {4} survey points", ts.Closed.Value, ts.FoundCount(false), Landmarks.Stakes, ts.FoundCount(true), Landmarks.Points), "t-small t-muted wrap", _players, false);
|
||||
foreach (var p in PlayerAgent.All)
|
||||
{
|
||||
var row = UIK.El("player-row", _players);
|
||||
var sw = UIK.El("swatch", row);
|
||||
sw.style.backgroundColor = p.Tint;
|
||||
var av = UIK.El("avatar", row);
|
||||
if (SteamManager.Initialized && p.SteamId.Value != 0)
|
||||
{
|
||||
var tex = SteamManager.GetAvatar(new Steamworks.CSteamID(p.SteamId.Value));
|
||||
if (tex) av.style.backgroundImage = new StyleBackground(tex);
|
||||
}
|
||||
var name = UIK.Text(p.IsOwner ? Loc.F("{0} (you)", p.DisplayName) : p.DisplayName, "t-h2 t-dark", row);
|
||||
name.style.flexGrow = 1;
|
||||
if (p.IsOwnedByServer) UIK.Text(Loc.T("HOST"), "key", row);
|
||||
}
|
||||
UIK.PopIn(_players, 0f, 0.25f);
|
||||
}
|
||||
|
||||
// ───────────────────────── per frame ─────────────────────────
|
||||
|
||||
public void Tick(bool active)
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
if (ts) _targetMoney = ts.Money.Value;
|
||||
if (System.Math.Abs(_shownMoney - _targetMoney) > 0.004)
|
||||
{
|
||||
double diff = _targetMoney - _shownMoney;
|
||||
_shownMoney += diff * Mathf.Min(1f, Time.unscaledDeltaTime * 9f);
|
||||
if (System.Math.Abs(_shownMoney - _targetMoney) < 0.02) _shownMoney = _targetMoney;
|
||||
if (diff > 0 && Time.unscaledTime - _lastTick > 0.07f) { _lastTick = Time.unscaledTime; Sfx.Play("coin_tick", 0.09f, 1.2f, 0.1f); }
|
||||
}
|
||||
_money.text = UIK.Money(_shownMoney);
|
||||
|
||||
if (!ts || _local == null) return;
|
||||
RefreshHotbar(false);
|
||||
UpdatePlanet(ts);
|
||||
UpdateTool(ts);
|
||||
UpdateBuild(active);
|
||||
UpdateAim(active);
|
||||
UpdateTags();
|
||||
UpdateDrops();
|
||||
UpdateHints(ts);
|
||||
_compass.Tick(_local, active);
|
||||
Achievements.Tick();
|
||||
}
|
||||
|
||||
void UpdatePlanet(TeamState ts)
|
||||
{
|
||||
int id = HexGrid.SectorAt(Planet.LocalUp);
|
||||
float clean = MowMap.Cleared(id);
|
||||
_sectorName.text = Crops.Name(Crops.At(id)).ToUpper(Loc.Culture) + " " + Loc.Num(id + 1);
|
||||
_sectorPct.text = Loc.F("{0:0.#}% mown", clean * 100f);
|
||||
int state = clean >= 1f ? 2 : clean > 0f ? 1 : 0;
|
||||
if (state != _hexState) { _hexState = state; _sectorHex.MarkDirtyRepaint(); }
|
||||
_planetPct.text = Loc.F("{0:0.0000}%", ts.Mown01 * 100.0);
|
||||
_planetSub.text = Loc.F("of Herbaria-7 · {0} shipped", GameDefs.Kilos(ts.Shipped.Value));
|
||||
}
|
||||
|
||||
void DrawHex(MeshGenerationContext ctx)
|
||||
{
|
||||
var r = _sectorHex.contentRect;
|
||||
var p = ctx.painter2D;
|
||||
p.fillColor = _hexState == 2 ? new Color(0.9f, 0.84f, 0.56f) : _hexState == 1 ? new Color(0.93f, 0.71f, 0.22f) : new Color(0.36f, 0.62f, 0.22f);
|
||||
p.strokeColor = new Color(0.165f, 0.13f, 0.08f);
|
||||
p.lineWidth = 4f;
|
||||
p.BeginPath();
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
float a = (i * 60f + 30f) * Mathf.Deg2Rad;
|
||||
var at = r.center + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * (r.width * 0.46f);
|
||||
if (i == 0) p.MoveTo(at); else p.LineTo(at);
|
||||
}
|
||||
p.ClosePath();
|
||||
p.Fill();
|
||||
p.Stroke();
|
||||
}
|
||||
|
||||
/// <summary>The plate shows the machine you're driving, or the tool in your hands.</summary>
|
||||
void UpdateTool(TeamState ts)
|
||||
{
|
||||
var tools = _local.Tools;
|
||||
var v = _local.Vehicle;
|
||||
bool has = v || tools.Current != ToolId.None;
|
||||
_plate.style.display = has ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_buildHint.style.display = tools.Belt.Contains(ToolId.Hammer) ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_bootsHint.style.display = _local.HasGear(GearId.Boots) ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_phoneUpHint.style.display = Phone.IsOut ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_phoneTurnHint.style.display = Phone.TakesWheel ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_chips.style.display = v ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (v)
|
||||
{
|
||||
_chipMow.EnableInClassList("drive-chip-on", v.Slurping.Value);
|
||||
_chipBoost.EnableInClassList("drive-chip-on", Ctl.Sprint);
|
||||
_chipCruise.EnableInClassList("drive-chip-on", v.Cruising);
|
||||
}
|
||||
if (!has) return;
|
||||
float kg = v ? v.Load : tools.Bin(tools.Current);
|
||||
float cap = v ? v.Capacity : tools.CurrentCap;
|
||||
bool bin = cap > 0f;
|
||||
_toolName.text = v ? v.Def.name : GameDefs.Tool(tools.Current).name;
|
||||
_gauge.style.display = bin ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_toolKg.style.display = bin ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (!bin) { _toolRate.text = ""; return; }
|
||||
float f = Mathf.Clamp01(kg / cap);
|
||||
_gaugeFill.style.height = Length.Percent(f * 100f);
|
||||
_toolKg.text = cap < 100f ? Loc.F("{0:0.00} / {1:0.##} KG", kg, cap) : Loc.F("{0:0} / {1:0} KG", kg, cap);
|
||||
bool full = f >= 0.999f;
|
||||
_plate.EnableInClassList("tank-full", full);
|
||||
_toolRate.text = v ? Loc.F("{0:0} KM/H", v.Body ? v.Body.linearVelocity.magnitude * 3.6f : 0f) : tools.IsCutting ? Loc.F("+{0:0.##} kg/s", tools.LastRate) : full ? Loc.T("FULL") : "";
|
||||
if (full && Time.unscaledTime - _tankPunch > 2f) { _tankPunch = Time.unscaledTime; UIK.Punch(_plate, 0.08f); }
|
||||
}
|
||||
|
||||
static readonly string[] CatNames = { Loc.N("SERVICES"), Loc.N("LOGISTICS"), Loc.N("PRODUCTION"), Loc.N("POWER"), Loc.N("STRUCTURES"), Loc.N("DECOR") };
|
||||
|
||||
void UpdateBuild(bool active)
|
||||
{
|
||||
var b = PlayerBuild.Local;
|
||||
bool show = active && b && b.Active;
|
||||
_build.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (!show) { _buildKey = -1; return; }
|
||||
var list = b.Available();
|
||||
var ts = TeamState.Instance;
|
||||
int key = (int)b.Category * 10000 + list.Count * 100 + b.Selected;
|
||||
if (key != _buildKey)
|
||||
{
|
||||
bool first = _buildKey < 0;
|
||||
_buildKey = key;
|
||||
_buildCats.Clear();
|
||||
for (int c = 0; c < CatNames.Length; c++)
|
||||
{
|
||||
if (!b.CategoryUnlocked((PieceCat)c)) continue;
|
||||
var chip = UIK.Text(Loc.T(CatNames[c]), "build-cat", _buildCats);
|
||||
if (c == (int)b.Category) chip.AddToClassList("build-cat-on");
|
||||
}
|
||||
_buildRow.Clear();
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
var d = list[i];
|
||||
var card = UIK.El("build-card", _buildRow);
|
||||
if (i == b.Selected) card.AddToClassList("build-card-on");
|
||||
UIK.Img(AssetBank.I.Tex(d.icon), "build-icon", card);
|
||||
UIK.Text(d.name, "build-name", card);
|
||||
UIK.Text(d.id == PieceId.Belt ? Loc.F("{0}/m", UIK.Money(d.price)) : UIK.Money(d.price), "build-price", card);
|
||||
if (first) UIK.PopIn(card, i * 0.03f, 0.3f);
|
||||
else if (i == b.Selected) UIK.Punch(card, 0.12f);
|
||||
}
|
||||
}
|
||||
var cur = b.Current;
|
||||
bool bad = !b.Valid && !string.IsNullOrEmpty(b.Reason);
|
||||
_buildReason.text = bad ? b.Reason : !string.IsNullOrEmpty(b.Note) ? b.Note : cur != null ? Loc.F("{0}: {1}", cur.name, cur.desc) : "";
|
||||
_buildReason.EnableInClassList("t-red", bad && !b.Target);
|
||||
}
|
||||
|
||||
void UpdateAim(bool active)
|
||||
{
|
||||
bool building = PlayerBuild.Local && PlayerBuild.Local.Active;
|
||||
// not over the phone held up in front of the face (it would sit on the Director's forehead)
|
||||
bool phoneUp = Phone.I && Phone.I.Mode == PhoneMode.Up;
|
||||
_crosshair.style.display = active && !phoneUp ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
var p = _local;
|
||||
var tools = p.Tools;
|
||||
string prompt = null, key = Binds.Cap(Act.Interact);
|
||||
bool hot = false;
|
||||
if (active && building) { }
|
||||
else if (active && p.Driving.Value)
|
||||
{
|
||||
// only when it matters: standing still, unloading, feeding a belt or full. The markers show where to go.
|
||||
var v = p.Vehicle;
|
||||
bool still = v && v.Body && v.Body.linearVelocity.magnitude < 0.6f;
|
||||
if (v && v.Def.bed > 0) { key = Binds.Cap(Act.MovePiece); prompt = v.Bed.Count > 0 ? Loc.T("Tip the bundles out behind") : still ? Loc.T("Empty bed · E with a bundle in your arms loads it") : null; }
|
||||
else if (v && v.Baling) { key = ""; prompt = Loc.T("Baling onto the belt…"); }
|
||||
else if (v && v.Unloading) { key = ""; prompt = Loc.T("Unloading…"); hot = true; }
|
||||
else if (v && v.Capacity > 0f && v.Load >= v.Capacity * 0.9f) { key = ""; prompt = Loc.T("Hopper full: drive to an UNLOAD marker"); }
|
||||
else if (v && VehicleShed.Near(v.transform.position)) { key = Binds.Cap(Act.Boots); prompt = Loc.T("Garage: upgrade this machine"); hot = true; }
|
||||
else if (still) prompt = Loc.T("Hop off [R] View");
|
||||
}
|
||||
else if (active && p.Grab.Holding)
|
||||
{
|
||||
bool bundle = p.Grab.Held && p.Grab.Held.GetComponent<Cargo>();
|
||||
if (bundle && p.AimInteractable is Depot)
|
||||
{
|
||||
prompt = Loc.T("Hand in this bundle");
|
||||
hot = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
key = Binds.Cap(Act.Use);
|
||||
prompt = bundle ? Loc.T("Throw it in the DEPOT or onto a belt [E] Drop [R] Turn") : Loc.T("Throw [E] Drop [R] Turn");
|
||||
}
|
||||
}
|
||||
else if (active && p.HasAim && p.AimHit.collider)
|
||||
{
|
||||
if (p.AimInteractable != null && (p.AimInteractable as Component) && p.AimInteractable.Prompt != null)
|
||||
{
|
||||
prompt = p.AimInteractable.Prompt;
|
||||
hot = p.AimInteractable.CanInteract;
|
||||
if (!hot) key = "";
|
||||
}
|
||||
var aimed = p.AimPiece;
|
||||
if (aimed && !building)
|
||||
{
|
||||
string tier = aimed.Upgrades != UpgradeKind.None ? aimed.Switched ? Loc.F("{0}, stopped", GameDefs.TierName(aimed.Tier.Value)) : GameDefs.TierName(aimed.Tier.Value) : "";
|
||||
prompt = Loc.F("{0} [T] Upgrades & settings", prompt ?? aimed.Def.name + (tier.Length > 0 ? " " + tier : ""));
|
||||
}
|
||||
else if (prompt == null && p.AimGrabbable && !p.AimGrabbable.IsHeld)
|
||||
{
|
||||
var c = p.AimGrabbable.GetComponent<Cargo>();
|
||||
prompt = !c ? Loc.T("Pick up") : Loc.F(c.kind == CargoKind.Hay ? Loc.N("Pick up hay ({0})") : c.kind == CargoKind.Brick ? Loc.N("Pick up pressed brick ({0})") : Loc.N("Pick up grass bundle ({0})"), GameDefs.Kilos(c.Kg.Value));
|
||||
hot = true;
|
||||
}
|
||||
}
|
||||
else if (active && !tools.IsCutting && Ctl.UseHeld && tools.OutOfRange && GameDefs.IsBlade(tools.Current))
|
||||
{
|
||||
key = "LMB";
|
||||
prompt = Loc.T("Too far — get closer to the grass");
|
||||
}
|
||||
|
||||
_crosshair.EnableInClassList("crosshair-hot", hot || tools.IsCutting);
|
||||
// the Director's words run along the same strip of screen: the hint waits until he hangs up
|
||||
if (DirectorCall.Busy) prompt = null;
|
||||
if (prompt != null)
|
||||
{
|
||||
_prompt.style.display = DisplayStyle.Flex;
|
||||
_promptKey.text = key;
|
||||
_promptKey.style.display = string.IsNullOrEmpty(key) ? DisplayStyle.None : DisplayStyle.Flex;
|
||||
ShowPrompt(prompt);
|
||||
}
|
||||
else { _prompt.style.display = DisplayStyle.None; _promptWas = null; }
|
||||
|
||||
var cam = CameraFx.Cam;
|
||||
bool blade = active && cam && tools.BladeOn && GameDefs.IsBlade(tools.Current) && !p.Driving.Value && _root.panel != null;
|
||||
_blade.style.display = blade ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (!blade) return;
|
||||
var side = cam.transform.right * TeamState.Instance.ToolWidth(tools.Current) * 0.5f;
|
||||
var a = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, tools.BladeAt - side, cam);
|
||||
var b = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, tools.BladeAt + side, cam);
|
||||
_blade.style.left = a.x;
|
||||
_blade.style.top = (a.y + b.y) * 0.5f - 3f;
|
||||
_blade.style.width = Mathf.Max(8f, b.x - a.x);
|
||||
}
|
||||
|
||||
readonly List<Label> _drops = new List<Label>();
|
||||
static Transform s_yard;
|
||||
|
||||
/// <summary>
|
||||
/// Driving with grass in the hopper: every place that takes it gets a marker, the base yard (paid at once) and each garage pad
|
||||
/// and Unload Bay (into the bin, out as bundles onto belts). Off screen they slide to the edge, so you know which way to turn.
|
||||
/// A baler also sees the belt starts it can feed.
|
||||
/// </summary>
|
||||
void UpdateDrops()
|
||||
{
|
||||
var v = _local.Vehicle;
|
||||
var cam = CameraFx.Cam;
|
||||
int n = 0;
|
||||
bool show = v && cam && _root.panel != null && v.Def.width > 0f && v.Load >= Mathf.Max(1f, v.Capacity * 0.25f) && !v.Unloading;
|
||||
_dropSpots.Clear();
|
||||
if (show)
|
||||
{
|
||||
if (!s_yard) { var d = GameObject.Find("DockZone"); s_yard = d ? d.transform : null; }
|
||||
if (s_yard) _dropSpots.Add((s_yard.position, Loc.T("Yard")));
|
||||
foreach (var pad in SiloPiece.Pads)
|
||||
if (pad && pad.IsSpawned && _dropSpots.Count < 12) _dropSpots.Add((pad.PadSpot, pad.PadName));
|
||||
// only the nearest one may sit on the screen edge; the rest show only when in view
|
||||
var from = v.transform.position;
|
||||
_dropSpots.Sort((x, y) => (x.at - from).sqrMagnitude.CompareTo((y.at - from).sqrMagnitude));
|
||||
_placed.Clear();
|
||||
foreach (var spot in _dropSpots) if (Drop(n, spot.at, spot.name, cam, from, n == 0)) n++;
|
||||
}
|
||||
for (int i = n; i < _drops.Count; i++) _drops[i].style.display = DisplayStyle.None;
|
||||
}
|
||||
|
||||
readonly List<(Vector3 at, string name)> _dropSpots = new List<(Vector3, string)>();
|
||||
readonly List<Rect> _placed = new List<Rect>();
|
||||
|
||||
/// <summary>A small pill over an unload spot: the name and the distance on one line, stacked clear of the others.</summary>
|
||||
bool Drop(int i, Vector3 at, string what, Camera cam, Vector3 from, bool nearest)
|
||||
{
|
||||
var world = at + Planet.Up(at) * 3f;
|
||||
var vp = cam.WorldToViewportPoint(world);
|
||||
bool behind = vp.z < 0f;
|
||||
if (behind) { vp.x = 1f - vp.x; vp.y = 1f - vp.y; }
|
||||
float W = _root.layout.width, H = _root.layout.height;
|
||||
if (float.IsNaN(W) || W < 10f) return false;
|
||||
var pos = new Vector2(vp.x * W, (1f - vp.y) * H);
|
||||
bool off = behind || pos.x < 0f || pos.x > W || pos.y < 0f || pos.y > H;
|
||||
if (off && !nearest) return false;
|
||||
if (i >= _drops.Count) _drops.Add(UIK.Text("", "drop-marker t-outline", _world, false));
|
||||
var tag = _drops[i];
|
||||
float dist = Vector3.Distance(at, from);
|
||||
tag.text = nearest ? Loc.F("UNLOAD · {0} {1:0} m", what, dist) : Loc.F("{0} {1:0} m", what, dist);
|
||||
tag.EnableInClassList("drop-marker-near", nearest);
|
||||
tag.style.display = DisplayStyle.Flex;
|
||||
if (off)
|
||||
{
|
||||
// slide along the edge toward it
|
||||
var c = new Vector2(W, H) * 0.5f;
|
||||
var d = pos - c;
|
||||
if (behind && d.sqrMagnitude < 1f) d = Vector2.down;
|
||||
float k = Mathf.Min((W * 0.5f - 70f) / Mathf.Max(1e-3f, Mathf.Abs(d.x)), (H * 0.5f - 40f) / Mathf.Max(1e-3f, Mathf.Abs(d.y)));
|
||||
pos = c + d * k;
|
||||
}
|
||||
float w = tag.resolvedStyle.width, h = tag.resolvedStyle.height;
|
||||
if (float.IsNaN(w)) w = 80f;
|
||||
if (float.IsNaN(h)) h = 20f;
|
||||
var r = new Rect(pos.x - w * 0.5f, pos.y - h, w, h);
|
||||
// stack upward clear of the pills already placed this frame
|
||||
for (int guard = 0; guard < 12; guard++)
|
||||
{
|
||||
bool hit = false;
|
||||
foreach (var q in _placed) if (q.Overlaps(r)) { r.y = q.y - h - 2f; hit = true; }
|
||||
if (!hit) break;
|
||||
}
|
||||
_placed.Add(r);
|
||||
tag.style.left = r.x;
|
||||
tag.style.top = r.y;
|
||||
tag.style.opacity = off ? 0.8f : 1f;
|
||||
tag.style.scale = new Scale(Vector3.one);
|
||||
return true;
|
||||
}
|
||||
|
||||
void UpdateTags()
|
||||
{
|
||||
var cam = CameraFx.Cam;
|
||||
foreach (var p in PlayerAgent.All)
|
||||
{
|
||||
if (!p || p.IsOwner) continue;
|
||||
if (!_tags.TryGetValue(p, out var tag))
|
||||
{
|
||||
tag = UIK.Text("", "nametag t-outline", _world);
|
||||
_tags[p] = tag;
|
||||
}
|
||||
tag.text = p.DisplayName;
|
||||
tag.style.color = Color.Lerp(p.Tint, Color.white, 0.35f);
|
||||
var head = p.transform.position + p.transform.up * 1.75f;
|
||||
var vp = cam ? cam.WorldToViewportPoint(head) : Vector3.back;
|
||||
bool visible = vp.z > 0.2f && vp.z < 60f;
|
||||
tag.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (!visible || _root.panel == null) continue;
|
||||
var pos = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, head, cam);
|
||||
float w = tag.resolvedStyle.width;
|
||||
tag.style.left = pos.x - (float.IsNaN(w) ? 50 : w * 0.5f);
|
||||
tag.style.top = pos.y - 20;
|
||||
float s = Mathf.Clamp(6f / vp.z, 0.55f, 1.1f);
|
||||
tag.style.scale = new Scale(new Vector3(s, s, 1));
|
||||
}
|
||||
var dead = new List<PlayerAgent>();
|
||||
foreach (var kv in _tags) if (!kv.Key || !PlayerAgent.All.Contains(kv.Key)) dead.Add(kv.Key);
|
||||
foreach (var d in dead) { _tags[d].RemoveFromHierarchy(); _tags.Remove(d); }
|
||||
}
|
||||
|
||||
/// <summary>"Battery Bank: 0.3 of 25 kWh, charging. Nothing to run [T] Upgrades" as a title, a line per sentence,
|
||||
/// and a chip per extra key. Rebuilt only when the words change.</summary>
|
||||
void ShowPrompt(string prompt)
|
||||
{
|
||||
if (prompt == _promptWas) return;
|
||||
_promptWas = prompt;
|
||||
var parts = prompt.Split(new[] { " [" }, System.StringSplitOptions.None);
|
||||
string main = parts[0].Trim();
|
||||
_promptMore.Clear();
|
||||
for (int i = 1; i < parts.Length; i++)
|
||||
{
|
||||
int close = parts[i].IndexOf(']');
|
||||
if (close <= 0) continue;
|
||||
var chip = UIK.El("prompt-chip", _promptMore);
|
||||
UIK.Text(parts[i].Substring(0, close), "key key-small", chip);
|
||||
UIK.Text(parts[i].Substring(close + 1).Trim(), "prompt-chip-text", chip, false);
|
||||
}
|
||||
_promptMore.style.display = _promptMore.childCount > 0 ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
string title = main, body = "";
|
||||
// translations: Chinese and Japanese write their own colon and full stop
|
||||
int colon = main.IndexOf(": "), wide = main.IndexOf(':'), cut = colon + 2;
|
||||
if (wide > 0 && (colon < 0 || wide < colon)) { colon = wide; cut = wide + 1; }
|
||||
if (colon > 0 && colon <= 32) { title = main.Substring(0, colon).TrimEnd(); body = main.Substring(cut); }
|
||||
var lines = new List<string>();
|
||||
foreach (var s in body.Split(new[] { ". ", "。" }, System.StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var t = s.Trim().TrimEnd('.');
|
||||
if (t.Length > 0) lines.Add(char.ToUpper(t[0], Loc.Culture) + t.Substring(1));
|
||||
}
|
||||
_promptTitle.text = title;
|
||||
_promptText.text = string.Join("\n", lines);
|
||||
_promptText.style.display = lines.Count > 0 ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
}
|
||||
|
||||
void UpdateHints(TeamState ts)
|
||||
{
|
||||
string hint = null, voice = null;
|
||||
var tools = _local.Tools;
|
||||
float cap = tools.CurrentCap;
|
||||
if (tools.Belt.Count == 0)
|
||||
{
|
||||
hint = Loc.T("Empty hands! Walk to the SUPPLY WALL on the west side of the deck and take the nail scissors (E).");
|
||||
voice = "asst_tools";
|
||||
}
|
||||
else if (ts.Shipped.Value < 5d)
|
||||
{
|
||||
if (GameDefs.IsBlade(tools.Current) && _local.Tank.Value >= cap - 0.01f)
|
||||
{
|
||||
hint = Loc.T("Container full! Press E at the DEPOT to hand it all in, or Q to tie a 1 kg bundle you can carry and throw.");
|
||||
voice = "asst_full";
|
||||
}
|
||||
else if (GameDefs.IsBlade(tools.Current) && _local.Tank.Value < 0.01f)
|
||||
{
|
||||
hint = Loc.T("Hop down to the meadow (SPACE at the railing) and HOLD LEFT CLICK: sweep the blade over the grass. Earth needs every blade of it.");
|
||||
voice = "asst_mow";
|
||||
}
|
||||
}
|
||||
else if (ts.Shipped.Value < 40d && ts.Money.Value >= 5d)
|
||||
{
|
||||
hint = Loc.T("Spend your cash: better tools at the SUPPLY WALL, upgrades at the CONSOLE. Mowers are sold at a GARAGE: build one with the Hammer.");
|
||||
voice = "asst_spend";
|
||||
}
|
||||
|
||||
// during the Director's call his words run along the same strip of screen: the hint waits until he hangs up
|
||||
bool show = hint != null && !(PlayerBuild.Local && PlayerBuild.Local.Active) && !_local.Driving.Value && !DirectorCall.Busy;
|
||||
bool shown = _hint.style.display == DisplayStyle.Flex;
|
||||
if (show && _hintText.text != hint)
|
||||
{
|
||||
_hintText.text = hint;
|
||||
_hint.style.display = DisplayStyle.Flex;
|
||||
UIK.PopIn(_hint, 0.1f);
|
||||
}
|
||||
// the assistant says it too, once she may talk (and again after a good while, if it's still up)
|
||||
if (show && voice != null) Assistant.Say(voice);
|
||||
else if (!show && shown) { _hint.style.display = DisplayStyle.None; _hintText.text = ""; }
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/Hud.cs.meta
Normal file
2
Assets/Scripts/UI/Hud.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 88304e14301a1764d990068e9eb6553c
|
||||
342
Assets/Scripts/UI/IntroCinematic.cs
Normal file
342
Assets/Scripts/UI/IntroCinematic.cs
Normal file
@ -0,0 +1,342 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The opening of a new game. Black, and echoes in an empty hangar; the black thins slowly onto the planks of the base; the
|
||||
/// phone rings and comes up, and the Director of G.R.A.S.S.A. gives his orders from Earth. Then a sharp look up at the
|
||||
/// meadow and hard cuts climbing higher and higher until the whole planet hangs in space, "we take grass very seriously",
|
||||
/// and a hard cut back into your own eyes: the game is yours. Space or Enter skips it.
|
||||
/// </summary>
|
||||
[DefaultExecutionOrder(10000)]
|
||||
public class IntroCinematic : MonoBehaviour
|
||||
{
|
||||
public static bool Running { get; private set; }
|
||||
/// <summary>The dev bot asks for it on a world that isn't new.</summary>
|
||||
public static bool Force;
|
||||
/// <summary>The trailer films it without the "Space: skip" in the corner.</summary>
|
||||
public static bool NoSkipHint;
|
||||
/// <summary>A game starting now could open on the film (not under a dev bot unless it asked).</summary>
|
||||
public static bool MightRun => Force || !CommandLine.Has("-autodemo");
|
||||
/// <summary>Whether the film plays has been decided for this game and it isn't playing: until then nobody talks.</summary>
|
||||
public static bool Settled { get; private set; }
|
||||
|
||||
/// <summary>The trailer: the film again, now, on whatever world this is.</summary>
|
||||
public static void Again()
|
||||
{
|
||||
Force = true;
|
||||
var i = FindAnyObjectByType<IntroCinematic>();
|
||||
if (!i) return;
|
||||
i._tried = false;
|
||||
i._since = Time.time - 1f;
|
||||
}
|
||||
|
||||
enum Shot { None, Eyes, Lens }
|
||||
Shot _shot;
|
||||
float _pitch, _pitchTo;
|
||||
Vector3 _eye, _look, _drift;
|
||||
float _shotT;
|
||||
float _near = 0.05f, _far = 14000f;
|
||||
Coroutine _run;
|
||||
bool _tried;
|
||||
float _since = -1f;
|
||||
VisualElement _black, _top, _bottom;
|
||||
Label _skip;
|
||||
|
||||
void Update()
|
||||
{
|
||||
var me = PlayerAgent.Local;
|
||||
var ts = TeamState.Instance;
|
||||
if (!me || !me.IsSpawned || !ts || !ts.IsSpawned) { _tried = false; _since = -1f; Settled = false; if (Running) Finish(); return; }
|
||||
if (_since < 0f) _since = Time.time;
|
||||
if (!_tried && Time.time - _since > 0.8f)
|
||||
{
|
||||
_tried = true;
|
||||
bool fresh = ts.Shipped.Value <= 0d && ts.Mown.Value <= 0d;
|
||||
bool bot = CommandLine.Has("-autodemo");
|
||||
if ((fresh && !bot) || Force) _run = StartCoroutine(Run());
|
||||
else { UIRoot.I?.ReleaseFade(0.6f); Settled = true; }
|
||||
}
|
||||
if (Running && Keyboard.current != null && (Keyboard.current.spaceKey.wasPressedThisFrame || Keyboard.current.enterKey.wasPressedThisFrame)) Skip();
|
||||
}
|
||||
|
||||
void Skip()
|
||||
{
|
||||
if (_run != null) StopCoroutine(_run);
|
||||
_run = null;
|
||||
DirectorCall.Abort();
|
||||
Sfx.Play("cut_return", 0.5f, 1f, 0f);
|
||||
Finish();
|
||||
}
|
||||
|
||||
IEnumerator Run()
|
||||
{
|
||||
Running = true;
|
||||
Force = false;
|
||||
Ctl.Cinematic = true;
|
||||
UIRoot.I.HideHud(true);
|
||||
Sfx.Duck(0f);
|
||||
Build();
|
||||
_black.style.opacity = 1f;
|
||||
_black.style.display = DisplayStyle.Flex;
|
||||
UIRoot.I.ReleaseFade(0f);
|
||||
// face the ramp: when the eyes come up they look out over the meadow, not at the cabin
|
||||
var me0 = PlayerAgent.Local;
|
||||
if (me0) me0.LookAt(Planet.Surface(new Vector3(0f, 0f, -40f)) + Planet.Up(me0.transform.position) * 1.5f);
|
||||
// the shots from the air want the meadow furry far out
|
||||
GrassField.FurReach = 3.5f;
|
||||
_skip.style.display = NoSkipHint ? DisplayStyle.None : DisplayStyle.Flex;
|
||||
Phone.I?.Show(PhoneMode.Away);
|
||||
|
||||
// 1. black, and the echo of an empty hangar
|
||||
_shot = Shot.Eyes;
|
||||
_pitch = _pitchTo = 64f;
|
||||
Sfx.Play("intro_echo", 0.9f, 1f, 0f);
|
||||
yield return new WaitForSeconds(2.4f);
|
||||
|
||||
// 2. the black thins slowly onto the floor of the base
|
||||
Fade(_black, 0f, 3.6f);
|
||||
yield return new WaitForSeconds(3.0f);
|
||||
|
||||
// 3. the phone rings; it comes up to the face, and he's on it
|
||||
Sfx.Play("phone_ring", 0.5f, 1f, 0f);
|
||||
yield return new WaitForSeconds(1.2f);
|
||||
Phone.I?.Show(PhoneMode.Up);
|
||||
// still looking down at the planks over the phone: the world waits for the end of the call
|
||||
_pitchTo = 58f;
|
||||
yield return new WaitForSeconds(0.7f);
|
||||
yield return DirectorCall.Speak("dir_intro", true);
|
||||
|
||||
// 4. the phone goes down and the head comes up, quick but smooth, onto the meadow; then cuts climbing until
|
||||
// the planet hangs in space
|
||||
Phone.I?.Show(PhoneMode.Away);
|
||||
yield return new WaitForSeconds(0.15f);
|
||||
Bars(true);
|
||||
Sfx.Play("cut_whoosh_1", 0.38f, 1.15f, 0f);
|
||||
Lift(-3f, 0.6f);
|
||||
yield return new WaitForSeconds(0.6f);
|
||||
CameraFx.FovKick(-6f);
|
||||
yield return new WaitForSeconds(1.0f);
|
||||
var me = PlayerAgent.Local;
|
||||
var cam = CameraFx.Cam;
|
||||
Vector3 eye = cam ? cam.transform.parent ? cam.transform.parent.position : cam.transform.position : me.transform.position;
|
||||
var up = Planet.Up(eye);
|
||||
var fwd = Vector3.ProjectOnPlane(me.transform.forward, up).normalized;
|
||||
|
||||
var home = Planet.OnSurface(Vector3.up);
|
||||
var away = -fwd;
|
||||
var side = Vector3.Cross(up, fwd);
|
||||
(float h, float back, float hold)[] climb = { (9f, 16f, 0.55f), (110f, 150f, 0.5f), (420f, 380f, 0.5f), (1400f, 700f, 0.55f) };
|
||||
for (int i = 0; i < climb.Length; i++)
|
||||
{
|
||||
var (h, back, hold) = climb[i];
|
||||
Sfx.Play(i % 2 == 0 ? "cut_whoosh_2" : "cut_whoosh_1", 0.42f, 1f + i * 0.07f, 0f);
|
||||
var at = Planet.Surface(home + away * back + side * back * 0.35f);
|
||||
var e = at + Planet.Up(at) * h;
|
||||
Lens(e, home, Vector3.ProjectOnPlane(home - e, Planet.Up(e)).normalized * h * 0.05f);
|
||||
CameraFx.FovKick(4f);
|
||||
yield return new WaitForSeconds(hold);
|
||||
}
|
||||
|
||||
// the whole ball, and the agency's motto over it
|
||||
Sfx.Play("cut_whoosh_2", 0.5f, 0.8f, 0f);
|
||||
Sfx.Play("space_rumble", 0.85f, 1f, 0f);
|
||||
var tilt = (Vector3.up + away * 0.55f + side * 0.25f).normalized;
|
||||
var far = Planet.Center + tilt * (Planet.Radius * 2.54f); // the same framing on a smaller ball
|
||||
Lens(far, Planet.Center, side * 60f);
|
||||
Space(true, far);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
yield return DirectorCall.Speak("dir_intro_tag", false);
|
||||
yield return new WaitForSeconds(0.7f);
|
||||
|
||||
// 5. the hard cut back, and it's yours
|
||||
Sfx.Play("cut_return", 0.55f, 1f, 0f);
|
||||
_run = null;
|
||||
Finish();
|
||||
CameraFx.FovKick(14f);
|
||||
CameraFx.Shake(0.45f);
|
||||
}
|
||||
|
||||
void Finish()
|
||||
{
|
||||
Running = false;
|
||||
Settled = true;
|
||||
_liftAt = -1f;
|
||||
Space(false, Vector3.zero);
|
||||
GrassField.FurReach = 1f;
|
||||
_shot = Shot.None;
|
||||
var cam = CameraFx.Cam;
|
||||
if (cam) { cam.nearClipPlane = 0.05f; cam.farClipPlane = 14000f; }
|
||||
if (cam && cam.transform.parent) cam.transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
|
||||
Ctl.Cinematic = false;
|
||||
if (UIRoot.I) UIRoot.I.HideHud(false);
|
||||
// the assistant says hello once the film is over: from here on she's the one with the hints
|
||||
Assistant.Say("asst_hello");
|
||||
Sfx.Duck(1f);
|
||||
if (_black != null) { Tween.Kill(_black); _black.style.display = DisplayStyle.None; }
|
||||
if (_skip != null) _skip.style.display = DisplayStyle.None;
|
||||
Bars(false);
|
||||
if (Phone.I && Phone.I.Mode != PhoneMode.Away) Phone.I.Show(PhoneMode.Away);
|
||||
}
|
||||
|
||||
// the head coming up: from where it was to _pitchTo in a set time, eased in and out
|
||||
float _liftAt = -1f, _liftFrom, _liftFor;
|
||||
|
||||
void Lift(float to, float seconds)
|
||||
{
|
||||
_liftFrom = _pitch;
|
||||
_pitchTo = to;
|
||||
_liftAt = Time.time;
|
||||
_liftFor = seconds;
|
||||
}
|
||||
|
||||
void Lens(Vector3 eye, Vector3 look, Vector3 drift)
|
||||
{
|
||||
_shot = Shot.Lens;
|
||||
_eye = eye; _look = look; _drift = drift;
|
||||
_shotT = 0f;
|
||||
bool high = Planet.Altitude(eye) > 700f;
|
||||
_near = high ? 4f : 0.05f;
|
||||
_far = high ? 60000f : 14000f;
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
var cam = CameraFx.Cam;
|
||||
if (!cam || _shot == Shot.None) return;
|
||||
var rig = cam.transform.parent;
|
||||
if (_shot == Shot.Eyes && rig)
|
||||
{
|
||||
// our own eyes, held looking down at the planks
|
||||
if (_liftAt >= 0f)
|
||||
{
|
||||
float k = Mathf.Clamp01((Time.time - _liftAt) / _liftFor);
|
||||
// quick off the mark and settling softly: an ease in-out skewed toward the start
|
||||
k = Mathf.Pow(k, 0.7f);
|
||||
k = k * k * (3f - 2f * k);
|
||||
_pitch = Mathf.Lerp(_liftFrom, _pitchTo, k);
|
||||
if (Time.time - _liftAt >= _liftFor) _liftAt = -1f;
|
||||
}
|
||||
else _pitch = Mathf.Lerp(_pitch, _pitchTo, Time.deltaTime * 1.6f);
|
||||
var up = Planet.Up(rig.position);
|
||||
var fwd = Vector3.ProjectOnPlane(rig.forward, up).normalized;
|
||||
if (fwd.sqrMagnitude < 0.01f) fwd = Vector3.ProjectOnPlane(Vector3.forward, up).normalized;
|
||||
var turn = Quaternion.AngleAxis(_pitch, Vector3.Cross(up, fwd)) * Quaternion.LookRotation(fwd, up);
|
||||
cam.transform.SetPositionAndRotation(rig.position, turn);
|
||||
}
|
||||
else if (_shot == Shot.Lens)
|
||||
{
|
||||
// each shot creeps a little, so a cut lands on something alive
|
||||
_shotT += Time.deltaTime;
|
||||
var e = _eye + _drift * _shotT;
|
||||
cam.transform.SetPositionAndRotation(e, Quaternion.LookRotation(_look - e, Planet.Up(e)));
|
||||
}
|
||||
cam.nearClipPlane = _near;
|
||||
cam.farClipPlane = _far;
|
||||
}
|
||||
|
||||
// ───────── out in space: black sky and stars instead of the day's blue ─────────
|
||||
|
||||
ParticleSystem _stars;
|
||||
CameraClearFlags _clear;
|
||||
Color _clearColour;
|
||||
bool _inSpace;
|
||||
|
||||
void Space(bool on, Vector3 eye)
|
||||
{
|
||||
var cam = CameraFx.Cam;
|
||||
if (!cam || on == _inSpace) return;
|
||||
_inSpace = on;
|
||||
if (on)
|
||||
{
|
||||
_clear = cam.clearFlags;
|
||||
_clearColour = cam.backgroundColor;
|
||||
cam.clearFlags = CameraClearFlags.SolidColor;
|
||||
cam.backgroundColor = new Color(0.008f, 0.012f, 0.03f);
|
||||
if (!_stars)
|
||||
{
|
||||
var go = new GameObject("IntroStars");
|
||||
_stars = go.AddComponent<ParticleSystem>();
|
||||
_stars.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
|
||||
var main = _stars.main;
|
||||
main.playOnAwake = false; main.loop = false;
|
||||
main.startLifetime = 60f; main.startSpeed = 0f;
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||||
main.maxParticles = 2000;
|
||||
var em = _stars.emission; em.enabled = false;
|
||||
var sh = _stars.shape; sh.enabled = false;
|
||||
var r = go.GetComponent<ParticleSystemRenderer>();
|
||||
r.sharedMaterial = AssetBank.I.Mat("FX_Sparkle") ?? AssetBank.I.Mat("FX_Soft");
|
||||
r.maxParticleSize = 0.02f;
|
||||
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
_stars.Play();
|
||||
}
|
||||
_stars.Clear();
|
||||
for (int i = 0; i < 1400; i++)
|
||||
{
|
||||
var d = Random.onUnitSphere;
|
||||
float far = 30000f;
|
||||
var ep = new ParticleSystem.EmitParams
|
||||
{
|
||||
position = eye + d * far,
|
||||
startSize = far * Random.Range(0.0012f, 0.0034f),
|
||||
startColor = Color.Lerp(new Color(0.75f, 0.85f, 1f), new Color(1f, 0.92f, 0.8f), Random.value) * Random.Range(0.55f, 1f),
|
||||
applyShapeToPosition = false,
|
||||
};
|
||||
_stars.Emit(ep, 1);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
cam.clearFlags = _clear;
|
||||
cam.backgroundColor = _clearColour;
|
||||
if (_stars) _stars.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
// ───────── the screen ─────────
|
||||
|
||||
void Build()
|
||||
{
|
||||
var root = UIRoot.I.Cinema;
|
||||
if (_black == null || _black.panel == null)
|
||||
{
|
||||
_black = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
_black.AddToClassList("cinema-black");
|
||||
root.Add(_black);
|
||||
_top = Bar(root, true);
|
||||
_bottom = Bar(root, false);
|
||||
_skip = UIK.Text(Loc.T("SPACE skip"), "cinema-skip t-outline", root, false);
|
||||
}
|
||||
// the call's captions go over the black and the bars
|
||||
_black.SendToBack();
|
||||
}
|
||||
|
||||
static VisualElement Bar(VisualElement root, bool top)
|
||||
{
|
||||
var b = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
b.AddToClassList("cinema-bars");
|
||||
if (top) b.style.top = 0; else b.style.bottom = 0;
|
||||
b.style.display = DisplayStyle.None;
|
||||
root.Add(b);
|
||||
b.SendToBack();
|
||||
return b;
|
||||
}
|
||||
|
||||
void Bars(bool on)
|
||||
{
|
||||
if (_top == null) return;
|
||||
_top.style.display = _bottom.style.display = on ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
}
|
||||
|
||||
static void Fade(VisualElement e, float to, float seconds)
|
||||
{
|
||||
float from = e.resolvedStyle.opacity;
|
||||
Tween.Kill(e);
|
||||
Tween.Run(e, seconds, k => e.style.opacity = Mathf.Lerp(from, to, k), Ease.InOutQuad);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/IntroCinematic.cs.meta
Normal file
2
Assets/Scripts/UI/IntroCinematic.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a24f5763471d8db4899ae9f22c03c581
|
||||
283
Assets/Scripts/UI/MapScreen.cs
Normal file
283
Assets/Scripts/UI/MapScreen.cs
Normal file
@ -0,0 +1,283 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// M: the globe of Herbaria-7. Drag turns it, the wheel zooms in until every sector is its own hexagon. Sectors nobody
|
||||
/// has touched are the meadow, begun ones gold, finished ones the pale straw of mown ground.
|
||||
/// </summary>
|
||||
public class MapScreen
|
||||
{
|
||||
const float MaxZoom = 60f, HexZoom = 14f;
|
||||
const int MaxHexes = 1400;
|
||||
|
||||
public VisualElement Card { get; }
|
||||
readonly VisualElement _chart;
|
||||
readonly Label _stats;
|
||||
Quaternion _view;
|
||||
float _zoom;
|
||||
bool _dragging;
|
||||
Vector2 _last;
|
||||
|
||||
static readonly Color Meadow = new Color(0.27f, 0.47f, 0.17f);
|
||||
static readonly Color Space = new Color(0.09f, 0.11f, 0.13f);
|
||||
static readonly Color Lines = new Color(1f, 1f, 1f, 0.1f);
|
||||
static readonly Color Rim = new Color(0.72f, 0.86f, 0.5f, 0.8f);
|
||||
static readonly Color Begun = new Color(0.93f, 0.71f, 0.22f);
|
||||
static readonly Color Done = new Color(0.9f, 0.84f, 0.56f);
|
||||
static readonly Color Base = new Color(0.78f, 0.28f, 0.18f);
|
||||
static readonly Color Stake = new Color(1f, 0.45f, 0.35f);
|
||||
static readonly Color Robot = new Color(0.55f, 0.8f, 1f);
|
||||
static readonly Color Station = new Color(1f, 0.85f, 0.3f);
|
||||
static readonly Color Border = new Color(0.1f, 0.14f, 0.05f, 0.5f);
|
||||
|
||||
static readonly Dictionary<int, Vector3[]> s_corners = new Dictionary<int, Vector3[]>();
|
||||
readonly HashSet<int> _seen = new HashSet<int>();
|
||||
readonly Queue<int> _queue = new Queue<int>();
|
||||
|
||||
public MapScreen(VisualElement layer, Action close, float zoom = 1f)
|
||||
{
|
||||
_zoom = zoom;
|
||||
Card = UIK.El("card rig-map", layer);
|
||||
var header = UIK.El("card-header", Card);
|
||||
UIK.Text("HERBARIA-7", "t-h1 t-dark", header);
|
||||
_stats = UIK.Text("", "t-body t-dark", header, false);
|
||||
UIK.Btn("X", close, "btn btn-red btn-small", header);
|
||||
_chart = UIK.El("map-chart", Card);
|
||||
_chart.pickingMode = PickingMode.Position;
|
||||
_chart.style.overflow = Overflow.Hidden;
|
||||
_chart.generateVisualContent += Draw;
|
||||
_chart.RegisterCallback<WheelEvent>(e => { _zoom = Mathf.Clamp(_zoom * (e.delta.y > 0 ? 0.8f : 1.25f), 1f, MaxZoom); _chart.MarkDirtyRepaint(); });
|
||||
_chart.RegisterCallback<PointerDownEvent>(e => { _dragging = true; _last = e.position; _chart.CapturePointer(e.pointerId); });
|
||||
_chart.RegisterCallback<PointerUpEvent>(e => { _dragging = false; _chart.ReleasePointer(e.pointerId); });
|
||||
_chart.RegisterCallback<PointerMoveEvent>(e =>
|
||||
{
|
||||
if (!_dragging) return;
|
||||
var d = (Vector2)e.position - _last;
|
||||
_last = e.position;
|
||||
float k = 57.3f / (Radius * _zoom);
|
||||
_view = Quaternion.Euler(d.y * k, d.x * k, 0f) * _view;
|
||||
_chart.MarkDirtyRepaint();
|
||||
});
|
||||
var legend = UIK.El("map-legend", Card);
|
||||
Key(legend, Meadow, Loc.T("Untouched"));
|
||||
Key(legend, Begun, Loc.T("Started"));
|
||||
Key(legend, Done, Loc.T("Mown"));
|
||||
Key(legend, Base, Loc.T("Base"));
|
||||
Key(legend, Stake, Loc.T("Stake or point done"));
|
||||
Key(legend, Robot, Loc.T("Robot"));
|
||||
Key(legend, Station, Loc.T("Station"));
|
||||
UIK.Text(Loc.T("DRAG turn · WHEEL zoom · M close"), "t-small t-muted", legend, false);
|
||||
|
||||
var me = PlayerAgent.Local;
|
||||
var up = me ? Planet.Up(me.transform.position) : Vector3.up;
|
||||
var north = Vector3.ProjectOnPlane(Vector3.up, up);
|
||||
if (north.sqrMagnitude < 1e-4f) north = Vector3.forward;
|
||||
_view = Quaternion.Inverse(Quaternion.LookRotation(up, north));
|
||||
Refresh();
|
||||
_chart.schedule.Execute(Refresh).Every(300);
|
||||
}
|
||||
|
||||
void Refresh()
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
MowMap.Count();
|
||||
if (ts) _stats.text = Loc.F("{0:N0} started · {1:N0} mown · {2:0.0000}% of the planet", MowMap.Started, ts.Closed.Value, ts.Mown01 * 100.0);
|
||||
_chart.MarkDirtyRepaint();
|
||||
}
|
||||
|
||||
static void Key(VisualElement parent, Color c, string label)
|
||||
{
|
||||
var row = UIK.El("map-key", parent);
|
||||
UIK.El("swatch", row).style.backgroundColor = c;
|
||||
UIK.Text(label, "t-small t-dark", row, false);
|
||||
}
|
||||
|
||||
float Radius
|
||||
{
|
||||
get
|
||||
{
|
||||
var r = _chart.contentRect;
|
||||
return Mathf.Max(40f, Mathf.Min(r.width, r.height) * 0.47f);
|
||||
}
|
||||
}
|
||||
|
||||
Vector2 Screen(Vector3 d, out bool front)
|
||||
{
|
||||
var v = _view * d;
|
||||
front = v.z > 0f;
|
||||
return _chart.contentRect.center + new Vector2(v.x, -v.y) * Radius * _zoom;
|
||||
}
|
||||
|
||||
/// <summary>A sector's corners, in order round its middle.</summary>
|
||||
static Vector3[] Corners(HexGrid.Sector s)
|
||||
{
|
||||
if (s_corners.TryGetValue(s.id, out var c)) return c;
|
||||
var near = new List<Vector3>();
|
||||
foreach (int n in s.neighbours) near.Add(HexGrid.Get(n).c);
|
||||
near.Sort((a, b) => Angle(s, a).CompareTo(Angle(s, b)));
|
||||
c = new Vector3[near.Count];
|
||||
for (int i = 0; i < c.Length; i++) c[i] = (s.c + near[i] + near[(i + 1) % c.Length]).normalized;
|
||||
s_corners[s.id] = c;
|
||||
return c;
|
||||
}
|
||||
|
||||
static float Angle(HexGrid.Sector s, Vector3 n) => Mathf.Atan2(Vector3.Dot(n - s.c, s.e2), Vector3.Dot(n - s.c, s.e1));
|
||||
|
||||
void Hex(Painter2D p, HexGrid.Sector s)
|
||||
{
|
||||
var c = Corners(s);
|
||||
p.BeginPath();
|
||||
p.MoveTo(Screen(c[0], out _));
|
||||
for (int i = 1; i < c.Length; i++) p.LineTo(Screen(c[i], out _));
|
||||
p.ClosePath();
|
||||
}
|
||||
|
||||
static Color Shade(MowMap.Mask m) => m == null || !m.keep ? Meadow : m.done ? Done : Begun;
|
||||
|
||||
void Draw(MeshGenerationContext ctx)
|
||||
{
|
||||
var r = _chart.contentRect;
|
||||
if (r.width < 4f) return;
|
||||
var ts = TeamState.Instance;
|
||||
|
||||
var p = ctx.painter2D;
|
||||
p.fillColor = Space;
|
||||
p.BeginPath(); p.MoveTo(new Vector2(r.xMin, r.yMin)); p.LineTo(new Vector2(r.xMax, r.yMin)); p.LineTo(new Vector2(r.xMax, r.yMax)); p.LineTo(new Vector2(r.xMin, r.yMax)); p.ClosePath(); p.Fill();
|
||||
float size = Radius * _zoom;
|
||||
p.fillColor = Meadow;
|
||||
p.BeginPath(); p.Arc(r.center, size, 0f, 360f); p.Fill();
|
||||
|
||||
if (_zoom >= HexZoom) Hexes(p, r);
|
||||
else Dots(p);
|
||||
Lattice(p);
|
||||
p.strokeColor = Rim;
|
||||
p.lineWidth = 3f;
|
||||
p.BeginPath(); p.Arc(r.center, size, 0f, 360f); p.Stroke();
|
||||
|
||||
// what stands on the ball
|
||||
Dot(p, Vector3.up, 7f, Base);
|
||||
if (ts)
|
||||
{
|
||||
foreach (int id in ts.Found)
|
||||
Dot(p, Planet.Up(Landmarks.Spot(id)), 4f, Stake);
|
||||
for (int i = 1; i < Stations.Count; i++)
|
||||
if (ts.StationOpen(i)) Dot(p, Stations.Dir(i), 6f, Station);
|
||||
}
|
||||
foreach (var m in Mowbot.All)
|
||||
if (m) Dot(p, Planet.Up(m.At.Value), 4f, Robot);
|
||||
foreach (var v in Vehicle.All)
|
||||
if (v) Arrow(p, v.transform, 7f, new Color(0.96f, 0.9f, 0.72f));
|
||||
foreach (var pl in PlayerAgent.All)
|
||||
if (pl) Arrow(p, pl.transform, pl.IsOwner ? 11f : 8f, pl.Tint);
|
||||
}
|
||||
|
||||
void Dot(Painter2D p, Vector3 dir, float size, Color col)
|
||||
{
|
||||
var at = Screen(dir, out bool front);
|
||||
if (!front) return;
|
||||
p.fillColor = col;
|
||||
p.strokeColor = Color.white;
|
||||
p.lineWidth = 2f;
|
||||
p.BeginPath(); p.Arc(at, size, 0f, 360f); p.Fill(); p.Stroke();
|
||||
}
|
||||
|
||||
/// <summary>Far out each worked sector is a speck.</summary>
|
||||
void Dots(Painter2D p)
|
||||
{
|
||||
float size = Mathf.Max(1.5f, 13f / Planet.Radius * Radius * _zoom);
|
||||
foreach (bool done in new[] { false, true })
|
||||
{
|
||||
p.fillColor = done ? Done : Begun;
|
||||
p.BeginPath();
|
||||
foreach (var m in MowMap.All)
|
||||
{
|
||||
if (!m.keep || m.done != done) continue;
|
||||
var at = Screen(m.s.c, out bool front);
|
||||
if (!front) continue;
|
||||
p.MoveTo(at + new Vector2(size, 0f));
|
||||
p.Arc(at, size, 0f, 360f);
|
||||
}
|
||||
p.Fill();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Close up, every sector in view, walking out from the one in the middle.</summary>
|
||||
void Hexes(Painter2D p, Rect r)
|
||||
{
|
||||
var masks = new Dictionary<int, MowMap.Mask>();
|
||||
foreach (var m in MowMap.All) masks[m.s.id] = m;
|
||||
_seen.Clear();
|
||||
_queue.Clear();
|
||||
int first = HexGrid.SectorAt(Quaternion.Inverse(_view) * Vector3.forward);
|
||||
_queue.Enqueue(first);
|
||||
_seen.Add(first);
|
||||
var view = new Rect(r.x - 40f, r.y - 40f, r.width + 80f, r.height + 80f);
|
||||
p.strokeColor = Border;
|
||||
p.lineWidth = 1f;
|
||||
int drawn = 0;
|
||||
while (_queue.Count > 0 && drawn < MaxHexes)
|
||||
{
|
||||
var s = HexGrid.Get(_queue.Dequeue());
|
||||
var at = Screen(s.c, out bool front);
|
||||
if (!front || !view.Contains(at)) continue;
|
||||
drawn++;
|
||||
masks.TryGetValue(s.id, out var m);
|
||||
p.fillColor = Shade(m);
|
||||
Hex(p, s);
|
||||
p.Fill();
|
||||
p.Stroke();
|
||||
foreach (int n in s.neighbours)
|
||||
if (_seen.Add(n)) _queue.Enqueue(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Latitude and longitude every 30°.</summary>
|
||||
void Lattice(Painter2D p)
|
||||
{
|
||||
p.strokeColor = Lines;
|
||||
p.lineWidth = 1.5f;
|
||||
for (int lat = -60; lat <= 60; lat += 30) Trace(p, t => Planet.FromLatLon(lat, t * 360f));
|
||||
for (int lon = 0; lon < 360; lon += 30) Trace(p, t => Planet.FromLatLon(-90f + t * 180f, lon));
|
||||
}
|
||||
|
||||
void Trace(Painter2D p, Func<float, Vector3> along)
|
||||
{
|
||||
bool open = false;
|
||||
p.BeginPath();
|
||||
for (int i = 0; i <= 60; i++)
|
||||
{
|
||||
var at = Screen(along(i / 60f), out bool front);
|
||||
if (!front) { open = false; continue; }
|
||||
if (open) p.LineTo(at); else p.MoveTo(at);
|
||||
open = true;
|
||||
}
|
||||
p.Stroke();
|
||||
}
|
||||
|
||||
void Arrow(Painter2D p, Transform t, float size, Color col)
|
||||
{
|
||||
var d = Planet.Up(t.position);
|
||||
var at = Screen(d, out bool front);
|
||||
if (!front) return;
|
||||
var ahead = Screen((d + t.forward * 0.02f).normalized, out _);
|
||||
var f = (ahead - at).normalized;
|
||||
if (f.sqrMagnitude < 0.01f) f = Vector2.up;
|
||||
var side = new Vector2(-f.y, f.x);
|
||||
p.fillColor = col;
|
||||
p.strokeColor = Color.white;
|
||||
p.lineWidth = 2f;
|
||||
p.BeginPath();
|
||||
p.MoveTo(at + f * size);
|
||||
p.LineTo(at - f * size * 0.7f + side * size * 0.7f);
|
||||
p.LineTo(at - f * size * 0.35f);
|
||||
p.LineTo(at - f * size * 0.7f - side * size * 0.7f);
|
||||
p.ClosePath();
|
||||
p.Fill();
|
||||
p.Stroke();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/MapScreen.cs.meta
Normal file
2
Assets/Scripts/UI/MapScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f315608970728448bb08f6b0766b20c
|
||||
248
Assets/Scripts/UI/NotebookScreen.cs
Normal file
248
Assets/Scripts/UI/NotebookScreen.cs
Normal file
@ -0,0 +1,248 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>H: the crew's spiral notebook. Each chapter is a tab; lines starting with # are headings, and everything that
|
||||
/// has a number in the game is read from the game, so the notes can't go out of date.</summary>
|
||||
public class NotebookScreen
|
||||
{
|
||||
public VisualElement Card { get; }
|
||||
readonly VisualElement _tabs, _page;
|
||||
readonly List<Button> _buttons = new List<Button>();
|
||||
int _open;
|
||||
|
||||
static readonly (string title, Func<IEnumerable<string>> lines)[] Chapters =
|
||||
{
|
||||
(Loc.N("Start Here"), StartHere),
|
||||
(Loc.N("Tools"), Tools),
|
||||
(Loc.N("Bundles"), Bundles),
|
||||
(Loc.N("Upgrades"), Upgrades),
|
||||
(Loc.N("Building"), Building),
|
||||
(Loc.N("Power"), Power),
|
||||
(Loc.N("Production"), Production),
|
||||
(Loc.N("Machines"), Machines),
|
||||
(Loc.N("Robots"), Robots),
|
||||
(Loc.N("Sectors"), Sectors),
|
||||
(Loc.N("Keys"), Keys),
|
||||
};
|
||||
|
||||
public NotebookScreen(VisualElement layer, Action close)
|
||||
{
|
||||
Card = UIK.El("card notebook", layer);
|
||||
var header = UIK.El("card-header", Card);
|
||||
UIK.Text(Loc.T("CREW NOTEBOOK"), "t-h1 t-dark", header);
|
||||
UIK.Btn("X", close, "btn btn-red btn-small", header);
|
||||
var body = UIK.El("notebook-body", Card);
|
||||
_tabs = UIK.El("notebook-tabs", body);
|
||||
var spiral = UIK.El("notebook-spiral", body);
|
||||
for (int i = 0; i < 16; i++) UIK.El("notebook-ring", spiral);
|
||||
var scroll = new ScrollView(ScrollViewMode.Vertical);
|
||||
scroll.AddToClassList("notebook-page");
|
||||
body.Add(scroll);
|
||||
_page = scroll.contentContainer;
|
||||
for (int i = 0; i < Chapters.Length; i++)
|
||||
{
|
||||
int c = i;
|
||||
_buttons.Add(UIK.Btn(Loc.T(Chapters[i].title), () => Open(c), "tab notebook-tab", _tabs));
|
||||
}
|
||||
Open(0);
|
||||
}
|
||||
|
||||
void Open(int chapter)
|
||||
{
|
||||
_open = chapter;
|
||||
for (int i = 0; i < _buttons.Count; i++) _buttons[i].EnableInClassList("tab-on", i == _open);
|
||||
_page.Clear();
|
||||
foreach (var line in Chapters[chapter].lines())
|
||||
{
|
||||
bool head = line.StartsWith("# ");
|
||||
var l = UIK.Text(head ? line.Substring(2) : line, head ? "t-h2 t-dark notebook-head" : "t-body t-dark notebook-line", _page, head);
|
||||
l.style.whiteSpace = WhiteSpace.Normal;
|
||||
}
|
||||
}
|
||||
|
||||
static TeamState Ts => TeamState.Instance;
|
||||
|
||||
static IEnumerable<string> StartHere()
|
||||
{
|
||||
yield return "# " + Loc.T("The job");
|
||||
yield return Loc.T("Earth has run out of grass and Herbaria-7 is covered in it. Cut it, bundle it, ship it home.");
|
||||
yield return "# " + Loc.T("First day");
|
||||
yield return Loc.T("Take the nail scissors from the SUPPLY WALL on the west side of the deck.");
|
||||
yield return Loc.T("Hop over the railing with SPACE, hold LEFT CLICK and sweep the blade over the grass. It goes straight into the tool's container.");
|
||||
yield return Loc.T("Press E at the GRASS DEPOT to hand it in. You're paid at once.");
|
||||
yield return Loc.T("Spend it on whatever slows you down the most: a wider blade, a bigger container, then belts and machines.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Tools()
|
||||
{
|
||||
yield return "# " + Loc.T("On the supply wall");
|
||||
foreach (var d in GameDefs.Tools)
|
||||
{
|
||||
if (!GameDefs.IsBlade(d.id)) continue;
|
||||
string price = d.price > 0 ? UIK.Money(Ts ? Ts.ToolPrice(d) : d.price) : Loc.T("free");
|
||||
float width = Ts ? Ts.ToolWidth(d.id) : d.width;
|
||||
float cap = Ts ? Ts.ToolCap(d.id) : d.capacity;
|
||||
yield return Loc.F("{0}: {1:0.#} cm strip, {2:0.##} kg container, {3}", d.name, width * 100f, cap, price);
|
||||
}
|
||||
yield return "# " + Loc.T("Gear");
|
||||
yield return Loc.F("Build Hammer: {0}. B takes it out and opens the build menu.", UIK.Money(GameDefs.Tool(ToolId.Hammer).price));
|
||||
yield return Loc.F("Jetpack: {0}. Double-tap SPACE in the air for a dash.", UIK.Money(GameDefs.JetpackPrice));
|
||||
yield return Loc.F("Gravity Boots: {0}. G brings back Earth's pull.", UIK.Money(GameDefs.BootsPrice));
|
||||
yield return Loc.F("Night Vision: {0}. N goes from the headlamp to night vision to nothing.", UIK.Money(GameDefs.NightVisionPrice));
|
||||
yield return Loc.T("Every tool keeps its own grass. Slots on the belt are personal, up to six.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Bundles()
|
||||
{
|
||||
yield return "# " + Loc.T("Tying");
|
||||
yield return Loc.F("Q ties up to {0:0} kg from the tool in your hands into a bundle. Tying sells nothing: a bundle has to reach the depot.", GameDefs.BundleKg);
|
||||
yield return "# " + Loc.T("Carrying");
|
||||
yield return Loc.T("E picks a bundle up. LEFT CLICK throws it, E at the depot hands it in, E anywhere else drops it.");
|
||||
yield return Loc.T("A bundle on a belt rides to the end of the belt.");
|
||||
yield return "# " + Loc.T("Prices");
|
||||
yield return Loc.F("Grass pays {0} a kilo.", UIK.Money(GameDefs.PerKg(CargoKind.Grass)));
|
||||
}
|
||||
|
||||
static IEnumerable<string> Upgrades()
|
||||
{
|
||||
yield return "# " + Loc.T("The matrix");
|
||||
yield return Loc.T("The console on the deck sells upgrades for the whole crew. Five branches grow out of the Earth Uplink, which comes free.");
|
||||
if (Ts) yield return Loc.F("Installed so far: {0} of {1}.", Ts.Installs, TeamState.TotalInstalls);
|
||||
yield return "# " + Loc.T("Worth buying first");
|
||||
yield return Loc.T("A bigger container for the tool you use most, then Wider Blades, then Servo Boots.");
|
||||
yield return Loc.T("Machines are sold at a garage. There's none at the base: build one, see their own chapter.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Building()
|
||||
{
|
||||
yield return "# " + Loc.T("Anywhere on the ball");
|
||||
yield return Loc.T("With the hammer in hand you can build on any ground that has been mown, not just on the deck.");
|
||||
yield return Loc.T("Nothing goes on standing grass: cut it first. The ghost turns red and says how much is cut, and its outline on the ground shows what has to go. A belt needs a mown path along its whole length.");
|
||||
yield return Loc.T("Q changes category, the wheel picks a piece, LEFT CLICK places it, R turns it.");
|
||||
yield return Loc.T("RIGHT CLICK takes a piece down and gives all the money back. T carries it somewhere else, the middle button copies it.");
|
||||
yield return "# " + Loc.T("Belts");
|
||||
yield return Loc.F("Click where a belt starts, click where it ends. {0} a metre, up to {1:0} m in one run.", UIK.Money(GameDefs.Piece(PieceId.Belt).price), GameDefs.BeltLongest);
|
||||
yield return Loc.T("It carries on from where it ended until it lands on a port or you press RIGHT CLICK. Each click makes a corner.");
|
||||
yield return Loc.F("CTRL + wheel sets the height, {0:0.0} to {1:0} m. Posts grow down to the ground by themselves.", GameDefs.BeltLowest, GameDefs.BeltHighest);
|
||||
yield return Loc.T("A belt ending near a port snaps onto it. A belt ending on another belt loads onto it from the side.");
|
||||
yield return Loc.T("The depot takes twelve belts, three on each side, and pays as soon as a bundle arrives.");
|
||||
yield return "# " + Loc.T("Splitting and merging");
|
||||
yield return Loc.T("The splitter deals bundles to every belt joined to it, left, right and straight on, and when one is full the others carry on. E on it makes it a sorter: grass, hay or brick goes left, the rest the other way.");
|
||||
yield return Loc.T("The merger brings up to three belts into one, in turn. E on it gives one of them the right of way.");
|
||||
yield return "# " + Loc.T("Foundations");
|
||||
yield return Loc.T("A slab of level ground. On it things sit on a half-metre grid, F places them freely.");
|
||||
yield return Loc.T("Slabs of the same shape line up edge to edge. Square ones turn in steps of 90 degrees, hexagons in 30.");
|
||||
yield return Loc.T("Carry a foundation with T and everything standing on it comes along.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Power()
|
||||
{
|
||||
yield return "# " + Loc.T("Sun and night");
|
||||
yield return Loc.F("The sun goes round Herbaria-7 every {0:0} minutes, and each place has its own time of day.", GameDefs.DayLength / 60f);
|
||||
yield return Loc.T("N switches the headlamp. Night vision from the supply wall comes next on the same key.");
|
||||
yield return "# " + Loc.T("The network");
|
||||
yield return Loc.T("A panel, a battery or a pole feeds every machine inside its radius. Anything that reaches anything else joins up into one network and shares its power.");
|
||||
yield return Loc.T("A machine's percentage is how fast it runs: 100% is full speed, 30% is a third of it. It takes grass in and turns it out all the time, never in one go.");
|
||||
yield return "# " + Loc.T("Solar panels");
|
||||
foreach (var d in GameDefs.Pieces)
|
||||
if (GameDefs.IsPanel(d.id))
|
||||
{
|
||||
var p = GameDefs.Panel(d.id);
|
||||
yield return Loc.F("{0}: {1:0.#} kW, {2:0} m, {3}", d.name, p.kw, p.radius, UIK.Money(d.price));
|
||||
}
|
||||
yield return "# " + Loc.T("Batteries");
|
||||
yield return Loc.T("They fill with whatever sun the machines don't use, and when the panels fall short they make up the difference, at night as well.");
|
||||
foreach (var d in GameDefs.Pieces)
|
||||
if (GameDefs.IsBattery(d.id))
|
||||
{
|
||||
var b = GameDefs.Battery(d.id);
|
||||
yield return Loc.F("{0}: {1:0} kWh, up to {2:0} kW, {3:0} m, {4}", d.name, b.kwh, b.kw, b.radius, UIK.Money(d.price));
|
||||
}
|
||||
yield return "# " + Loc.T("Poles");
|
||||
yield return Loc.F("{0}: reaches {1:0} m, {2}. String them out to bring power to a far machine.", GameDefs.Piece(PieceId.Pole).name, GameDefs.PoleReach, UIK.Money(GameDefs.Piece(PieceId.Pole).price));
|
||||
yield return Loc.T("Aim at a panel, a battery, a pole or a machine to read how the network is doing. The lamp on a machine shows it too: green is full speed, amber is short of power, red is none.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Production()
|
||||
{
|
||||
yield return "# " + Loc.T("Worth more than grass");
|
||||
yield return Loc.F("Grass pays {0} a kilo, hay {1}, brick {2}.", UIK.Money(GameDefs.PerKg(CargoKind.Grass)), UIK.Money(GameDefs.PerKg(CargoKind.Hay)), UIK.Money(GameDefs.PerKg(CargoKind.Brick)));
|
||||
foreach (var id in new[] { PieceId.Dryer, PieceId.Press })
|
||||
{
|
||||
var d = GameDefs.Piece(id);
|
||||
yield return "# " + d.name;
|
||||
yield return Loc.F("{0} Draws {1:0} kW, {2}.", d.desc, d.kw, UIK.Money(d.price));
|
||||
}
|
||||
yield return "# " + Loc.T("Setting it up");
|
||||
yield return Loc.T("Bundles go in by belt or from your arms with E, and what's made leaves by the front. With no belt there it lands on the ground.");
|
||||
yield return Loc.T("A good line: grass into a splitter, one side to the windmill, the other to the press. The windmill's hay goes to the press too, the bricks to the depot.");
|
||||
yield return Loc.T("One windmill feeds two and a half presses.");
|
||||
yield return "# " + Loc.T("Fields");
|
||||
yield return Loc.T("Here and there wild wheat, oats, corn and sunflowers grow up through the grass. They cut and weigh like grass, and a field sector pays more when it's mown clean: half as much again for wheat and oats, double for corn, three times for sunflowers.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Machines()
|
||||
{
|
||||
yield return "# " + Loc.T("Your own");
|
||||
yield return Loc.T("Everyone buys their own machine at a garage you built with the Hammer, one of each, and anyone can ride it. Upgrades belong to the machine.");
|
||||
foreach (var d in GameDefs.Vehicles)
|
||||
yield return d.bed > 0 ? Loc.F("{0}: {1} bundles, {2}", d.name, d.bed, UIK.Money(d.price)) : Loc.F("{0}: {1:0.##} m strip, {2:0} kg hopper, {3}", d.name, d.width, d.hopper, UIK.Money(d.price));
|
||||
yield return "# " + Loc.T("Driving");
|
||||
yield return Loc.T("E gets in and out, SHIFT boosts. With Cruise Control, C holds your speed.");
|
||||
yield return Loc.T("On the pickup E with a bundle in your arms loads it, T tips the bed out.");
|
||||
yield return "# " + Loc.T("Unloading");
|
||||
yield return Loc.T("Drive into the yard at the foot of the ramp and it's paid as it comes off. On the pad in front of a garage it goes into the silo, and two ports at the back turn that into bundles for your belts.");
|
||||
yield return "# " + Loc.T("Calling");
|
||||
yield return Loc.T("Any garage can bring your machine to its pad, wherever you left it.");
|
||||
yield return "# " + Loc.T("Upgrades");
|
||||
yield return Loc.T("They cost the listed price on a $1000 machine, half that on the cheapest and up to three times on the dearest.");
|
||||
foreach (var t in GameDefs.Tunes) yield return Loc.F("{0}: {1} at the top level", t.name, t.effect(t.prices.Length));
|
||||
}
|
||||
|
||||
static IEnumerable<string> Robots()
|
||||
{
|
||||
yield return "# " + Loc.T("Docked");
|
||||
yield return Loc.T("Build a dock and its robot gets to work on the sectors around it, nearest first, row by row. No power needed.");
|
||||
foreach (var r in GameDefs.Robots)
|
||||
if (r.reach > 0) yield return Loc.F("{0}: {1} rings of sectors, {2:0.#} m strip, {3:0} kg hopper, {4}", r.name, r.reach, r.width, r.hopper, UIK.Money(GameDefs.Piece(r.piece).price));
|
||||
yield return Loc.T("A full robot walks home and the dock ties the grass into bundles. Give the dock a belt: with nowhere to put them it stops at 100 kg.");
|
||||
yield return "# " + Loc.T("The Reaper");
|
||||
yield return Loc.T("It needs no dock and goes on to the next unfinished sector by itself, for as long as there is grass.");
|
||||
yield return Loc.T("Every kilo is shot into a Bundle Catcher, anywhere on the planet. A Catcher holds 100 kg and puts it on a belt. With no Catcher free the Reaper stops when its hopper is full.");
|
||||
yield return "# " + Loc.T("The Binder");
|
||||
yield return Loc.T("E hands it the contents of your tool. It ties them into bundles and puts them on the belt, so you don't have to walk to the depot.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Sectors()
|
||||
{
|
||||
yield return "# " + Loc.T("Sectors");
|
||||
yield return Loc.F("Herbaria-7 is {0:N0} hexagons of about {1:0} m², with gold lines between them.", GameDefs.Sectors, GameDefs.SectorArea);
|
||||
yield return Loc.F("A sector mown clean pays {0} on top of its grass.", UIK.Money(GameDefs.SectorBonus(0)));
|
||||
yield return "# " + Loc.T("Stakes and survey points");
|
||||
yield return Loc.F("{0} survey stakes stand tangled around the planet: hold E to sort one out for {1}.", Landmarks.Stakes, UIK.Money(GameDefs.StakePay));
|
||||
yield return Loc.F("{0} survey points want reading: hold E for {1}.", Landmarks.Points, UIK.Money(GameDefs.PointPay));
|
||||
if (Ts) yield return Loc.F("Found so far: {0} stakes, {1} points.", Ts.FoundCount(false), Ts.FoundCount(true));
|
||||
yield return "# " + Loc.T("Stations");
|
||||
yield return Loc.T("Eleven more stations stand around the planet. Walk up to one and it opens for the crew: a depot, a supply wall, a console and a travel terminal.");
|
||||
yield return Loc.F("The terminal takes you to any station you have found for {0}.", UIK.Money(GameDefs.TravelPrice));
|
||||
yield return "# " + Loc.T("Getting home");
|
||||
yield return Loc.T("The compass always knows the way to the base: it stands at the north pole. M shows the whole planet.");
|
||||
}
|
||||
|
||||
static IEnumerable<string> Keys()
|
||||
{
|
||||
yield return "# " + Loc.T("On foot");
|
||||
yield return Loc.T("WASD walk, SHIFT run, SPACE jump, E use");
|
||||
yield return Loc.T("LEFT CLICK cut, Q tie a bundle, 1-6 or the wheel change tool");
|
||||
yield return Loc.T("B build, G gravity boots");
|
||||
yield return "# " + Loc.T("Building");
|
||||
yield return Loc.T("Q category, wheel piece, LEFT CLICK place, RIGHT CLICK remove");
|
||||
yield return Loc.T("R rotate, T move, middle button copy, CTRL + wheel belt height, F free placement");
|
||||
yield return Loc.T("N headlamp, M map, H notebook, TAB crew, ESC pause, ~ console");
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/NotebookScreen.cs.meta
Normal file
2
Assets/Scripts/UI/NotebookScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dd4e65016d6b6c7449a286474dc6afef
|
||||
678
Assets/Scripts/UI/PhoneScreen.cs
Normal file
678
Assets/Scripts/UI/PhoneScreen.cs
Normal file
@ -0,0 +1,678 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// What's on the phone: HaulOS, a UI Toolkit panel drawn into a texture on the display. A home screen with the state of
|
||||
/// the job and the sites, and Uplink, the page itself with a dock under it. Tapping goes through our own hit test, because
|
||||
/// the phone is a 3D object swinging about, so a button is just an element with an Action in its userData.
|
||||
/// </summary>
|
||||
public class PhoneScreen
|
||||
{
|
||||
public const int W = 720, H = 1578; // the same shape as Phone.ScreenW and ScreenH
|
||||
const int TopH = 138, DockH = 124, WebH = H - TopH - DockH;
|
||||
static readonly Color Mint = new Color(0.45f, 1f, 0.72f), Hay = new Color(1f, 0.8f, 0.36f), Ink = new Color(0.9f, 1f, 0.94f);
|
||||
static readonly Color Dim = new Color(0.72f, 0.9f, 0.8f, 0.72f), Glass = new Color(0.56f, 1f, 0.76f, 0.09f), Edge = new Color(0.56f, 1f, 0.76f, 0.26f);
|
||||
static readonly Color Deep = new Color(0.016f, 0.05f, 0.04f);
|
||||
|
||||
static readonly (string name, string url, Color colour, Action<Painter2D, float> glyph)[] Sites =
|
||||
{
|
||||
("YouTube", "https://m.youtube.com/", new Color(1f, 0.38f, 0.32f), Play),
|
||||
("Shorts", "https://m.youtube.com/shorts", new Color(1f, 0.56f, 0.34f), Feed),
|
||||
("Twitch", "https://m.twitch.tv/", new Color(0.72f, 0.56f, 1f), Live),
|
||||
("TikTok", "https://www.tiktok.com/foryou", new Color(0.36f, 0.94f, 0.94f), Feed),
|
||||
("Instagram", "https://www.instagram.com/reels/", new Color(1f, 0.52f, 0.76f), Lens),
|
||||
("Reddit", "https://www.reddit.com/", new Color(1f, 0.62f, 0.3f), Talk),
|
||||
("Google", "https://www.google.com/", new Color(0.5f, 0.74f, 1f), Find),
|
||||
("Wikipedia", "https://www.wikipedia.org/", new Color(0.82f, 0.88f, 0.86f), Book),
|
||||
};
|
||||
|
||||
public RenderTexture Tex { get; }
|
||||
/// <summary>The display's root, for whatever takes the whole screen over (a call).</summary>
|
||||
public VisualElement Root => _root;
|
||||
public PhoneWeb Web { get; }
|
||||
/// <summary>A page is up, rather than the home screen.</summary>
|
||||
public bool ShowingPage => _page;
|
||||
public bool Wide => _wide;
|
||||
/// <summary>A text box has the keyboard.</summary>
|
||||
public bool Typing => _addressing || _editing;
|
||||
|
||||
readonly VisualElement _root, _home, _top, _dock, _view, _progress, _status, _unturn, _relay;
|
||||
readonly Label _clock, _homeClock, _homeDate, _address, _search, _opening, _note, _mown, _money, _shipped, _link;
|
||||
readonly VisualElement _mownBar;
|
||||
VisualElement _hover, _homeGrid;
|
||||
Label _typeInto;
|
||||
readonly Label _mownTitle, _fundsTitle, _mapTile, _bookTile;
|
||||
// every label with whether it's in the display face: a new language may bring new letters
|
||||
readonly List<(Label label, bool display)> _labels = new List<(Label, bool)>();
|
||||
string _lang;
|
||||
bool _page, _wide, _visible, _focus, _touching, _addressing, _editing;
|
||||
string _typed = "", _shownUrl;
|
||||
Vector2 _touchAt;
|
||||
float _nextStats;
|
||||
|
||||
public PhoneScreen(GameObject host)
|
||||
{
|
||||
Tex = new RenderTexture(W, H, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "PhoneScreen", useMipMap = true, autoGenerateMips = true, anisoLevel = 4 };
|
||||
Tex.Create();
|
||||
Web = new PhoneWeb((float)WebH / W, (float)H / W);
|
||||
|
||||
var main = UnityEngine.Object.FindAnyObjectByType<UIDocument>(FindObjectsInactive.Include);
|
||||
var ps = UnityEngine.Object.Instantiate(main.panelSettings);
|
||||
ps.targetTexture = Tex;
|
||||
ps.scaleMode = PanelScaleMode.ConstantPixelSize;
|
||||
ps.scale = 1f;
|
||||
ps.clearColor = true;
|
||||
ps.colorClearValue = Color.black;
|
||||
ps.sortingOrder = -10;
|
||||
|
||||
var go = new GameObject("PhoneUI");
|
||||
go.SetActive(false);
|
||||
go.transform.SetParent(host.transform, false);
|
||||
var doc = go.AddComponent<UIDocument>();
|
||||
doc.panelSettings = ps;
|
||||
go.SetActive(true);
|
||||
|
||||
_root = doc.rootVisualElement;
|
||||
_root.style.width = W; _root.style.height = H;
|
||||
_root.style.backgroundColor = Deep;
|
||||
UIK.SetFont(_root, false);
|
||||
|
||||
var wall = AssetBank.I.Tex("phone_wallpaper");
|
||||
var back = Abs(_root);
|
||||
back.pickingMode = PickingMode.Ignore;
|
||||
if (wall) { back.style.backgroundImage = new StyleBackground(wall); back.style.unityBackgroundScaleMode = ScaleMode.ScaleAndCrop; }
|
||||
|
||||
// ── home ──
|
||||
_home = Abs(_root);
|
||||
_home.pickingMode = PickingMode.Ignore;
|
||||
_home.style.paddingLeft = 40; _home.style.paddingRight = 40; _home.style.paddingTop = 84;
|
||||
_homeClock = T("0:00", 168, Ink, _home, true);
|
||||
_homeDate = T("HERBARIA-7", 25, Mint, _home, true);
|
||||
_homeDate.style.letterSpacing = 4f;
|
||||
_homeDate.style.marginBottom = 28;
|
||||
|
||||
var cards = Row(_home);
|
||||
cards.style.justifyContent = Justify.SpaceBetween;
|
||||
cards.style.marginBottom = 24;
|
||||
var left = Panel(cards, 312, 146);
|
||||
_mownTitle = T(Loc.T("PLANET MOWN"), 21, Dim, left, true);
|
||||
_mownTitle.style.letterSpacing = 2f;
|
||||
_mown = T(Loc.F("{0:0.0000}%", 0d), 44, Ink, left, true);
|
||||
var track = El(left);
|
||||
track.pickingMode = PickingMode.Ignore;
|
||||
track.style.height = 8; track.style.marginTop = 8;
|
||||
track.style.backgroundColor = Edge;
|
||||
Round(track, 4);
|
||||
_mownBar = El(track);
|
||||
_mownBar.pickingMode = PickingMode.Ignore;
|
||||
_mownBar.style.height = 8; _mownBar.style.width = Length.Percent(1);
|
||||
_mownBar.style.backgroundColor = Mint;
|
||||
Round(_mownBar, 4);
|
||||
var right = Panel(cards, 312, 146);
|
||||
_fundsTitle = T(Loc.T("COMPANY FUNDS"), 21, Dim, right, true);
|
||||
_fundsTitle.style.letterSpacing = 2f;
|
||||
_money = T("$0", 44, Hay, right, true);
|
||||
_shipped = T("", 23, Dim, right, false);
|
||||
|
||||
var search = El(_home);
|
||||
search.style.height = 92;
|
||||
search.style.marginBottom = 24;
|
||||
search.style.paddingLeft = 30;
|
||||
search.style.flexDirection = FlexDirection.Row;
|
||||
search.style.alignItems = Align.Center;
|
||||
Skin(search, 46);
|
||||
search.userData = (Action)(() => StartAddress(_search));
|
||||
Glyph(search, 44, Mint, Find).style.marginRight = 18;
|
||||
_search = T(Loc.T("Search or type a site"), 32, Dim, search, false);
|
||||
|
||||
_homeGrid = El(_home);
|
||||
_homeGrid.pickingMode = PickingMode.Ignore;
|
||||
_homeGrid.style.flexDirection = FlexDirection.Row;
|
||||
_homeGrid.style.flexWrap = Wrap.Wrap;
|
||||
_homeGrid.style.justifyContent = Justify.SpaceBetween;
|
||||
foreach (var (name, url, colour, glyph) in Sites) Tile(_homeGrid, name, colour, glyph, () => Open(url));
|
||||
_mapTile = Tile(_homeGrid, Loc.T("Map"), Mint, Hex, () => { Phone.I.Show(PhoneMode.Side); UIRoot.I.OpenMap(); });
|
||||
_bookTile = Tile(_homeGrid, Loc.T("Notebook"), Hay, Book, () => { Phone.I.Show(PhoneMode.Side); UIRoot.I.OpenNotebook(); });
|
||||
|
||||
_note = T(Note, 24, Dim, _home, false);
|
||||
_note.style.whiteSpace = WhiteSpace.Normal;
|
||||
_note.style.unityTextAlign = TextAnchor.MiddleCenter;
|
||||
_note.style.marginTop = 6;
|
||||
|
||||
// ── a page: the address on top, the dock under it, and the page between them ──
|
||||
_view = Abs(_root);
|
||||
_view.pickingMode = PickingMode.Ignore;
|
||||
_view.style.top = TopH; _view.style.bottom = StyleKeyword.Auto; _view.style.height = WebH;
|
||||
_view.style.backgroundColor = Color.black;
|
||||
_view.style.backgroundImage = new StyleBackground(Background.FromRenderTexture((RenderTexture)Web.Picture));
|
||||
_view.style.unityBackgroundScaleMode = ScaleMode.StretchToFill;
|
||||
_view.style.alignItems = Align.Center;
|
||||
_view.style.justifyContent = Justify.Center;
|
||||
_opening = T(Loc.T("Linking..."), 36, Mint, _view, true);
|
||||
_unturn = El(_view);
|
||||
_unturn.style.position = Position.Absolute;
|
||||
_unturn.style.right = 28; _unturn.style.top = 28; _unturn.style.width = 92; _unturn.style.height = 92;
|
||||
_unturn.style.alignItems = Align.Center; _unturn.style.justifyContent = Justify.Center;
|
||||
Skin(_unturn, 46);
|
||||
_unturn.style.backgroundColor = new Color(0f, 0f, 0f, 0.55f);
|
||||
_unturn.userData = (Action)Turn;
|
||||
Glyph(_unturn, 52, Mint, Rotate);
|
||||
|
||||
_top = Abs(_root);
|
||||
_top.pickingMode = PickingMode.Ignore;
|
||||
_top.style.bottom = StyleKeyword.Auto; _top.style.height = TopH;
|
||||
_top.style.backgroundColor = new Color(0.016f, 0.05f, 0.04f, 0.97f);
|
||||
_top.style.justifyContent = Justify.FlexEnd;
|
||||
_top.style.paddingLeft = 16; _top.style.paddingRight = 16; _top.style.paddingBottom = 10;
|
||||
var pill = El(_top);
|
||||
pill.style.height = 62;
|
||||
pill.style.paddingLeft = 24; pill.style.paddingRight = 18;
|
||||
pill.style.flexDirection = FlexDirection.Row;
|
||||
pill.style.alignItems = Align.Center;
|
||||
Skin(pill, 31);
|
||||
pill.userData = (Action)(() => StartAddress(_address));
|
||||
Glyph(pill, 30, Mint, Find).style.marginRight = 14;
|
||||
_address = T("", 28, Ink, pill, false);
|
||||
|
||||
_dock = Abs(_root);
|
||||
_dock.pickingMode = PickingMode.Ignore;
|
||||
_dock.style.top = StyleKeyword.Auto; _dock.style.height = DockH;
|
||||
_dock.style.backgroundColor = new Color(0.016f, 0.05f, 0.04f, 0.97f);
|
||||
_dock.style.flexDirection = FlexDirection.Row;
|
||||
_dock.style.justifyContent = Justify.SpaceAround;
|
||||
_dock.style.alignItems = Align.Center;
|
||||
_dock.style.paddingLeft = 56; _dock.style.paddingBottom = 12;
|
||||
Dock(Back, () => Web.Back());
|
||||
Dock(Forward, () => Web.Forward());
|
||||
Dock(Reload, () => Web.Reload());
|
||||
Dock(Rotate, Turn);
|
||||
Dock(Hex, Home);
|
||||
|
||||
_progress = El(_root);
|
||||
_progress.pickingMode = PickingMode.Ignore;
|
||||
_progress.style.position = Position.Absolute;
|
||||
_progress.style.top = TopH - 5; _progress.style.height = 5;
|
||||
_progress.style.width = Length.Percent(30);
|
||||
_progress.style.backgroundColor = Mint;
|
||||
|
||||
// ── the strip over everything ──
|
||||
_status = Abs(_root);
|
||||
_status.pickingMode = PickingMode.Ignore;
|
||||
_status.style.bottom = StyleKeyword.Auto; _status.style.height = 62;
|
||||
_status.style.flexDirection = FlexDirection.Row;
|
||||
_status.style.justifyContent = Justify.SpaceBetween;
|
||||
_status.style.alignItems = Align.Center;
|
||||
_status.style.paddingLeft = 44; _status.style.paddingRight = 112; _status.style.paddingTop = 10;
|
||||
_clock = T("0:00", 28, Ink, _status, true);
|
||||
_relay = Row(_status);
|
||||
_relay.style.alignItems = Align.Center;
|
||||
_link = T(Loc.T("RELAY"), 21, Mint, _relay, true);
|
||||
_link.style.letterSpacing = 3f;
|
||||
_link.style.marginRight = 10;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var bar = El(_relay);
|
||||
bar.pickingMode = PickingMode.Ignore;
|
||||
bar.style.width = 6; bar.style.height = 8 + i * 5; bar.style.marginLeft = 3;
|
||||
bar.style.alignSelf = Align.FlexEnd;
|
||||
bar.style.backgroundColor = Mint;
|
||||
Round(bar, 2);
|
||||
}
|
||||
|
||||
_lang = Loc.Code;
|
||||
ShowPage(false);
|
||||
Tick();
|
||||
}
|
||||
|
||||
static string Note => PhoneWeb.Available ? Loc.T("The whole internet, relayed from Earth. Log in once and it stays.") : Loc.T("The relay needs Microsoft Edge or Google Chrome on this PC.");
|
||||
|
||||
/// <summary>The phone outlives a change of language: its fixed words and letters are put right here.</summary>
|
||||
void Relabel()
|
||||
{
|
||||
_lang = Loc.Code;
|
||||
UIK.SetFont(_root, false);
|
||||
foreach (var (l, display) in _labels) UIK.SetFont(l, display);
|
||||
_mownTitle.text = Loc.T("PLANET MOWN");
|
||||
_fundsTitle.text = Loc.T("COMPANY FUNDS");
|
||||
_mapTile.text = Loc.T("Map");
|
||||
_bookTile.text = Loc.T("Notebook");
|
||||
_note.text = Note;
|
||||
if (!_addressing) _search.text = Loc.T("Search or type a site");
|
||||
_nextStats = 0f;
|
||||
}
|
||||
|
||||
// ───────────────────────── little helpers ─────────────────────────
|
||||
|
||||
static VisualElement El(VisualElement parent)
|
||||
{
|
||||
var e = new VisualElement();
|
||||
parent?.Add(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
static VisualElement Abs(VisualElement parent)
|
||||
{
|
||||
var e = El(parent);
|
||||
e.style.position = Position.Absolute;
|
||||
e.style.left = 0; e.style.right = 0; e.style.top = 0; e.style.bottom = 0;
|
||||
return e;
|
||||
}
|
||||
|
||||
static VisualElement Row(VisualElement parent)
|
||||
{
|
||||
var e = El(parent);
|
||||
e.pickingMode = PickingMode.Ignore;
|
||||
e.style.flexDirection = FlexDirection.Row;
|
||||
return e;
|
||||
}
|
||||
|
||||
static void Round(VisualElement e, float r)
|
||||
{
|
||||
e.style.borderTopLeftRadius = r; e.style.borderTopRightRadius = r;
|
||||
e.style.borderBottomLeftRadius = r; e.style.borderBottomRightRadius = r;
|
||||
}
|
||||
|
||||
static void Skin(VisualElement e, float r)
|
||||
{
|
||||
Round(e, r);
|
||||
e.style.backgroundColor = Glass;
|
||||
e.style.borderTopWidth = 2; e.style.borderBottomWidth = 2; e.style.borderLeftWidth = 2; e.style.borderRightWidth = 2;
|
||||
e.style.borderTopColor = Edge; e.style.borderBottomColor = Edge; e.style.borderLeftColor = Edge; e.style.borderRightColor = Edge;
|
||||
}
|
||||
|
||||
static VisualElement Panel(VisualElement parent, float w, float h)
|
||||
{
|
||||
var e = El(parent);
|
||||
e.pickingMode = PickingMode.Ignore;
|
||||
e.style.width = w; e.style.height = h;
|
||||
e.style.paddingLeft = 22; e.style.paddingRight = 18; e.style.paddingTop = 14;
|
||||
Skin(e, 26);
|
||||
e.style.backgroundColor = new Color(0.02f, 0.07f, 0.055f, 0.74f);
|
||||
return e;
|
||||
}
|
||||
|
||||
Label T(string text, int size, Color c, VisualElement parent, bool display)
|
||||
{
|
||||
var l = new Label(text);
|
||||
UIK.SetFont(l, display);
|
||||
_labels.Add((l, display));
|
||||
l.style.fontSize = size;
|
||||
l.style.color = c;
|
||||
l.style.marginBottom = 0; l.style.marginTop = 0; l.style.marginLeft = 0; l.style.marginRight = 0;
|
||||
l.style.paddingBottom = 0; l.style.paddingTop = 0; l.style.paddingLeft = 0; l.style.paddingRight = 0;
|
||||
l.pickingMode = PickingMode.Ignore;
|
||||
parent?.Add(l);
|
||||
return l;
|
||||
}
|
||||
|
||||
Label Tile(VisualElement grid, string name, Color colour, Action<Painter2D, float> glyph, Action open)
|
||||
{
|
||||
var tile = El(grid);
|
||||
tile.style.width = 312; tile.style.height = 112;
|
||||
tile.style.marginBottom = 16;
|
||||
tile.style.flexDirection = FlexDirection.Row;
|
||||
tile.style.alignItems = Align.Center;
|
||||
tile.style.paddingLeft = 22;
|
||||
Skin(tile, 26);
|
||||
tile.style.backgroundColor = new Color(0.02f, 0.07f, 0.055f, 0.74f);
|
||||
tile.style.borderLeftColor = colour;
|
||||
tile.style.borderLeftWidth = 5;
|
||||
tile.userData = open;
|
||||
Glyph(tile, 56, colour, glyph).style.marginRight = 18;
|
||||
return T(name, 33, Ink, tile, true);
|
||||
}
|
||||
|
||||
void Dock(Action<Painter2D, float> glyph, Action click)
|
||||
{
|
||||
var b = El(_dock);
|
||||
b.style.width = 104; b.style.height = 92;
|
||||
b.style.alignItems = Align.Center; b.style.justifyContent = Justify.Center;
|
||||
b.userData = click;
|
||||
Glyph(b, 54, Ink, glyph);
|
||||
}
|
||||
|
||||
// ───────────────────────── glyphs: our own, and drawn, so they stay sharp ─────────────────────────
|
||||
|
||||
static VisualElement Glyph(VisualElement parent, float size, Color c, Action<Painter2D, float> draw)
|
||||
{
|
||||
var e = El(parent);
|
||||
e.pickingMode = PickingMode.Ignore;
|
||||
e.style.width = size; e.style.height = size;
|
||||
e.generateVisualContent += ctx =>
|
||||
{
|
||||
var p = ctx.painter2D;
|
||||
float s = e.contentRect.width / 100f;
|
||||
p.strokeColor = c; p.fillColor = c;
|
||||
p.lineWidth = 9f * s;
|
||||
p.lineCap = LineCap.Round; p.lineJoin = LineJoin.Round;
|
||||
draw(p, s);
|
||||
};
|
||||
return e;
|
||||
}
|
||||
|
||||
static void Path(Painter2D p, float s, bool closed, bool fill, params float[] xy)
|
||||
{
|
||||
p.BeginPath();
|
||||
p.MoveTo(new Vector2(xy[0], xy[1]) * s);
|
||||
for (int i = 2; i < xy.Length; i += 2) p.LineTo(new Vector2(xy[i], xy[i + 1]) * s);
|
||||
if (closed) p.ClosePath();
|
||||
if (fill) p.Fill();
|
||||
else p.Stroke();
|
||||
}
|
||||
|
||||
static void Ring(Painter2D p, float s, float x, float y, float r, float from = 0f, float to = 360f)
|
||||
{
|
||||
p.BeginPath();
|
||||
p.Arc(new Vector2(x, y) * s, r * s, Angle.Degrees(from), Angle.Degrees(to));
|
||||
p.Stroke();
|
||||
}
|
||||
|
||||
static void Play(Painter2D p, float s) => Path(p, s, true, true, 26, 14, 86, 50, 26, 86);
|
||||
static void Back(Painter2D p, float s) => Path(p, s, false, false, 64, 16, 30, 50, 64, 84);
|
||||
static void Forward(Painter2D p, float s) => Path(p, s, false, false, 36, 16, 70, 50, 36, 84);
|
||||
static void Hex(Painter2D p, float s) => Path(p, s, true, false, 50, 8, 88, 29, 88, 71, 50, 92, 12, 71, 12, 29);
|
||||
static void Find(Painter2D p, float s) { Ring(p, s, 42, 42, 28); Path(p, s, false, false, 63, 63, 88, 88); }
|
||||
static void Feed(Painter2D p, float s) { Path(p, s, true, false, 26, 8, 74, 8, 74, 92, 26, 92); Path(p, s, true, true, 42, 34, 64, 50, 42, 66); }
|
||||
static void Lens(Painter2D p, float s) { Path(p, s, true, false, 12, 12, 88, 12, 88, 88, 12, 88); Ring(p, s, 50, 50, 20); }
|
||||
static void Talk(Painter2D p, float s) => Path(p, s, true, false, 12, 16, 88, 16, 88, 68, 46, 68, 26, 88, 26, 68, 12, 68);
|
||||
static void Book(Painter2D p, float s) { Path(p, s, true, false, 18, 14, 82, 14, 82, 86, 18, 86); Path(p, s, false, false, 36, 36, 64, 36); Path(p, s, false, false, 36, 56, 64, 56); }
|
||||
static void Live(Painter2D p, float s) { Ring(p, s, 50, 50, 11); Ring(p, s, 50, 50, 28, -40f, 40f); Ring(p, s, 50, 50, 28, 140f, 220f); Ring(p, s, 50, 50, 44, -40f, 40f); Ring(p, s, 50, 50, 44, 140f, 220f); }
|
||||
static void Reload(Painter2D p, float s) { Ring(p, s, 50, 52, 34, -50f, 250f); Path(p, s, true, true, 70, 6, 94, 26, 62, 34); }
|
||||
static void Rotate(Painter2D p, float s) { Path(p, s, true, false, 10, 52, 90, 52, 90, 90, 10, 90); Ring(p, s, 50, 48, 36, 200f, 320f); Path(p, s, true, true, 92, 16, 86, 44, 64, 28); }
|
||||
|
||||
// ───────────────────────── pages ─────────────────────────
|
||||
|
||||
public void Open(string url)
|
||||
{
|
||||
if (!PhoneWeb.Available) return;
|
||||
EndTyping();
|
||||
ShowPage(true);
|
||||
_opening.text = Loc.T("Linking...");
|
||||
_opening.style.display = DisplayStyle.Flex;
|
||||
_address.text = Loc.T("Linking...");
|
||||
_shownUrl = null;
|
||||
Web.Go(url);
|
||||
}
|
||||
|
||||
public void Home()
|
||||
{
|
||||
EndTyping();
|
||||
if (_wide) Turn();
|
||||
ShowPage(false);
|
||||
_shownUrl = null;
|
||||
Web.Leave();
|
||||
}
|
||||
|
||||
void ShowPage(bool on)
|
||||
{
|
||||
_page = on;
|
||||
_home.style.display = on ? DisplayStyle.None : DisplayStyle.Flex;
|
||||
_view.style.display = _top.style.display = _dock.style.display = on ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
Dress();
|
||||
}
|
||||
|
||||
/// <summary>Sideways the page takes the whole display: the view is laid along the long side and turned onto it.</summary>
|
||||
void Dress()
|
||||
{
|
||||
bool full = _page && _wide;
|
||||
_top.style.display = _dock.style.display = _page && !_wide ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_status.style.display = full ? DisplayStyle.None : DisplayStyle.Flex;
|
||||
_unturn.style.display = full && _focus ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
_view.style.left = full ? W : 0;
|
||||
_view.style.top = full ? 0 : TopH;
|
||||
_view.style.right = StyleKeyword.Auto;
|
||||
_view.style.width = full ? H : W;
|
||||
_view.style.height = full ? W : WebH;
|
||||
_view.style.transformOrigin = new TransformOrigin(0, 0);
|
||||
_view.style.rotate = new Rotate(full ? 90f : 0f);
|
||||
}
|
||||
|
||||
/// <summary>The phone onto its side and back. Only a page has anything to gain from it.</summary>
|
||||
public void Turn()
|
||||
{
|
||||
if (!_page) return;
|
||||
EndTyping();
|
||||
_wide = !_wide;
|
||||
Web.Wide(_wide);
|
||||
Dress();
|
||||
Phone.I?.Turned(_wide);
|
||||
}
|
||||
|
||||
public void ModeChanged(PhoneMode m)
|
||||
{
|
||||
_visible = m != PhoneMode.Away;
|
||||
_focus = m == PhoneMode.Up;
|
||||
if (!_focus) EndTyping();
|
||||
Web.Show(_visible);
|
||||
Dress();
|
||||
if (_hover != null && !_focus) Hover(new Vector2(-1f, -1f));
|
||||
}
|
||||
|
||||
/// <summary>The wheel, wherever the phone is held.</summary>
|
||||
public void Wheel(int dir) { if (_page) Web.Wheel(dir); }
|
||||
|
||||
// ───────────────────────── fingers ─────────────────────────
|
||||
|
||||
VisualElement Under(Vector2 uv)
|
||||
{
|
||||
if (uv.x < 0f || uv.x > 1f || uv.y < 0f || uv.y > 1f || _root.panel == null) return null;
|
||||
var e = _root.panel.Pick(new Vector2(uv.x * W, (1f - uv.y) * H));
|
||||
while (e != null && !(e.userData is Action)) e = e.parent;
|
||||
return e;
|
||||
}
|
||||
|
||||
public void Hover(Vector2 uv)
|
||||
{
|
||||
var e = Under(uv);
|
||||
if (e == _hover) return;
|
||||
if (_hover != null) _hover.style.scale = new Scale(Vector3.one);
|
||||
_hover = e;
|
||||
if (_hover != null) _hover.style.scale = new Scale(Vector3.one * 1.04f);
|
||||
}
|
||||
|
||||
/// <summary>Panel pixels to the page's own: on its side the view is turned a quarter, so its x runs down the panel.</summary>
|
||||
Vector2 ToPage(Vector2 uv)
|
||||
{
|
||||
var at = new Vector2(uv.x * W, (1f - uv.y) * H);
|
||||
if (_wide) return new Vector2(at.y / H * Web.CssW, (W - at.x) / W * Web.CssH);
|
||||
return new Vector2(at.x / W * Web.CssW, (at.y - TopH) / WebH * Web.CssH);
|
||||
}
|
||||
|
||||
/// <summary>The mouse on the phone: a button takes a press, and the page takes presses and drags itself.</summary>
|
||||
public void Pointer(Vector2 uv, bool down, bool held, bool up)
|
||||
{
|
||||
if (down && Under(uv)?.userData is Action a)
|
||||
{
|
||||
Sfx.Play("ui_click", 0.4f, 1.2f);
|
||||
a();
|
||||
return;
|
||||
}
|
||||
if (!_page) return;
|
||||
var css = ToPage(uv);
|
||||
bool inside = uv.x >= 0f && uv.x <= 1f && css.y >= 0f && css.y <= Web.CssH && css.x >= 0f && css.x <= Web.CssW;
|
||||
if (down && inside)
|
||||
{
|
||||
if (_addressing) EndTyping();
|
||||
_touching = true;
|
||||
_touchAt = css;
|
||||
Web.Touch("touchStart", css.x, css.y);
|
||||
return;
|
||||
}
|
||||
if (!_touching) return;
|
||||
if (held && (css - _touchAt).sqrMagnitude > 1f)
|
||||
{
|
||||
_touchAt = css;
|
||||
Web.Touch("touchMove", css.x, css.y);
|
||||
}
|
||||
if (up || !held)
|
||||
{
|
||||
_touching = false;
|
||||
Web.TouchEnd();
|
||||
CheckField();
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── typing ─────────────────────────
|
||||
|
||||
/// <summary>A tap may have landed in a text box: the page is asked a moment later, once it has reacted.</summary>
|
||||
async void CheckField()
|
||||
{
|
||||
await System.Threading.Tasks.Task.Delay(180);
|
||||
bool field = await Web.FieldActive();
|
||||
if (field == _editing) return;
|
||||
if (field) { _editing = true; Listen(true); Ctl.Typing = true; }
|
||||
else EndTyping();
|
||||
}
|
||||
|
||||
void StartAddress(Label into)
|
||||
{
|
||||
EndTyping();
|
||||
_addressing = true;
|
||||
_typeInto = into;
|
||||
_typed = "";
|
||||
into.text = "|";
|
||||
into.style.color = Ink;
|
||||
Listen(true);
|
||||
Ctl.Typing = true;
|
||||
}
|
||||
|
||||
void EndTyping()
|
||||
{
|
||||
if (Typing) { Listen(false); Ctl.Typing = false; }
|
||||
_editing = false;
|
||||
if (_addressing)
|
||||
{
|
||||
_addressing = false;
|
||||
_shownUrl = null;
|
||||
_search.text = Loc.T("Search or type a site");
|
||||
_search.style.color = Dim;
|
||||
}
|
||||
}
|
||||
|
||||
public void CancelTyping() => EndTyping();
|
||||
|
||||
void Listen(bool on)
|
||||
{
|
||||
var k = Keyboard.current;
|
||||
if (k == null) return;
|
||||
k.onTextInput -= Char;
|
||||
if (on) k.onTextInput += Char;
|
||||
}
|
||||
|
||||
/// <summary>One character from the keyboard, into the address or into the page.</summary>
|
||||
public void Char(char c)
|
||||
{
|
||||
if (_addressing)
|
||||
{
|
||||
if (c == '\r' || c == '\n')
|
||||
{
|
||||
var t = _typed.Trim();
|
||||
EndTyping();
|
||||
if (t.Length > 0) Open(ToUrl(t));
|
||||
return;
|
||||
}
|
||||
if (c == '\b') { if (_typed.Length > 0) _typed = _typed.Substring(0, _typed.Length - 1); }
|
||||
else if (c == 22) _typed += GUIUtility.systemCopyBuffer;
|
||||
else if (c >= 32) _typed += c;
|
||||
_typeInto.text = _typed + "|";
|
||||
return;
|
||||
}
|
||||
if (c == '\b') Web.Key("Backspace", 8, null);
|
||||
else if (c == '\r' || c == '\n') Web.Key("Enter", 13, "\\r");
|
||||
else if (c == '\t') Web.Key("Tab", 9, null);
|
||||
else if (c == 22) Web.Insert(GUIUtility.systemCopyBuffer);
|
||||
else if (c >= 32) Web.Insert(c.ToString());
|
||||
}
|
||||
|
||||
static string ToUrl(string t)
|
||||
{
|
||||
if (t.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || t.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return t;
|
||||
if (t.IndexOf(' ') < 0 && t.IndexOf('.') > 0) return "https://" + t;
|
||||
return "https://duckduckgo.com/?q=" + Uri.EscapeDataString(t);
|
||||
}
|
||||
|
||||
// ───────────────────────── every frame ─────────────────────────
|
||||
|
||||
static string Short(string url)
|
||||
{
|
||||
var m = Regex.Match(url, @"^https?://(?:www\.|m\.)?([^/?#]+)");
|
||||
return m.Success ? m.Groups[1].Value : url;
|
||||
}
|
||||
|
||||
public void Tick()
|
||||
{
|
||||
if (_lang != Loc.Code) Relabel();
|
||||
Web.Tick(_focus);
|
||||
if (Web.Fresh) _view.MarkDirtyRepaint();
|
||||
var problem = Web.TakeProblem();
|
||||
if (problem != null)
|
||||
{
|
||||
problem = Loc.T(problem);
|
||||
_opening.text = problem;
|
||||
_opening.style.display = DisplayStyle.Flex;
|
||||
_address.text = problem;
|
||||
_note.text = problem;
|
||||
}
|
||||
string url = Web.Url;
|
||||
if (url == "about:blank")
|
||||
{
|
||||
// backed out past the first page
|
||||
if (_page && !Web.Loading) Home();
|
||||
url = null;
|
||||
}
|
||||
if (url != null && url != _shownUrl && !_addressing && _page)
|
||||
{
|
||||
_shownUrl = url;
|
||||
_opening.style.display = DisplayStyle.None;
|
||||
_address.text = url.StartsWith("chrome-error", StringComparison.Ordinal) ? Loc.T("Can't reach that site") : Short(url);
|
||||
}
|
||||
bool busy = Web.Loading && _page && !_wide;
|
||||
_progress.style.display = busy ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (busy) _progress.style.left = Length.Percent(Mathf.PingPong(Time.unscaledTime * 90f, 70f));
|
||||
if (!_visible && _nextStats > 0f) return;
|
||||
if (Time.unscaledTime < _nextStats) return;
|
||||
_nextStats = Time.unscaledTime + 0.5f;
|
||||
|
||||
string now = DateTime.Now.ToString("H:mm", Loc.Culture);
|
||||
if (_clock.text != now) { _clock.text = now; _homeClock.text = now; }
|
||||
var ts = TeamState.Instance;
|
||||
if (ts)
|
||||
{
|
||||
_mown.text = Loc.F("{0:0.0000}%", ts.Mown01 * 100.0);
|
||||
_mownBar.style.width = Length.Percent(Mathf.Clamp((float)ts.Mown01 * 100f, 1f, 100f));
|
||||
_money.text = UIK.Money(ts.Money.Value);
|
||||
_shipped.text = Loc.F("{0} shipped", GameDefs.Kilos(ts.Shipped.Value));
|
||||
}
|
||||
var me = PlayerAgent.Local;
|
||||
_homeDate.text = me ? Loc.F("HERBARIA-7 · SECTOR {0}", HexGrid.SectorAt(Planet.Up(me.transform.position)) + 1) : "HERBARIA-7";
|
||||
_link.text = Web.Ready ? Loc.T("RELAY") : Loc.T("RELAY IDLE");
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
EndTyping();
|
||||
if (_wide) { _wide = false; Web.Wide(false); Dress(); }
|
||||
ShowPage(false);
|
||||
_shownUrl = null;
|
||||
Web.Close();
|
||||
}
|
||||
|
||||
/// <summary>Test hook: where a tile is, in display coordinates.</summary>
|
||||
public Vector2 TileAt(int i)
|
||||
{
|
||||
var c = _homeGrid[i].worldBound.center;
|
||||
return new Vector2(c.x / W, 1f - c.y / H);
|
||||
}
|
||||
|
||||
/// <summary>Test hook: a point of the page, in display coordinates.</summary>
|
||||
public Vector2 PageAt(float x, float y) => _wide
|
||||
? new Vector2(1f - y, 1f - x)
|
||||
: new Vector2(x, 1f - (TopH + y * WebH) / H);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/PhoneScreen.cs.meta
Normal file
2
Assets/Scripts/UI/PhoneScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 84d35151a10ff2447849631694cc2635
|
||||
124
Assets/Scripts/UI/PieceScreen.cs
Normal file
124
Assets/Scripts/UI/PieceScreen.cs
Normal file
@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// T on anything built: its upgrade level and what the next one does and costs, its mode if it is a splitter or a merger,
|
||||
/// and its switch if it has one (a belt stopped, a machine paused). Everything here is for the whole crew, paid from the wallet.
|
||||
/// </summary>
|
||||
public class PieceScreen
|
||||
{
|
||||
public VisualElement Card { get; }
|
||||
readonly BuildPiece _p;
|
||||
readonly VisualElement _body;
|
||||
readonly Action _close;
|
||||
|
||||
public PieceScreen(VisualElement layer, Action close, BuildPiece piece)
|
||||
{
|
||||
_p = piece;
|
||||
_close = close;
|
||||
Card = UIK.El("card", layer);
|
||||
Card.pickingMode = PickingMode.Position;
|
||||
Card.style.width = 680;
|
||||
var header = UIK.El("card-header", Card);
|
||||
UIK.Text(piece.Def.name.ToUpper(Loc.Culture), "t-h1 t-dark", header);
|
||||
UIK.Btn("X", close, "btn btn-red btn-small", header);
|
||||
_body = UIK.El(null, Card);
|
||||
Refresh();
|
||||
// the numbers follow the wallet and the piece while the card is up
|
||||
int was = Stamp();
|
||||
Card.schedule.Execute(() =>
|
||||
{
|
||||
if (!_p || !_p.IsSpawned) { _close(); return; }
|
||||
int now = Stamp();
|
||||
if (now != was) { was = now; Refresh(); }
|
||||
}).Every(200);
|
||||
}
|
||||
|
||||
int Stamp() => !_p ? 0 : _p.Setting * 31 + (TeamState.Instance ? (int)TeamState.Instance.Money.Value : 0);
|
||||
|
||||
void Refresh()
|
||||
{
|
||||
_body.Clear();
|
||||
var ts = TeamState.Instance;
|
||||
if (!_p || !ts) return;
|
||||
var kind = _p.Upgrades;
|
||||
int tier = _p.Tier.Value;
|
||||
|
||||
if (kind != UpgradeKind.None)
|
||||
{
|
||||
var row = UIK.El("tune-row", _body);
|
||||
var names = UIK.El("tune-names", row);
|
||||
UIK.Text($"{GameDefs.TierName(tier)}", "t-small t-dark", names, false);
|
||||
UIK.Text(tier == 0 ? Loc.T("As built.") : Loc.F("Now {0}.", GameDefs.TierEffect(kind, tier)), "tune-effect", names, false);
|
||||
if (tier < GameDefs.MaxTier)
|
||||
{
|
||||
double price = GameDefs.UpgradePrice(_p, tier);
|
||||
bool can = ts.Money.Value >= price;
|
||||
var up = UIK.El("tune-row", _body);
|
||||
var upNames = UIK.El("tune-names", up);
|
||||
UIK.Text(Loc.F("Upgrade to {0}", GameDefs.TierName(tier + 1)), "t-small t-dark", upNames, false);
|
||||
UIK.Text(Loc.F("{0}.", Cap(GameDefs.TierEffect(kind, tier + 1))), "tune-effect", upNames, false);
|
||||
UIK.Btn(UIK.Money(price), () =>
|
||||
{
|
||||
if (!can) { Sfx.Play("error", 0.7f); return; }
|
||||
_p.UpgradeRpc();
|
||||
Sfx.Play("cash_register", 0.9f);
|
||||
}, (can ? "btn btn-green" : "btn btn-grey") + " btn-small", up);
|
||||
}
|
||||
else UIK.Text(Loc.T("Fully upgraded."), "tune-effect", _body, false);
|
||||
}
|
||||
|
||||
var junction = _p.GetComponentInChildren<IJunction>();
|
||||
if (junction != null)
|
||||
{
|
||||
var row = UIK.El("tune-row", _body);
|
||||
var names = UIK.El("tune-names", row);
|
||||
UIK.Text(Loc.T("Mode"), "t-small t-dark", names, false);
|
||||
UIK.Text(Cap(junction.ModeName(_p.Mode.Value)), "tune-effect", names, false);
|
||||
UIK.Btn(Loc.T("CHANGE"), () => { _p.NextModeRpc(junction.ModeCount); Sfx.Play("ui_click", 0.7f); }, "btn btn-blue btn-small", row);
|
||||
}
|
||||
|
||||
string switchName = SwitchName();
|
||||
if (switchName != null)
|
||||
{
|
||||
var row = UIK.El("tune-row", _body);
|
||||
var names = UIK.El("tune-names", row);
|
||||
UIK.Text(switchName, "t-small t-dark", names, false);
|
||||
UIK.Text(_p.Switched ? SwitchOff() : _p.Upgrades == UpgradeKind.Silo ? Loc.T("Open: bundles go out to the belts.") : Loc.T("Running."), "tune-effect", names, false);
|
||||
UIK.Btn(_p.Switched ? (_p.Upgrades == UpgradeKind.Silo ? Loc.T("OPEN") : Loc.T("START")) : (_p.Upgrades == UpgradeKind.Silo ? Loc.T("SHUT") : Loc.T("STOP")), () => { _p.SwitchRpc(); Sfx.Play("ui_click", 0.7f); }, (_p.Switched ? "btn btn-green" : "btn btn-red") + " btn-small", row);
|
||||
}
|
||||
|
||||
if (kind == UpgradeKind.None && junction == null && switchName == null)
|
||||
UIK.Text(Loc.T("Nothing to set on this one."), "tune-effect", _body, false);
|
||||
UIK.Text(Loc.T("Upgrades are for the whole crew and come out of the shared wallet."), "t-small t-muted wrap", _body, false).style.marginTop = 10;
|
||||
}
|
||||
|
||||
string SwitchName()
|
||||
{
|
||||
switch (_p.Upgrades)
|
||||
{
|
||||
case UpgradeKind.Belt: return Loc.T("Belt");
|
||||
case UpgradeKind.Machine: return Loc.T("Machine");
|
||||
case UpgradeKind.Robot: return _p.GetComponent<Mowbot>() ? Loc.T("Robot") : null;
|
||||
case UpgradeKind.Silo: return Loc.T("Hatches");
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
string SwitchOff()
|
||||
{
|
||||
switch (_p.Upgrades)
|
||||
{
|
||||
case UpgradeKind.Belt: return Loc.T("Stopped: what's on it waits where it is.");
|
||||
case UpgradeKind.Robot: return Loc.T("Stopped: it waits where it is.");
|
||||
case UpgradeKind.Silo: return Loc.T("Shut: everything stays in the silo.");
|
||||
default: return Loc.T("Paused: it takes grass in but doesn't work it.");
|
||||
}
|
||||
}
|
||||
|
||||
static string Cap(string s) => string.IsNullOrEmpty(s) ? s : char.ToUpper(s[0], Loc.Culture) + s.Substring(1);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/PieceScreen.cs.meta
Normal file
2
Assets/Scripts/UI/PieceScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f5393791320a3414ca744f54cf924685
|
||||
319
Assets/Scripts/UI/ShopScreen.cs
Normal file
319
Assets/Scripts/UI/ShopScreen.cs
Normal file
@ -0,0 +1,319 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The upgrade matrix as node graphs: the GreenHaul console shows CONTAINERS · CUTTING · SUIT · LOGISTICS · ECONOMY,
|
||||
/// each branch growing out of the free Earth Uplink, the garage shows the FLEET. Click a node to inspect it, buy it from
|
||||
/// the shared crew wallet.
|
||||
/// </summary>
|
||||
public class ShopScreen
|
||||
{
|
||||
public VisualElement Card { get; }
|
||||
readonly Label _money, _installs;
|
||||
readonly Action _close;
|
||||
public static readonly PerkTree[] TerminalTrees = { PerkTree.Containers, PerkTree.Cutting, PerkTree.Suit, PerkTree.Logistics, PerkTree.Economy };
|
||||
readonly PerkTree[] _trees;
|
||||
bool Hub => _trees == TerminalTrees;
|
||||
int TreeCount => _trees.Length;
|
||||
readonly Button[] _tabs;
|
||||
readonly Label[] _tabBadges;
|
||||
readonly VisualElement _graph, _canvas, _lines, _detail;
|
||||
readonly Dictionary<PerkId, VisualElement> _nodes = new Dictionary<PerkId, VisualElement>();
|
||||
VisualElement _hubNode;
|
||||
PerkTree _tree = PerkTree.Containers;
|
||||
PerkId _selected = PerkId.BinScissors;
|
||||
|
||||
const float ColW = 236f, RowH = 196f, Node = 112f, PadX = 30f, PadY = 22f;
|
||||
// the canvas fits the widest / deepest tree so every tab has the same scale
|
||||
static int MaxCol { get { int m = 0; foreach (var d in GameDefs.Perks) m = Mathf.Max(m, d.col); return m; } }
|
||||
static int MaxRow { get { int m = 0; foreach (var d in GameDefs.Perks) m = Mathf.Max(m, d.row); return m; } }
|
||||
static readonly float CanvasW = PadX * 2f + ColW * (MaxCol + 1), CanvasH = PadY + RowH * (MaxRow + 1) + Node + 64f;
|
||||
|
||||
static readonly string[] TreeNames = { Loc.N("CONTAINERS"), Loc.N("CUTTING"), Loc.N("SUIT"), Loc.N("LOGISTICS"), Loc.N("ECONOMY"), Loc.N("FLEET") };
|
||||
static readonly Color[] TreeColors =
|
||||
{
|
||||
new Color(0.9f, 0.72f, 0.24f), new Color(0.45f, 0.8f, 0.2f), new Color(0.85f, 0.75f, 0.4f), new Color(1f, 0.8f, 0.25f),
|
||||
new Color(0.25f, 0.7f, 0.45f), new Color(0.75f, 0.45f, 0.25f),
|
||||
};
|
||||
|
||||
TeamState Ts => TeamState.Instance;
|
||||
|
||||
public ShopScreen(VisualElement layer, Action close, PerkTree[] trees = null, string title = null)
|
||||
{
|
||||
_close = close;
|
||||
_trees = trees ?? TerminalTrees;
|
||||
_tabs = new Button[_trees.Length];
|
||||
_tabBadges = new Label[_trees.Length];
|
||||
_tree = _trees[0];
|
||||
Card = UIK.El("card shop", layer);
|
||||
Card.pickingMode = PickingMode.Position;
|
||||
var header = UIK.El("card-header", Card);
|
||||
var left = UIK.El(null, header);
|
||||
left.style.flexDirection = FlexDirection.Row;
|
||||
left.style.alignItems = Align.Center;
|
||||
UIK.Text(title ?? Loc.T("UPGRADE MATRIX"), "t-h1 t-dark", left).style.marginRight = 20;
|
||||
if (_trees == TerminalTrees) _installs = UIK.Text("", "t-h2 t-muted", left);
|
||||
|
||||
var right = UIK.El(null, header);
|
||||
right.style.flexDirection = FlexDirection.Row;
|
||||
right.style.alignItems = Align.Center;
|
||||
var wallet = UIK.El("pill", right);
|
||||
UIK.Img(AssetBank.I.Tex("icon_coin"), "check-icon", wallet);
|
||||
_money = UIK.Text("$0", "t-h2 t-dark", wallet);
|
||||
wallet.style.marginRight = 16;
|
||||
UIK.Btn("X", close, "btn btn-red btn-small", right);
|
||||
|
||||
// tree tabs get their own row so they never collide with the wallet
|
||||
var tabs = UIK.El("shop-tabs", Card);
|
||||
for (int i = 0; i < TreeCount; i++)
|
||||
{
|
||||
int t = i;
|
||||
// label as a child: a Button that has children is no longer measured by its own text
|
||||
_tabs[i] = UIK.Btn("", () => SetTree(_trees[t], true), "tab", tabs);
|
||||
UIK.Text(Loc.T(TreeNames[(int)_trees[i]]), "tab-label", _tabs[i]).pickingMode = PickingMode.Ignore;
|
||||
_tabBadges[i] = UIK.Text("", "tab-badge", _tabs[i]);
|
||||
}
|
||||
|
||||
var body = UIK.El("tree-body", Card);
|
||||
_graph = UIK.El("tree-graph", body);
|
||||
// nodes live on a fixed-size canvas that is scaled down to fit whatever room the graph gets
|
||||
_canvas = UIK.El("tree-canvas", _graph);
|
||||
_canvas.pickingMode = PickingMode.Ignore;
|
||||
_canvas.style.width = CanvasW; _canvas.style.height = CanvasH;
|
||||
_graph.RegisterCallback<GeometryChangedEvent>(_ => FitCanvas());
|
||||
_lines = UIK.El("tree-lines", _canvas);
|
||||
_lines.pickingMode = PickingMode.Ignore;
|
||||
_lines.generateVisualContent += DrawLines;
|
||||
_detail = UIK.El("tree-detail", body);
|
||||
|
||||
TeamState.Changed += Refresh;
|
||||
Card.RegisterCallback<DetachFromPanelEvent>(_ => TeamState.Changed -= Refresh);
|
||||
// open on the first tree that has something affordable
|
||||
// a single tree needs no tab row
|
||||
if (TreeCount == 1) tabs.style.display = DisplayStyle.None;
|
||||
for (int i = 0; i < TreeCount; i++) if (Affordable(_trees[i]) > 0) { _tree = _trees[i]; break; }
|
||||
SetTree(_tree, true);
|
||||
}
|
||||
|
||||
int Affordable(PerkTree tree)
|
||||
{
|
||||
var ts = Ts;
|
||||
if (!ts) return 0;
|
||||
int n = 0;
|
||||
foreach (var d in GameDefs.Perks)
|
||||
if (d.tree == tree && ts.Level(d.id) < d.maxLevel && ts.PerkAvailable(d) && ts.Money.Value >= d.PriceFor(ts.Level(d.id))) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
public void SetTree(PerkTree tree, bool animate)
|
||||
{
|
||||
_tree = tree;
|
||||
for (int i = 0; i < TreeCount; i++) _tabs[i].EnableInClassList("tab-on", _trees[i] == tree);
|
||||
// select the cheapest thing you can buy right now, else the root
|
||||
PerkDef pick = null;
|
||||
var ts = Ts;
|
||||
foreach (var d in GameDefs.Perks)
|
||||
{
|
||||
if (d.tree != tree) continue;
|
||||
if (pick == null) pick = d;
|
||||
if (ts && ts.Level(d.id) < d.maxLevel && ts.PerkAvailable(d) && (pick == null || !ts.PerkAvailable(pick) || ts.Level(pick.id) >= pick.maxLevel || d.PriceFor(ts.Level(d.id)) < pick.PriceFor(ts.Level(pick.id))))
|
||||
pick = d;
|
||||
}
|
||||
if (pick != null) _selected = pick.id;
|
||||
Rebuild(animate);
|
||||
}
|
||||
|
||||
void Refresh() => Rebuild(false);
|
||||
|
||||
void FitCanvas()
|
||||
{
|
||||
var r = _graph.contentRect;
|
||||
if (r.width < 1f || r.height < 1f) return;
|
||||
float k = Mathf.Min(1f, Mathf.Min(r.width / CanvasW, r.height / CanvasH));
|
||||
_canvas.style.transformOrigin = new TransformOrigin(0, 0);
|
||||
_canvas.style.scale = new Scale(new Vector3(k, k, 1f));
|
||||
_canvas.style.left = (r.width - CanvasW * k) * 0.5f;
|
||||
_canvas.style.top = (r.height - CanvasH * k) * 0.5f;
|
||||
}
|
||||
|
||||
Vector2 NodePos(PerkDef d) => new Vector2(PadX + d.col * ColW + (ColW - Node) * 0.5f, PadY + (d.row + (Hub ? 1 : 0)) * RowH);
|
||||
Vector2 NodeCenter(PerkDef d) => NodePos(d) + new Vector2(Node, Node) * 0.5f;
|
||||
static Vector2 HubPos => new Vector2(CanvasW * 0.5f - Node * 0.5f, PadY);
|
||||
|
||||
void Rebuild(bool animate)
|
||||
{
|
||||
var ts = Ts;
|
||||
if (!ts) return;
|
||||
_money.text = UIK.Money(ts.Money.Value);
|
||||
if (_installs != null) _installs.text = $"{ts.Installs} / {TeamState.TotalInstalls}";
|
||||
for (int i = 0; i < TreeCount; i++)
|
||||
{
|
||||
int n = Affordable(_trees[i]);
|
||||
_tabBadges[i].text = n > 0 ? n.ToString() : "";
|
||||
_tabBadges[i].style.display = n > 0 ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
}
|
||||
|
||||
// nodes
|
||||
foreach (var n in _nodes.Values) n.RemoveFromHierarchy();
|
||||
_nodes.Clear();
|
||||
_hubNode?.RemoveFromHierarchy();
|
||||
if (Hub)
|
||||
{
|
||||
_hubNode = UIK.El("node node-maxed", _canvas);
|
||||
_hubNode.style.left = HubPos.x; _hubNode.style.top = HubPos.y;
|
||||
UIK.Img(AssetBank.I.Tex("icon_star"), "node-icon", _hubNode);
|
||||
UIK.Text(Loc.T("Earth Uplink"), "node-name", _hubNode, false);
|
||||
}
|
||||
int k = 0;
|
||||
foreach (var d in GameDefs.Perks)
|
||||
{
|
||||
if (d.tree != _tree) continue;
|
||||
int lvl = ts.Level(d.id);
|
||||
bool maxed = lvl >= d.maxLevel;
|
||||
bool avail = ts.PerkAvailable(d);
|
||||
bool afford = avail && !maxed && ts.Money.Value >= d.PriceFor(lvl);
|
||||
var node = UIK.El("node", _canvas);
|
||||
node.pickingMode = PickingMode.Position;
|
||||
var pos = NodePos(d);
|
||||
node.style.left = pos.x; node.style.top = pos.y;
|
||||
node.AddToClassList(maxed ? "node-maxed" : lvl > 0 ? "node-owned" : !avail ? "node-locked" : afford ? "node-afford" : "node-available");
|
||||
if (d.id == _selected) node.AddToClassList("node-selected");
|
||||
var icon = UIK.Img(AssetBank.I.Tex(d.icon), "node-icon", node);
|
||||
icon.pickingMode = PickingMode.Ignore;
|
||||
if (!avail) UIK.Text("?", "node-lock t-outline", node).pickingMode = PickingMode.Ignore;
|
||||
if (d.maxLevel > 1) UIK.Text($"{lvl}/{d.maxLevel}", "node-level t-outline", node).pickingMode = PickingMode.Ignore;
|
||||
else if (lvl > 0) UIK.Text(Loc.T("OWNED"), "node-level t-outline", node).pickingMode = PickingMode.Ignore;
|
||||
var name = UIK.Text(d.name, "node-name", node, false);
|
||||
name.pickingMode = PickingMode.Ignore;
|
||||
var id = d.id;
|
||||
node.RegisterCallback<ClickEvent>(_ => { _selected = id; Sfx.Play("ui_click", 0.6f, 1.1f); Rebuild(false); });
|
||||
node.RegisterCallback<MouseEnterEvent>(_ => Sfx.Play("ui_hover", 0.35f, 1.2f));
|
||||
if (afford) Pulse(node);
|
||||
_nodes[d.id] = node;
|
||||
if (animate) UIK.PopIn(node, 0.03f * k, 0.35f);
|
||||
k++;
|
||||
}
|
||||
_lines.MarkDirtyRepaint();
|
||||
BuildDetail(animate);
|
||||
}
|
||||
|
||||
static void Pulse(VisualElement e)
|
||||
{
|
||||
Tween.Run(e, 1.2f, t => { if (e.panel != null) e.style.scale = new Scale(Vector3.one * (1f + Mathf.Sin(t * Mathf.PI * 2f) * 0.035f)); }, Ease.Linear, 0f, () => { if (e.panel != null) Pulse(e); });
|
||||
}
|
||||
|
||||
void DrawLines(MeshGenerationContext ctx)
|
||||
{
|
||||
var ts = Ts;
|
||||
if (!ts) return;
|
||||
var p = ctx.painter2D;
|
||||
p.lineCap = LineCap.Round;
|
||||
p.lineJoin = LineJoin.Round;
|
||||
foreach (var d in GameDefs.Perks)
|
||||
{
|
||||
if (d.tree != _tree) continue;
|
||||
if (Hub && d.requires.Length == 0) Link(p, HubPos + new Vector2(Node, Node) * 0.5f, NodeCenter(d), ts.Has(d.id));
|
||||
foreach (var r in d.requires)
|
||||
{
|
||||
var rd = GameDefs.Perk(r);
|
||||
// a root that needs a perk from another tree has no line to draw (the detail panel names it)
|
||||
if (rd.tree != d.tree) continue;
|
||||
Link(p, NodeCenter(rd), NodeCenter(d), ts.Has(d.id), ts.Has(r));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Link(Painter2D p, Vector2 a, Vector2 b, bool mine, bool have = true)
|
||||
{
|
||||
// outline then fill, so lines read like the chunky UI borders
|
||||
p.strokeColor = new Color(0.165f, 0.13f, 0.08f, 1f);
|
||||
p.lineWidth = 16f;
|
||||
Path(p, a, b);
|
||||
p.strokeColor = mine ? TreeColors[(int)_tree] : have ? new Color(1f, 1f, 1f) : new Color(0.78f, 0.8f, 0.66f);
|
||||
p.lineWidth = 9f;
|
||||
Path(p, a, b);
|
||||
}
|
||||
|
||||
static void Path(Painter2D p, Vector2 a, Vector2 b)
|
||||
{
|
||||
p.BeginPath();
|
||||
p.MoveTo(a);
|
||||
if (Mathf.Abs(a.x - b.x) < 1f) p.LineTo(b);
|
||||
else
|
||||
{
|
||||
float midY = (a.y + b.y) * 0.5f;
|
||||
p.BezierCurveTo(new Vector2(a.x, midY), new Vector2(b.x, midY), b);
|
||||
}
|
||||
p.Stroke();
|
||||
}
|
||||
|
||||
void BuildDetail(bool animate)
|
||||
{
|
||||
var ts = Ts;
|
||||
_detail.Clear();
|
||||
var d = GameDefs.Perk(_selected);
|
||||
if (d.tree != _tree) return;
|
||||
int lvl = ts.Level(d.id);
|
||||
bool maxed = lvl >= d.maxLevel;
|
||||
bool avail = ts.PerkAvailable(d);
|
||||
long price = d.PriceFor(lvl);
|
||||
bool afford = ts.Money.Value >= price;
|
||||
|
||||
var top = UIK.El("detail-top", _detail);
|
||||
top.style.backgroundColor = Color.Lerp(TreeColors[(int)_tree], Color.white, 0.55f);
|
||||
UIK.Img(AssetBank.I.Tex(d.icon), "detail-icon", top);
|
||||
UIK.Text(d.name, "t-h1 t-dark t-center detail-title", _detail);
|
||||
if (d.maxLevel > 1)
|
||||
{
|
||||
var pips = UIK.El("item-level detail-pips", _detail);
|
||||
for (int i = 0; i < d.maxLevel; i++) UIK.El(i < lvl ? "pip pip-on" : "pip", pips);
|
||||
}
|
||||
var desc = UIK.Text(d.desc, "item-desc t-center", _detail, false);
|
||||
desc.style.whiteSpace = WhiteSpace.Normal;
|
||||
if (d.effect != null)
|
||||
{
|
||||
var fx = UIK.El("detail-effect", _detail);
|
||||
if (lvl > 0) UIK.Text(Loc.F("NOW {0}", d.EffectFor(lvl)), "t-small t-muted", fx, false);
|
||||
if (!maxed) UIK.Text(Loc.F("NEXT {0}", d.EffectFor(lvl + 1)), "t-body t-dark", fx, false);
|
||||
}
|
||||
var spacer = UIK.El(null, _detail);
|
||||
spacer.style.flexGrow = 1;
|
||||
if (maxed) UIK.Text(d.maxLevel > 1 ? Loc.T("MAXED OUT!") : Loc.T("OWNED"), "price t-green t-outline t-center", _detail);
|
||||
else if (!avail)
|
||||
{
|
||||
var names = new List<string>();
|
||||
foreach (var r in d.requires) if (ts.Level(r) < d.requireLevel) names.Add(d.requireLevel > 1 ? $"{GameDefs.Perk(r).name} {GameDefs.ToRoman(d.requireLevel)}" : GameDefs.Perk(r).name);
|
||||
var req = UIK.Text(Loc.F("Requires {0}", string.Join(" + ", names)), "t-body t-muted t-center", _detail, false);
|
||||
req.style.whiteSpace = WhiteSpace.Normal;
|
||||
}
|
||||
else
|
||||
{
|
||||
var b = UIK.Btn(lvl > 0 ? Loc.F("UPGRADE {0}", UIK.Money(price)) : Loc.F("UNLOCK {0}", UIK.Money(price)), () => Buy(d, afford), afford ? "btn btn-green" : "btn btn-grey", _detail);
|
||||
b.style.alignSelf = Align.Stretch;
|
||||
}
|
||||
if (animate) UIK.SlideIn(_detail, new Vector2(40, 0), 0.05f, 0.3f);
|
||||
}
|
||||
|
||||
void Buy(PerkDef d, bool afford)
|
||||
{
|
||||
_nodes.TryGetValue(d.id, out var node);
|
||||
if (!afford)
|
||||
{
|
||||
Sfx.Play("error", 0.7f);
|
||||
if (node != null) UIK.Punch(node, 0.08f, 0.3f);
|
||||
Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn);
|
||||
return;
|
||||
}
|
||||
Ts.BuyPerkRpc((int)d.id);
|
||||
Sfx.Play("cash_register", 0.9f);
|
||||
if (node != null) UIK.Punch(node, 0.3f, 0.45f);
|
||||
var cam = CameraFx.Cam;
|
||||
if (cam) Fx.Confetti(cam.transform.position + cam.transform.forward * 1.6f - cam.transform.up * 0.5f, 60, 4f);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
2
Assets/Scripts/UI/ShopScreen.cs.meta
Normal file
2
Assets/Scripts/UI/ShopScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d8a26f0a8235e9148a1c9a49addd9ab2
|
||||
51
Assets/Scripts/UI/StationScreen.cs
Normal file
51
Assets/Scripts/UI/StationScreen.cs
Normal file
@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>The twelve stations with how far each is, and a ticket to the ones you've found.</summary>
|
||||
public class StationScreen
|
||||
{
|
||||
public VisualElement Card { get; }
|
||||
|
||||
public StationScreen(VisualElement layer, Action close)
|
||||
{
|
||||
Card = UIK.El("card", layer);
|
||||
Card.pickingMode = PickingMode.Position;
|
||||
Card.style.width = 620;
|
||||
var header = UIK.El("card-header", Card);
|
||||
UIK.Text(Loc.T("STATIONS"), "t-h1 t-dark", header);
|
||||
UIK.Btn("X", close, "btn btn-red btn-small", header);
|
||||
var ts = TeamState.Instance;
|
||||
var me = PlayerAgent.Local;
|
||||
if (!ts || !me) return;
|
||||
var list = new ScrollView(ScrollViewMode.Vertical);
|
||||
list.AddToClassList("tune-list");
|
||||
Card.Add(list);
|
||||
int here = Stations.Nearest(me.transform.position);
|
||||
var up = Planet.Up(me.transform.position);
|
||||
int hidden = 0;
|
||||
for (int i = 0; i < Stations.Count; i++)
|
||||
{
|
||||
int id = i;
|
||||
bool open = ts.StationOpen(i);
|
||||
if (!open) { hidden++; continue; }
|
||||
var row = UIK.El("tune-row", list.contentContainer);
|
||||
var names = UIK.El("tune-names", row);
|
||||
UIK.Text(Stations.Name(i), "t-small t-dark", names, false);
|
||||
float metres = Mathf.Acos(Mathf.Clamp(Vector3.Dot(up, Stations.Dir(i)), -1f, 1f)) * Planet.Radius;
|
||||
UIK.Text(Compass.Distance(metres), "tune-effect", names, false);
|
||||
bool can = i != here && ts.Money.Value >= GameDefs.TravelPrice;
|
||||
UIK.Btn(i == here ? Loc.T("HERE") : UIK.Money(GameDefs.TravelPrice), () =>
|
||||
{
|
||||
if (!can) { Sfx.Play("error", 0.7f); return; }
|
||||
ts.TravelRpc(id);
|
||||
Sfx.Play("cash_register", 0.9f);
|
||||
close();
|
||||
}, (can ? "btn btn-green" : "btn btn-grey") + " btn-small", row);
|
||||
}
|
||||
if (hidden > 0) UIK.Text(Loc.F("{0} more out there. Walk up to one and it opens.", hidden), "tune-effect", list.contentContainer, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/StationScreen.cs.meta
Normal file
2
Assets/Scripts/UI/StationScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7df1aa229c5800e4a9ac231a04642bde
|
||||
384
Assets/Scripts/UI/Studio.cs
Normal file
384
Assets/Scripts/UI/Studio.cs
Normal file
@ -0,0 +1,384 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Where the people on the video calls are filmed: far under the planet, out of every other camera's sight, each in a
|
||||
/// booth of their own with a camera rendering into a texture that the phone (or the HUD) shows. The booth has the
|
||||
/// mission-control picture behind its sitter and its own lamps, in a shader that takes no light from the planet's sun.
|
||||
/// </summary>
|
||||
public class Studio : MonoBehaviour
|
||||
{
|
||||
/// <summary>The layer nothing else draws.</summary>
|
||||
public const int Layer = 31;
|
||||
static readonly Vector3 Origin = new Vector3(0f, -9000f, 0f);
|
||||
|
||||
static Studio _i;
|
||||
readonly Dictionary<string, Booth> _booths = new Dictionary<string, Booth>();
|
||||
float _nextMask;
|
||||
|
||||
static Studio I
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_i && Application.isPlaying) _i = new GameObject("[Studio]").AddComponent<Studio>();
|
||||
return _i;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The booth for this model (SM_Dir_Boss, SM_Dir_Assistant), made the first time it's asked for.</summary>
|
||||
/// <param name="centreY">Height on the sitter the picture is centred on, metres.</param>
|
||||
/// <param name="width">How much of them, side to side, the picture takes in, metres.</param>
|
||||
public static Booth Get(string model, int w, int h, float centreY, float width)
|
||||
{
|
||||
var i = I;
|
||||
if (!i) return null;
|
||||
var key = $"{model}:{w}x{h}";
|
||||
if (i._booths.TryGetValue(key, out var b) && b != null && b.Root) return b;
|
||||
b = Booth.Make(model, w, h, centreY, width, Origin + Vector3.right * 40f * i._booths.Count, i.transform);
|
||||
i._booths[key] = b;
|
||||
return b;
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
// a -batchmode player (the dev bots) renders no camera by itself: the booths that are on are filmed by hand
|
||||
if (Application.isBatchMode)
|
||||
foreach (var b in _booths.Values)
|
||||
if (b != null && b.Cam && b.Cam.enabled) b.Cam.Render();
|
||||
// nothing else ever looks into the booths
|
||||
if (Time.unscaledTime < _nextMask) return;
|
||||
_nextMask = Time.unscaledTime + 1f;
|
||||
foreach (var c in Camera.allCameras)
|
||||
{
|
||||
bool ours = false;
|
||||
foreach (var b in _booths.Values) if (b != null && b.Cam == c) ours = true;
|
||||
if (!ours) c.cullingMask &= ~(1 << Layer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Booth
|
||||
{
|
||||
public Transform Root;
|
||||
public Camera Cam;
|
||||
public RenderTexture Rt;
|
||||
public Puppet Puppet;
|
||||
readonly List<Material> _skin = new List<Material>();
|
||||
|
||||
public static Booth Make(string model, int w, int h, float centreY, float width, Vector3 at, Transform parent)
|
||||
{
|
||||
var b = new Booth();
|
||||
var root = new GameObject("[Booth " + model + "]").transform;
|
||||
root.SetParent(parent, false);
|
||||
root.position = at;
|
||||
b.Root = root;
|
||||
var studio = AssetBank.I.Mat("M_Studio");
|
||||
var src = AssetBank.I.Model(model);
|
||||
if (!src || !studio)
|
||||
{
|
||||
Debug.LogWarning($"[Studio] missing {(src ? "M_Studio" : model)}");
|
||||
return b;
|
||||
}
|
||||
var sitter = Object.Instantiate(src, root);
|
||||
// the model keeps its own turn (the importer faces it along +Z of its parent): the booth's forward is its front
|
||||
sitter.transform.localPosition = Vector3.zero;
|
||||
foreach (var r in sitter.GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
r.receiveShadows = false;
|
||||
if (r is SkinnedMeshRenderer smr) smr.updateWhenOffscreen = true;
|
||||
var mats = r.sharedMaterials;
|
||||
for (int k = 0; k < mats.Length; k++)
|
||||
{
|
||||
var m = new Material(studio);
|
||||
var o = mats[k];
|
||||
string name = o ? o.name.Replace(" (Instance)", "") : "";
|
||||
var bank = AssetBank.I.Mat(name);
|
||||
Texture tex = o && o.HasProperty("_BaseMap") ? o.GetTexture("_BaseMap") : null;
|
||||
if (!tex && bank && bank.HasProperty("_BaseMap")) tex = bank.GetTexture("_BaseMap");
|
||||
if (tex) m.SetTexture("_BaseMap", tex);
|
||||
if (name.Contains("MouthVoid"))
|
||||
{
|
||||
m.SetColor("_BaseColor", new Color(0.03f, 0.015f, 0.02f));
|
||||
m.SetFloat("_Cull", 0f);
|
||||
}
|
||||
else b._skin.Add(m);
|
||||
mats[k] = m;
|
||||
}
|
||||
r.sharedMaterials = mats;
|
||||
}
|
||||
|
||||
// the picture: centred on centreY, `width` across
|
||||
float aspect = w / (float)h;
|
||||
const float fov = 20f;
|
||||
float viewH = width / aspect;
|
||||
float dist = viewH * 0.5f / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad);
|
||||
var camGo = new GameObject("Camera");
|
||||
camGo.transform.SetParent(root, false);
|
||||
camGo.transform.localPosition = new Vector3(0f, centreY, dist);
|
||||
camGo.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
|
||||
var cam = camGo.AddComponent<Camera>();
|
||||
cam.fieldOfView = fov;
|
||||
cam.nearClipPlane = 0.2f;
|
||||
cam.farClipPlane = dist + 8f;
|
||||
cam.cullingMask = 1 << Studio.Layer;
|
||||
cam.clearFlags = CameraClearFlags.SolidColor;
|
||||
cam.backgroundColor = new Color(0.1f, 0.16f, 0.3f);
|
||||
cam.depth = -50;
|
||||
var data = camGo.AddComponent<UniversalAdditionalCameraData>();
|
||||
data.renderShadows = false;
|
||||
data.renderPostProcessing = false;
|
||||
b.Rt = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4, name = "Booth " + model };
|
||||
b.Rt.Create();
|
||||
cam.targetTexture = b.Rt;
|
||||
cam.enabled = false;
|
||||
b.Cam = cam;
|
||||
|
||||
// mission control behind them
|
||||
var bg = AssetBank.I.Tex("T_Dir_Bg");
|
||||
var wall = GameObject.CreatePrimitive(PrimitiveType.Quad);
|
||||
Object.Destroy(wall.GetComponent<Collider>());
|
||||
wall.name = "Backdrop";
|
||||
wall.transform.SetParent(root, false);
|
||||
const float back = 2.2f;
|
||||
float wallH = 2f * (dist + back) * Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad) * 1.04f;
|
||||
float imgAspect = bg ? bg.width / (float)bg.height : 1f;
|
||||
float qh = Mathf.Max(wallH, wallH * aspect / imgAspect), qw = qh * imgAspect;
|
||||
wall.transform.localPosition = new Vector3(0f, centreY, -back);
|
||||
wall.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
|
||||
wall.transform.localScale = new Vector3(qw, qh, 1f);
|
||||
var wm = new Material(studio);
|
||||
wm.SetFloat("_Lit", 0f);
|
||||
if (bg) wm.SetTexture("_BaseMap", bg);
|
||||
wm.SetColor("_BaseColor", new Color(0.82f, 0.86f, 0.95f));
|
||||
wall.GetComponent<Renderer>().sharedMaterial = wm;
|
||||
|
||||
foreach (var t in root.GetComponentsInChildren<Transform>(true)) t.gameObject.layer = Studio.Layer;
|
||||
b.Puppet = new Puppet(sitter.transform, root);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Films while it's shown.</summary>
|
||||
public void Show(bool on)
|
||||
{
|
||||
if (Cam) Cam.enabled = on;
|
||||
}
|
||||
|
||||
/// <summary>Red in the face, 0..1.</summary>
|
||||
public void Flush(float k)
|
||||
{
|
||||
foreach (var m in _skin) m.SetColor("_Flush", new Color(0f, 0f, 0f, k));
|
||||
}
|
||||
|
||||
/// <summary>A point of the booth on the picture, in pixels of a w by h picture (y down).</summary>
|
||||
public Vector2 OnPicture(Vector3 world, float w, float h)
|
||||
{
|
||||
if (!Cam) return Vector2.zero;
|
||||
var v = Cam.WorldToViewportPoint(world);
|
||||
return new Vector2(v.x * w, (1f - v.y) * h);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Works a sitter like a South Park cut-out: the top of the head (bone Top, cut at the mouth by gc_director.py) tips up off
|
||||
/// one side of the head and then the other, a syllable each, about the hinges Hinge_L and Hinge_R; the arms swing at
|
||||
/// the shoulders, the head nods and shakes, the body breathes; eyes and lids, where the model has them, look and blink
|
||||
/// (CrewFace). Every turn is about the sitter's own axes, found from the bind pose.
|
||||
/// </summary>
|
||||
public class Puppet
|
||||
{
|
||||
readonly Transform _root, _top, _head, _body, _frame;
|
||||
readonly Transform[] _arm = new Transform[2], _fore = new Transform[2];
|
||||
readonly Vector3 _rootPos, _topPos;
|
||||
readonly Quaternion _topRot, _headRot, _bodyRot;
|
||||
readonly Quaternion[] _armRot = new Quaternion[2], _foreRot = new Quaternion[2];
|
||||
readonly Vector3[] _hinge = new Vector3[2];
|
||||
readonly float[] _hingeSign = new float[2], _armSign = new float[2], _foreSign = new float[2];
|
||||
readonly Vector3 _topFwd, _headRight, _headFwd, _headUp, _bodyRight;
|
||||
readonly Vector3[] _armFwd = new Vector3[2], _foreFwd = new Vector3[2], _armRight = new Vector3[2], _foreRight = new Vector3[2];
|
||||
readonly float[] _swingSign = new float[2], _liftSign = new float[2];
|
||||
// the pose as it is, easing toward where it's going: arms out, swung forward, forearms raised; the head
|
||||
readonly float[] _out = new float[2], _swing = new float[2], _lift = new float[2], _beat = new float[2];
|
||||
float _nod, _tilt, _yaw, _nextBeat;
|
||||
readonly float _nodSign = 1f, _leanSign = 1f;
|
||||
readonly CrewFace _face;
|
||||
readonly Dictionary<string, Transform> _anchors = new Dictionary<string, Transform>();
|
||||
int _side = 1;
|
||||
bool _syllable;
|
||||
float _shake, _lastT;
|
||||
|
||||
public Transform Top => _top;
|
||||
|
||||
/// <param name="frame">Faces the way the sitter does: forward is their front, right their right.</param>
|
||||
public Puppet(Transform sitter, Transform frame)
|
||||
{
|
||||
_root = sitter;
|
||||
_rootPos = sitter.localPosition;
|
||||
Transform hl = null, hr = null;
|
||||
foreach (var t in sitter.GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
switch (t.name)
|
||||
{
|
||||
case "Top": _top = t; break;
|
||||
case "Head": _head = t; break;
|
||||
case "Body": _body = t; break;
|
||||
case "Arm_L": _arm[0] = t; break;
|
||||
case "Arm_R": _arm[1] = t; break;
|
||||
case "Fore_L": _fore[0] = t; break;
|
||||
case "Fore_R": _fore[1] = t; break;
|
||||
case "Hinge_L": hl = t; break;
|
||||
case "Hinge_R": hr = t; break;
|
||||
}
|
||||
if (t.name.StartsWith("Anchor_")) _anchors[t.name.Substring(7)] = t;
|
||||
}
|
||||
var fwd = frame.forward;
|
||||
var up = frame.up;
|
||||
var right = frame.right;
|
||||
if (_top && _top.parent)
|
||||
{
|
||||
_topPos = _top.localPosition;
|
||||
_topRot = _top.localRotation;
|
||||
var p = _top.parent;
|
||||
_topFwd = p.InverseTransformDirection(fwd).normalized;
|
||||
var upP = p.InverseTransformDirection(up);
|
||||
var hs = new[] { hl, hr };
|
||||
for (int i = 0; i < 2; i++)
|
||||
_hinge[i] = hs[i] ? p.InverseTransformPoint(hs[i].position) : _topPos;
|
||||
// which way round lifts the far side: try a little turn about each hinge and see the other one go up
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
var other = _hinge[1 - i];
|
||||
var moved = _hinge[i] + Quaternion.AngleAxis(5f, _topFwd) * (other - _hinge[i]);
|
||||
_hingeSign[i] = Vector3.Dot(moved - other, upP) >= 0f ? 1f : -1f;
|
||||
}
|
||||
}
|
||||
if (_head && _head.parent)
|
||||
{
|
||||
_headRot = _head.localRotation;
|
||||
var p = _head.parent;
|
||||
_headRight = p.InverseTransformDirection(right).normalized;
|
||||
_headFwd = p.InverseTransformDirection(fwd).normalized;
|
||||
_headUp = p.InverseTransformDirection(up).normalized;
|
||||
if (_top) _nodSign = SignFor(_head, _headRight, _top, fwd);
|
||||
}
|
||||
if (_body && _body.parent)
|
||||
{
|
||||
_bodyRot = _body.localRotation;
|
||||
_bodyRight = _body.parent.InverseTransformDirection(right).normalized;
|
||||
if (_head) _leanSign = SignFor(_body, _bodyRight, _head, fwd);
|
||||
}
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
var a = _arm[i];
|
||||
if (!a || !a.parent) continue;
|
||||
_armRot[i] = a.localRotation;
|
||||
_armFwd[i] = a.parent.InverseTransformDirection(fwd).normalized;
|
||||
var probe = _fore[i] ? _fore[i] : a;
|
||||
var hand = _fore[i] && _fore[i].childCount > 0 ? _fore[i].GetChild(0) : probe;
|
||||
float lateral = Mathf.Sign(Vector3.Dot(probe.position - frame.position, right));
|
||||
_armSign[i] = SignFor(a, _armFwd[i], probe, right * lateral);
|
||||
_armRight[i] = a.parent.InverseTransformDirection(right).normalized;
|
||||
_swingSign[i] = SignFor(a, _armRight[i], probe, fwd);
|
||||
if (_fore[i] && _fore[i].parent)
|
||||
{
|
||||
_foreRot[i] = _fore[i].localRotation;
|
||||
_foreFwd[i] = _fore[i].parent.InverseTransformDirection(fwd).normalized;
|
||||
_foreSign[i] = SignFor(_fore[i], _foreFwd[i], hand, right * lateral);
|
||||
_foreRight[i] = _fore[i].parent.InverseTransformDirection(right).normalized;
|
||||
_liftSign[i] = SignFor(_fore[i], _foreRight[i], hand, fwd);
|
||||
}
|
||||
}
|
||||
_face = CrewFace.Find(sitter, frame);
|
||||
_frame = frame;
|
||||
}
|
||||
|
||||
/// <summary>The sign of a turn of t about axis (in t's parent space) that moves probe along want.</summary>
|
||||
static float SignFor(Transform t, Vector3 axis, Transform probe, Vector3 want)
|
||||
{
|
||||
var rest = t.localRotation;
|
||||
var p0 = probe.position;
|
||||
t.localRotation = Quaternion.AngleAxis(6f, axis) * rest;
|
||||
var p1 = probe.position;
|
||||
t.localRotation = rest;
|
||||
return Vector3.Dot(p1 - p0, want) >= 0f ? 1f : -1f;
|
||||
}
|
||||
|
||||
/// <summary>Where an effect goes: Forehead, Temple, Eye_L, Eye_R, Ear_L, Ear_R (falls back to the top of the head).</summary>
|
||||
public Vector3 Anchor(string name)
|
||||
{
|
||||
if (_anchors.TryGetValue(name, out var t) && t) return t.position;
|
||||
return _top ? _top.position + _frame.up * 0.15f : _frame.position + _frame.up * 1.1f;
|
||||
}
|
||||
|
||||
/// <param name="open">How far the mouth is open, 0..1.</param>
|
||||
/// <param name="mood">How much of each Mood shows, indexed by Mood.</param>
|
||||
public void Tick(float t, float open, float[] mood)
|
||||
{
|
||||
float dt = Mathf.Clamp(t - _lastT, 0f, 0.1f);
|
||||
if (t < _lastT) dt = 0f;
|
||||
_lastT = t;
|
||||
float angry = mood[(int)Mood.Angry], stern = mood[(int)Mood.Stern], happy = mood[(int)Mood.Happy];
|
||||
float sad = mood[(int)Mood.Sad], scared = mood[(int)Mood.Scared], whisper = mood[(int)Mood.Whisper];
|
||||
|
||||
// the jaw: each syllable the top tips up off one side, the next off the other
|
||||
if (open > 0.28f) _syllable = true;
|
||||
else if (open < 0.07f && _syllable) { _syllable = false; _side = 1 - _side; }
|
||||
_shake = Mathf.Lerp(_shake, Mathf.Max(open > 0.5f ? (open - 0.5f) * (1f + angry * 2f) : 0f, scared * 0.5f), dt * 10f);
|
||||
if (_top)
|
||||
{
|
||||
int i = _side;
|
||||
float ang = open * (11f + angry * 4f) * _hingeSign[i];
|
||||
var q = Quaternion.AngleAxis(ang, _topFwd);
|
||||
_top.localRotation = q * _topRot;
|
||||
_top.localPosition = _hinge[i] + q * (_topPos - _hinge[i]);
|
||||
}
|
||||
|
||||
// everything eases toward its pose, so nothing jerks
|
||||
float ease = 1f - Mathf.Exp(-dt * 9f);
|
||||
|
||||
// the head: nods a little with the words, hangs when he's sad, cocks when stern, shudders when he shouts
|
||||
if (_head)
|
||||
{
|
||||
_nod = Mathf.Lerp(_nod, Mathf.Sin(t * 2.3f) * 1.2f + open * 2.5f + sad * 8f - happy * 3f - scared * 2f, ease);
|
||||
_tilt = Mathf.Lerp(_tilt, Mathf.Sin(t * 0.7f) * 1.2f + stern * 3f, ease);
|
||||
_yaw = Mathf.Lerp(_yaw, Mathf.Sin(t * 0.45f) * 2f, ease);
|
||||
float shudder = Mathf.Sin(t * 31f) * _shake * 1.6f;
|
||||
_head.localRotation = Quaternion.AngleAxis(_yaw + shudder, _headUp) * Quaternion.AngleAxis(_tilt, _headFwd) * Quaternion.AngleAxis(_nod * _nodSign, _headRight) * _headRot;
|
||||
}
|
||||
// the body: breathing, bouncing when pleased, leaning in to whisper
|
||||
if (_body) _body.localRotation = Quaternion.AngleAxis((whisper * 7f + Mathf.Sin(t * 1.6f) * 0.6f) * _leanSign, _bodyRight) * _bodyRot;
|
||||
float hop = Mathf.Abs(Mathf.Sin(t * 7f)) * happy * 0.02f + Mathf.Sin(t * 1.6f) * 0.003f;
|
||||
_root.position = _frame.TransformPoint(_rootPos) + _frame.up * hop;
|
||||
|
||||
// the arms talk the way people's do: a forearm comes up in front with a word now and then, one hand and then the
|
||||
// other; both come up and shake when he shouts, higher when he's thrilled, they tremble in a fright and hang when
|
||||
// he's sad. They hardly go out to the side, where the coat's shoulders would stretch.
|
||||
if (t >= _nextBeat)
|
||||
{
|
||||
_nextBeat = t + Random.Range(0.7f, 1.6f);
|
||||
int hand = Random.value < 0.5f ? 0 : 1;
|
||||
_beat[hand] = open > 0.15f || Random.value < 0.3f ? Random.Range(0.5f, 1f) : 0f;
|
||||
_beat[1 - hand] *= 0.4f;
|
||||
}
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
if (!_arm[i]) continue;
|
||||
_beat[i] = Mathf.MoveTowards(_beat[i], 0f, dt * 0.35f);
|
||||
float shake = Mathf.Sin(t * 13f + i * 1.7f);
|
||||
float o = 1.5f + angry * 5f + happy * 12f + scared * 6f - sad * 1.5f;
|
||||
float sw = _beat[i] * 6f + angry * (8f + shake * 3f * Mathf.Max(open, 0.3f)) + happy * 6f + scared * 4f;
|
||||
float lf = _beat[i] * 32f + angry * (30f + shake * 6f) + happy * 45f + scared * (18f + Mathf.Sin(t * 37f + i) * 3f) - sad * 4f;
|
||||
_out[i] = Mathf.Lerp(_out[i], o, ease);
|
||||
_swing[i] = Mathf.Lerp(_swing[i], sw, ease);
|
||||
_lift[i] = Mathf.Lerp(_lift[i], Mathf.Max(0f, lf), ease);
|
||||
_arm[i].localRotation = Quaternion.AngleAxis(_out[i] * _armSign[i], _armFwd[i]) * Quaternion.AngleAxis(_swing[i] * _swingSign[i], _armRight[i]) * _armRot[i];
|
||||
if (_fore[i]) _fore[i].localRotation = Quaternion.AngleAxis(_lift[i] * _liftSign[i], _foreRight[i]) * _foreRot[i];
|
||||
}
|
||||
|
||||
_face?.Tick(dt, sad * -8f, angry > 0.3f || stern > 0.4f, scared > 0.3f || happy > 0.5f, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/Studio.cs.meta
Normal file
2
Assets/Scripts/UI/Studio.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 04f400cfd2d5103449936cae371e744e
|
||||
220
Assets/Scripts/UI/SupplyScreen.cs
Normal file
220
Assets/Scripts/UI/SupplyScreen.cs
Normal file
@ -0,0 +1,220 @@
|
||||
using System;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The supply wall: hand tools laid out with price tags, belt slots and gear, the selected item on the right. Tools
|
||||
/// and gear are personal, paid for from the crew wallet.
|
||||
/// </summary>
|
||||
public class SupplyScreen
|
||||
{
|
||||
const int SlotItem = GameDefs.ToolCount, JetItem = SlotItem + 1, BootItem = JetItem + 1, NightItem = BootItem + 1;
|
||||
|
||||
public VisualElement Card { get; }
|
||||
readonly Label _money;
|
||||
readonly VisualElement _grid, _detail;
|
||||
int _selected;
|
||||
|
||||
TeamState Ts => TeamState.Instance;
|
||||
PlayerAgent Me => PlayerAgent.Local;
|
||||
|
||||
public SupplyScreen(VisualElement layer, Action close)
|
||||
{
|
||||
Card = UIK.El("card shop", layer);
|
||||
Card.pickingMode = PickingMode.Position;
|
||||
var header = UIK.El("card-header", Card);
|
||||
UIK.Text(Loc.T("SUPPLY WALL"), "t-h1 t-dark", header);
|
||||
var right = UIK.El(null, header);
|
||||
right.style.flexDirection = FlexDirection.Row;
|
||||
right.style.alignItems = Align.Center;
|
||||
var wallet = UIK.El("pill", right);
|
||||
UIK.Img(AssetBank.I.Tex("icon_coin"), "check-icon", wallet);
|
||||
_money = UIK.Text("$0", "t-h2 t-dark", wallet);
|
||||
wallet.style.marginRight = 16;
|
||||
UIK.Btn("X", close, "btn btn-red btn-small", right);
|
||||
|
||||
var body = UIK.El("tree-body", Card);
|
||||
_grid = UIK.El("tree-graph supply-grid", body);
|
||||
_detail = UIK.El("tree-detail", body);
|
||||
|
||||
// a new tool lands on the belt a frame after the server says it's yours
|
||||
NetworkVariable<ushort>.OnValueChangedDelegate owned = (a, b) => Card.schedule.Execute(() => Rebuild(false)).ExecuteLater(60);
|
||||
NetworkVariable<byte>.OnValueChangedDelegate slots = (a, b) => Card.schedule.Execute(() => Rebuild(false)).ExecuteLater(60);
|
||||
var me = Me;
|
||||
if (me) { me.Owned.OnValueChanged += owned; me.BeltSlots.OnValueChanged += slots; }
|
||||
TeamState.Changed += Refresh;
|
||||
Card.RegisterCallback<DetachFromPanelEvent>(_ =>
|
||||
{
|
||||
TeamState.Changed -= Refresh;
|
||||
if (me) { me.Owned.OnValueChanged -= owned; me.BeltSlots.OnValueChanged -= slots; }
|
||||
});
|
||||
// open on the next thing to get
|
||||
foreach (var o in GameDefs.ToolOrder)
|
||||
if (me && !me.Owns(o)) { _selected = (int)o; break; }
|
||||
Rebuild(true);
|
||||
}
|
||||
|
||||
void Refresh() => Rebuild(false);
|
||||
|
||||
void Rebuild(bool animate)
|
||||
{
|
||||
var ts = Ts;
|
||||
var me = Me;
|
||||
if (!ts || !me) return;
|
||||
_money.text = UIK.Money(ts.Money.Value);
|
||||
_grid.Clear();
|
||||
foreach (var t in GameDefs.ToolOrder)
|
||||
{
|
||||
int i = (int)t;
|
||||
var d = GameDefs.Tool(t);
|
||||
string sub = GameDefs.IsBlade(t) ? Loc.F("{0:0.#} cm · {1:0.##} kg", ts.ToolWidth(t) * 100f, ts.ToolCap(t)) : Loc.T("Build menu");
|
||||
double price = ts.ToolPrice(d);
|
||||
string tag = me.Owns(t) ? (me.Tools.Belt.Contains(t) ? Loc.T("ON BELT") : Loc.T("OWNED")) : price <= 0d ? Loc.T("FREE") : UIK.Money(price);
|
||||
Item(i, d.icon, d.name, sub, tag, !me.Owns(t) && ts.Money.Value >= price, animate);
|
||||
}
|
||||
int slots = me.BeltSlots.Value;
|
||||
bool maxed = slots >= GameDefs.MaxBeltSlots;
|
||||
long slotPrice = GameDefs.BeltSlotPrice(slots);
|
||||
Item(SlotItem, "icon_perk_release", Loc.T("Belt Slot"), Loc.F("{0} / {1} slots", slots, GameDefs.MaxBeltSlots), maxed ? Loc.T("MAXED") : UIK.Money(slotPrice), !maxed && ts.Money.Value >= slotPrice, animate);
|
||||
Gear(JetItem, GearId.Jetpack, "icon_perk_jetpack", Loc.T("Jetpack"), Loc.T("Dash in the air"), animate);
|
||||
Gear(BootItem, GearId.Boots, "icon_perk_boots", Loc.T("Gravity Boots"), Loc.T("G: Earth's pull"), animate);
|
||||
Gear(NightItem, GearId.NightVision, "icon_perk_pure", Loc.T("Night Vision"), Loc.T("N: see in the dark"), animate);
|
||||
BuildDetail(animate);
|
||||
}
|
||||
|
||||
void Gear(int id, GearId g, string icon, string name, string sub, bool animate)
|
||||
{
|
||||
bool has = Me.HasGear(g);
|
||||
long price = GameDefs.GearPrice(g);
|
||||
Item(id, icon, name, sub, has ? Loc.T("OWNED") : UIK.Money(price), !has && Ts.Money.Value >= price, animate);
|
||||
}
|
||||
|
||||
void Item(int id, string icon, string name, string sub, string tag, bool afford, bool animate)
|
||||
{
|
||||
var e = UIK.El("supply-item", _grid);
|
||||
e.pickingMode = PickingMode.Position;
|
||||
e.EnableInClassList("supply-item-on", id == _selected);
|
||||
UIK.Img(AssetBank.I.Tex(icon), "supply-icon", e).pickingMode = PickingMode.Ignore;
|
||||
UIK.Text(name, "supply-name", e, false).pickingMode = PickingMode.Ignore;
|
||||
UIK.Text(sub, "supply-sub", e, false).pickingMode = PickingMode.Ignore;
|
||||
var t = UIK.Text(tag, "supply-tag", e, false);
|
||||
t.pickingMode = PickingMode.Ignore;
|
||||
t.EnableInClassList("supply-tag-afford", afford);
|
||||
e.RegisterCallback<ClickEvent>(_ => { _selected = id; Sfx.Play("ui_click", 0.6f, 1.1f); Rebuild(false); });
|
||||
e.RegisterCallback<MouseEnterEvent>(_ => Sfx.Play("ui_hover", 0.35f, 1.2f));
|
||||
if (animate) UIK.PopIn(e, 0.03f * id, 0.3f);
|
||||
}
|
||||
|
||||
void BuildDetail(bool animate)
|
||||
{
|
||||
var ts = Ts;
|
||||
var me = Me;
|
||||
_detail.Clear();
|
||||
string icon, title, desc;
|
||||
string[] stats;
|
||||
if (_selected == SlotItem)
|
||||
{
|
||||
icon = "icon_perk_release"; title = Loc.T("Belt Slot");
|
||||
desc = Loc.T("One more tool on your belt. Keys 1-6 or the wheel switch between them.");
|
||||
stats = new[] { Loc.F("NOW {0} of {1} slots", me.BeltSlots.Value, GameDefs.MaxBeltSlots) };
|
||||
}
|
||||
else if (_selected == JetItem)
|
||||
{
|
||||
icon = "icon_perk_jetpack"; title = Loc.T("Jetpack");
|
||||
desc = Loc.T("Double-tap SPACE in the air for a dash forward. Powered by... grass, obviously.");
|
||||
stats = new[] { Loc.F("Dash every {0:0.#} s", GameDefs.JetCooldown) };
|
||||
}
|
||||
else if (_selected == BootItem)
|
||||
{
|
||||
icon = "icon_perk_boots"; title = Loc.T("Gravity Boots");
|
||||
desc = Loc.T("Herbaria-7 pulls weakly. G clamps you down with Earth's gravity: you land fast, but you won't jump as high.");
|
||||
stats = new[] { Loc.F("Fall {0:0.#} instead of {1:0.#} m/s²", -me.gravity, GameDefs.LowGravity) };
|
||||
}
|
||||
else if (_selected == NightItem)
|
||||
{
|
||||
icon = "icon_perk_pure"; title = Loc.T("Night Vision");
|
||||
desc = Loc.T("N goes from the headlamp to night vision to nothing. Everything turns green, and you can see all the way to the horizon.");
|
||||
stats = new[] { Loc.T("Works as far as you can see") };
|
||||
}
|
||||
else
|
||||
{
|
||||
var t = (ToolId)_selected;
|
||||
var d = GameDefs.Tool(t);
|
||||
icon = d.icon; title = d.name; desc = d.desc;
|
||||
stats = GameDefs.IsBlade(t)
|
||||
? new[] { Loc.F("Strip width {0:0.#} cm", ts.ToolWidth(t) * 100f), Loc.F("Container {0:0.##} kg", ts.ToolCap(t)) }
|
||||
: new[] { Loc.T("Opens the build menu (B)") };
|
||||
}
|
||||
var top = UIK.El("detail-top", _detail);
|
||||
top.style.backgroundColor = new Color(0.9f, 0.8f, 0.55f);
|
||||
UIK.Img(AssetBank.I.Tex(icon), "detail-icon", top);
|
||||
UIK.Text(title, "t-h1 t-dark t-center detail-title", _detail);
|
||||
var dt = UIK.Text(desc, "item-desc t-center", _detail, false);
|
||||
dt.style.whiteSpace = WhiteSpace.Normal;
|
||||
var fx = UIK.El("detail-effect", _detail);
|
||||
foreach (var line in stats) UIK.Text(line, "t-body t-dark", fx, false);
|
||||
var spacer = UIK.El(null, _detail);
|
||||
spacer.style.flexGrow = 1;
|
||||
Action();
|
||||
if (animate) UIK.SlideIn(_detail, new Vector2(40, 0), 0.05f, 0.3f);
|
||||
}
|
||||
|
||||
/// <summary>The button of the selected item: buy it, put it on the belt, or take it in hand.</summary>
|
||||
void Action()
|
||||
{
|
||||
var ts = Ts;
|
||||
var me = Me;
|
||||
if (_selected == SlotItem)
|
||||
{
|
||||
int slots = me.BeltSlots.Value;
|
||||
if (slots >= GameDefs.MaxBeltSlots) { Done(Loc.T("MAXED OUT!")); return; }
|
||||
long price = GameDefs.BeltSlotPrice(slots);
|
||||
Buy(Loc.F("BUY {0}", UIK.Money(price)), ts.Money.Value >= price, () => ts.BuyBeltSlotRpc());
|
||||
}
|
||||
else if (_selected >= JetItem)
|
||||
{
|
||||
var g = _selected == JetItem ? GearId.Jetpack : _selected == BootItem ? GearId.Boots : GearId.NightVision;
|
||||
if (me.HasGear(g)) { Done(Loc.T("OWNED")); return; }
|
||||
long price = GameDefs.GearPrice(g);
|
||||
Buy(Loc.F("BUY {0}", UIK.Money(price)), ts.Money.Value >= price, () => ts.BuyGearRpc((byte)g));
|
||||
}
|
||||
else
|
||||
{
|
||||
var t = (ToolId)_selected;
|
||||
var tools = me.Tools;
|
||||
if (!me.Owns(t))
|
||||
{
|
||||
double price = ts.ToolPrice(GameDefs.Tool(t));
|
||||
Buy(price <= 0d ? Loc.T("TAKE IT") : Loc.F("BUY {0}", UIK.Money(price)), ts.Money.Value >= price, () => ts.BuyToolRpc((byte)t));
|
||||
}
|
||||
else if (tools.Current == t) Done(Loc.T("IN YOUR HANDS"));
|
||||
else
|
||||
{
|
||||
var b = UIK.Btn(tools.Belt.Contains(t) ? Loc.T("TAKE IN HAND") : Loc.T("PUT ON BELT"), () => { tools.Equip(t); Sfx.Play("plastic_grab", 0.6f); Rebuild(false); }, "btn btn-green", _detail);
|
||||
b.style.alignSelf = Align.Stretch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Done(string text) => UIK.Text(text, "price t-green t-outline t-center", _detail);
|
||||
|
||||
void Buy(string label, bool afford, Action buy)
|
||||
{
|
||||
var b = UIK.Btn(label, () =>
|
||||
{
|
||||
if (!afford)
|
||||
{
|
||||
Sfx.Play("error", 0.7f);
|
||||
Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn);
|
||||
return;
|
||||
}
|
||||
buy();
|
||||
Sfx.Play("cash_register", 0.9f);
|
||||
}, afford ? "btn btn-green" : "btn btn-grey", _detail);
|
||||
b.style.alignSelf = Align.Stretch;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/SupplyScreen.cs.meta
Normal file
2
Assets/Scripts/UI/SupplyScreen.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7b03d7a6907289642819ef2f948c1ac2
|
||||
84
Assets/Scripts/UI/TalkVideo.cs
Normal file
84
Assets/Scripts/UI/TalkVideo.cs
Normal file
@ -0,0 +1,84 @@
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Video;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A character's talking loops (Assets/StreamingAssets/Talk/<who>_<mood>.webm, VP8 with alpha, made by
|
||||
/// Tools/director/talk_videos.py): one player per mood, each looping into its own texture. The picture shows the one for
|
||||
/// the mood of the moment; the others wait where they left off, so a change of mood is a cut, not a stall.
|
||||
/// </summary>
|
||||
public class TalkVideo
|
||||
{
|
||||
readonly VideoPlayer[] _players;
|
||||
readonly RenderTexture[] _rts;
|
||||
int _on = -1;
|
||||
|
||||
/// <summary>The picture now; <see cref="Switched"/> says when it changes.</summary>
|
||||
public RenderTexture Rt => _rts[Mathf.Max(0, _on)];
|
||||
public System.Action<RenderTexture> Switched;
|
||||
|
||||
public TalkVideo(string who, string[] moods, int w, int h)
|
||||
{
|
||||
var go = new GameObject("Talk " + who);
|
||||
Object.DontDestroyOnLoad(go);
|
||||
_players = new VideoPlayer[moods.Length];
|
||||
_rts = new RenderTexture[moods.Length];
|
||||
for (int i = 0; i < moods.Length; i++)
|
||||
{
|
||||
var rt = new RenderTexture(w, h, 0, RenderTextureFormat.ARGB32) { name = $"Talk {who} {moods[i]}" };
|
||||
rt.Create();
|
||||
// see-through until the first frame is in
|
||||
var was = RenderTexture.active;
|
||||
RenderTexture.active = rt;
|
||||
GL.Clear(true, true, Color.clear);
|
||||
RenderTexture.active = was;
|
||||
var vp = go.AddComponent<VideoPlayer>();
|
||||
vp.playOnAwake = false;
|
||||
vp.source = VideoSource.Url;
|
||||
vp.url = Path.Combine(Application.streamingAssetsPath, "Talk", who + "_" + moods[i] + ".webm");
|
||||
vp.isLooping = true;
|
||||
vp.skipOnDrop = true;
|
||||
vp.audioOutputMode = VideoAudioOutputMode.None;
|
||||
vp.renderMode = VideoRenderMode.RenderTexture;
|
||||
vp.targetTexture = rt;
|
||||
vp.Prepare();
|
||||
_players[i] = vp;
|
||||
_rts[i] = rt;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plays the loop for this mood (and only it).</summary>
|
||||
public void Play(int mood)
|
||||
{
|
||||
mood = Mathf.Clamp(mood, 0, _players.Length - 1);
|
||||
if (mood != _on)
|
||||
{
|
||||
if (_on >= 0) _players[_on].Pause();
|
||||
_on = mood;
|
||||
Switched?.Invoke(_rts[mood]);
|
||||
}
|
||||
if (!_players[mood].isPlaying) _players[mood].Play();
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (_on >= 0) _players[_on].Pause();
|
||||
}
|
||||
|
||||
/// <summary>The Director: calm (and pleased), stern (and worried), furious.</summary>
|
||||
public static int BossMood(Mood m) => m == Mood.Angry ? 2 : m == Mood.Stern || m == Mood.Scared || m == Mood.Sad ? 1 : 0;
|
||||
|
||||
/// <summary>The assistant: cheerful, matter-of-fact, fed up.</summary>
|
||||
public static int AssistantMood(Mood m) => m == Mood.Stern ? 1 : m == Mood.Angry || m == Mood.Scared || m == Mood.Sad ? 2 : 0;
|
||||
|
||||
/// <summary>The strongest of the eased moods.</summary>
|
||||
public static Mood Strongest(float[] mood)
|
||||
{
|
||||
int best = 0;
|
||||
for (int i = 1; i < mood.Length; i++) if (mood[i] > mood[best]) best = i;
|
||||
return (Mood)best;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/TalkVideo.cs.meta
Normal file
2
Assets/Scripts/UI/TalkVideo.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 83090e29172506c4d8cdc0c610ed6f2f
|
||||
130
Assets/Scripts/UI/TreatHud.cs
Normal file
130
Assets/Scripts/UI/TreatHud.cs
Normal file
@ -0,0 +1,130 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The boosts you're on, as chips in the top left corner: the treat's picture, the boost's name and what it does, the time
|
||||
/// left and a bar running down. A chip pops in when the boost lands and blinks in its last ten seconds. Also the flash
|
||||
/// of colour over the whole screen at the moment a boost lands.
|
||||
/// </summary>
|
||||
public class TreatHud
|
||||
{
|
||||
static TreatHud _i;
|
||||
|
||||
readonly VisualElement _flash;
|
||||
readonly Chip[] _chips = new Chip[2];
|
||||
|
||||
class Chip
|
||||
{
|
||||
public VisualElement root, bar;
|
||||
public Label time;
|
||||
public bool shown;
|
||||
}
|
||||
|
||||
public TreatHud(VisualElement root)
|
||||
{
|
||||
_i = this;
|
||||
var col = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
col.style.position = Position.Absolute;
|
||||
col.style.left = 34; col.style.top = 30;
|
||||
col.style.flexDirection = FlexDirection.Column;
|
||||
root.Add(col);
|
||||
for (int i = 0; i < 2; i++) _chips[i] = MakeChip(col, (TreatId)i);
|
||||
|
||||
_flash = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
_flash.style.position = Position.Absolute;
|
||||
_flash.style.left = 0; _flash.style.top = 0; _flash.style.right = 0; _flash.style.bottom = 0;
|
||||
_flash.style.opacity = 0f;
|
||||
root.Add(_flash);
|
||||
|
||||
Treats.Started += OnStarted;
|
||||
col.schedule.Execute(Tick).Every(100);
|
||||
}
|
||||
|
||||
public void Detach() { Treats.Started -= OnStarted; }
|
||||
|
||||
Chip MakeChip(VisualElement parent, TreatId t)
|
||||
{
|
||||
var c = new Chip { root = new VisualElement { pickingMode = PickingMode.Ignore } };
|
||||
var r = c.root;
|
||||
r.style.flexDirection = FlexDirection.Row;
|
||||
r.style.alignItems = Align.Center;
|
||||
r.style.marginBottom = 8;
|
||||
r.style.paddingLeft = 8; r.style.paddingRight = 14; r.style.paddingTop = 6; r.style.paddingBottom = 6;
|
||||
r.style.backgroundColor = new Color(0.08f, 0.1f, 0.06f, 0.62f);
|
||||
r.style.borderTopLeftRadius = r.style.borderTopRightRadius = r.style.borderBottomLeftRadius = r.style.borderBottomRightRadius = 14;
|
||||
var edge = t == TreatId.Beer ? new Color(1f, 0.8f, 0.3f, 0.9f) : new Color(1f, 0.58f, 0.25f, 0.9f);
|
||||
r.style.borderLeftWidth = r.style.borderRightWidth = r.style.borderTopWidth = r.style.borderBottomWidth = 2;
|
||||
r.style.borderLeftColor = r.style.borderRightColor = r.style.borderTopColor = r.style.borderBottomColor = edge;
|
||||
r.style.display = DisplayStyle.None;
|
||||
parent.Add(r);
|
||||
|
||||
var icon = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
icon.style.width = 54; icon.style.height = 54; icon.style.marginRight = 10;
|
||||
var tex = AssetBank.I ? AssetBank.I.Tex(Treats.Icon(t)) : null;
|
||||
if (tex) icon.style.backgroundImage = new StyleBackground(tex);
|
||||
r.Add(icon);
|
||||
|
||||
var col = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
r.Add(col);
|
||||
UIK.Text(Treats.Boost(t), "t-body t-outline", col);
|
||||
var line = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
line.style.flexDirection = FlexDirection.Row;
|
||||
line.style.alignItems = Align.Center;
|
||||
col.Add(line);
|
||||
UIK.Text(Treats.Effect(t), "t-small t-outline", line);
|
||||
c.time = UIK.Text("", "t-small t-outline", line, false);
|
||||
c.time.style.marginLeft = 10;
|
||||
c.time.style.color = edge;
|
||||
var track = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
track.style.height = 5; track.style.marginTop = 4;
|
||||
track.style.backgroundColor = new Color(1f, 1f, 1f, 0.15f);
|
||||
track.style.borderTopLeftRadius = track.style.borderTopRightRadius = track.style.borderBottomLeftRadius = track.style.borderBottomRightRadius = 3;
|
||||
col.Add(track);
|
||||
c.bar = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
c.bar.style.height = Length.Percent(100);
|
||||
c.bar.style.backgroundColor = edge;
|
||||
c.bar.style.borderTopLeftRadius = c.bar.style.borderTopRightRadius = c.bar.style.borderBottomLeftRadius = c.bar.style.borderBottomRightRadius = 3;
|
||||
track.Add(c.bar);
|
||||
return c;
|
||||
}
|
||||
|
||||
void OnStarted(TreatId t)
|
||||
{
|
||||
var c = _chips[(int)t];
|
||||
c.root.style.display = DisplayStyle.Flex;
|
||||
c.shown = true;
|
||||
// a punch would kill the slide half way and leave the chip off the edge
|
||||
UIK.SlideIn(c.root, new Vector2(-260, 0), 0f, 0.45f);
|
||||
Tick();
|
||||
}
|
||||
|
||||
void Tick()
|
||||
{
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
var c = _chips[i];
|
||||
float left = Treats.Left((TreatId)i);
|
||||
if (left <= 0f)
|
||||
{
|
||||
if (c.shown) { c.shown = false; UIK.Fade(c.root, 0f, 0.3f, () => { c.root.style.display = DisplayStyle.None; c.root.style.opacity = 1f; }); }
|
||||
continue;
|
||||
}
|
||||
int s = Mathf.CeilToInt(left);
|
||||
c.time.text = $"{s / 60}:{s % 60:00}";
|
||||
c.bar.style.width = Length.Percent(100f * left / Treats.Seconds);
|
||||
c.root.style.opacity = left < 10f ? (Mathf.Repeat(Time.time * 2f, 1f) < 0.5f ? 1f : 0.45f) : 1f;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The whole screen washes with a colour for a moment and fades back.</summary>
|
||||
public static void Flash(Color c)
|
||||
{
|
||||
if (_i == null) return;
|
||||
var f = _i._flash;
|
||||
f.style.backgroundColor = new Color(c.r, c.g, c.b, 0.34f);
|
||||
Tween.Run(f, 0.7f, k => f.style.opacity = 1f - k, Ease.OutQuad);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/TreatHud.cs.meta
Normal file
2
Assets/Scripts/UI/TreatHud.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 968392e0d46bffe4880e1478ef675d79
|
||||
212
Assets/Scripts/UI/UIK.cs
Normal file
212
Assets/Scripts/UI/UIK.cs
Normal file
@ -0,0 +1,212 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Small UI Toolkit construction kit: fonts, buttons with sound, sliders, toggles and juicy animations.</summary>
|
||||
public static class UIK
|
||||
{
|
||||
public static Font Display, Body;
|
||||
|
||||
public static VisualElement El(string classes = null, VisualElement parent = null)
|
||||
{
|
||||
var e = new VisualElement { pickingMode = PickingMode.Ignore };
|
||||
AddClasses(e, classes);
|
||||
parent?.Add(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
public static Label Text(string text, string classes = null, VisualElement parent = null, bool display = true)
|
||||
{
|
||||
var l = new Label(text) { pickingMode = PickingMode.Ignore };
|
||||
AddClasses(l, classes);
|
||||
SetFont(l, display);
|
||||
parent?.Add(l);
|
||||
return l;
|
||||
}
|
||||
|
||||
public static void SetFont(VisualElement e, bool display)
|
||||
{
|
||||
var f = display ? Display : Body;
|
||||
if (f) e.style.unityFontDefinition = FontDefinition.FromFont(f);
|
||||
}
|
||||
|
||||
public static Button Btn(string text, Action onClick, string classes = "btn", VisualElement parent = null, bool sound = true)
|
||||
{
|
||||
var b = new Button(() =>
|
||||
{
|
||||
if (sound) Sfx.Play("ui_click", 0.8f, 1f, 0.04f);
|
||||
onClick?.Invoke();
|
||||
})
|
||||
{ text = text };
|
||||
b.focusable = false;
|
||||
AddClasses(b, classes);
|
||||
SetFont(b, true);
|
||||
b.RegisterCallback<PointerEnterEvent>(_ => { if (b.enabledSelf) Sfx.Play("ui_hover", 0.35f, 1f, 0.08f, 0.03f); });
|
||||
parent?.Add(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
public static VisualElement Img(Texture2D tex, string classes = null, VisualElement parent = null)
|
||||
{
|
||||
var e = El(classes, parent);
|
||||
if (tex) e.style.backgroundImage = new StyleBackground(tex);
|
||||
e.style.unityBackgroundScaleMode = ScaleMode.ScaleToFit;
|
||||
return e;
|
||||
}
|
||||
|
||||
public static void AddClasses(VisualElement e, string classes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(classes)) return;
|
||||
foreach (var c in classes.Split(' ')) if (c.Length > 0) e.AddToClassList(c);
|
||||
}
|
||||
|
||||
// ───────────────────────── widgets ─────────────────────────
|
||||
|
||||
/// <summary>Custom chunky slider. Returns a setter to update the value from code.</summary>
|
||||
public static Action<float> Slider(VisualElement parent, string label, float value, float min, float max, Func<float, string> fmt, Action<float> changed)
|
||||
{
|
||||
var row = El("setting", parent);
|
||||
Text(label, "setting-label", row, false);
|
||||
var track = El("slider", row);
|
||||
track.pickingMode = PickingMode.Position;
|
||||
var fill = El("slider-fill", track);
|
||||
var knob = El("slider-knob", track);
|
||||
var val = Text("", "setting-value", row, false);
|
||||
float current = value;
|
||||
|
||||
void Set(float v, bool notify)
|
||||
{
|
||||
current = Mathf.Clamp(v, min, max);
|
||||
float k = Mathf.InverseLerp(min, max, current);
|
||||
fill.style.width = Length.Percent(k * 100f);
|
||||
knob.style.left = Length.Percent(k * 100f);
|
||||
val.text = fmt(current);
|
||||
if (notify) changed?.Invoke(current);
|
||||
}
|
||||
|
||||
bool dragging = false;
|
||||
void FromPointer(Vector2 local)
|
||||
{
|
||||
float w = track.resolvedStyle.width;
|
||||
if (w <= 1f) return;
|
||||
Set(Mathf.Lerp(min, max, Mathf.Clamp01(local.x / w)), true);
|
||||
}
|
||||
track.RegisterCallback<PointerDownEvent>(e => { dragging = true; track.CapturePointer(e.pointerId); FromPointer(e.localPosition); Sfx.Play("ui_hover", 0.3f); });
|
||||
track.RegisterCallback<PointerMoveEvent>(e => { if (dragging) FromPointer(e.localPosition); });
|
||||
track.RegisterCallback<PointerUpEvent>(e => { dragging = false; track.ReleasePointer(e.pointerId); Sfx.Play("ui_click", 0.4f, 1.2f); });
|
||||
Set(value, false);
|
||||
return v => Set(v, false);
|
||||
}
|
||||
|
||||
public static void Toggle(VisualElement parent, string label, bool value, Action<bool> changed)
|
||||
{
|
||||
var row = El("setting", parent);
|
||||
Text(label, "setting-label", row, false);
|
||||
var t = El("toggle", row);
|
||||
t.pickingMode = PickingMode.Position;
|
||||
El("toggle-knob", t);
|
||||
bool on = value;
|
||||
t.EnableInClassList("toggle-on", on);
|
||||
t.RegisterCallback<ClickEvent>(_ =>
|
||||
{
|
||||
on = !on;
|
||||
t.EnableInClassList("toggle-on", on);
|
||||
Sfx.Play("ui_click", 0.7f, on ? 1.15f : 0.9f);
|
||||
changed?.Invoke(on);
|
||||
});
|
||||
}
|
||||
|
||||
public static void Choice(VisualElement parent, string label, string[] options, int value, Action<int> changed)
|
||||
{
|
||||
var row = El("setting", parent);
|
||||
Text(label, "setting-label", row, false);
|
||||
var box = El(null, row);
|
||||
box.style.flexDirection = FlexDirection.Row;
|
||||
var buttons = new Button[options.Length];
|
||||
for (int i = 0; i < options.Length; i++)
|
||||
{
|
||||
int idx = i;
|
||||
buttons[i] = Btn(options[i], () =>
|
||||
{
|
||||
for (int k = 0; k < buttons.Length; k++) buttons[k].EnableInClassList("tab-on", k == idx);
|
||||
changed?.Invoke(idx);
|
||||
}, "tab", box);
|
||||
buttons[i].EnableInClassList("tab-on", i == value);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── animation ─────────────────────────
|
||||
|
||||
public static void PopIn(VisualElement e, float delay = 0f, float duration = 0.42f)
|
||||
{
|
||||
e.style.scale = new Scale(Vector3.zero);
|
||||
e.style.opacity = 0f;
|
||||
Tween.Run(e, duration, k =>
|
||||
{
|
||||
e.style.scale = new Scale(new Vector3(k, k, 1));
|
||||
e.style.opacity = Mathf.Clamp01(k * 2f);
|
||||
}, Ease.OutBack, delay);
|
||||
}
|
||||
|
||||
public static void PopOut(VisualElement e, Action done = null, float duration = 0.18f)
|
||||
{
|
||||
Tween.Kill(e);
|
||||
Tween.Run(e, duration, k =>
|
||||
{
|
||||
float s = 1f - k;
|
||||
e.style.scale = new Scale(new Vector3(s, s, 1));
|
||||
e.style.opacity = 1f - k;
|
||||
}, Ease.InBack, 0f, done);
|
||||
}
|
||||
|
||||
public static void SlideIn(VisualElement e, Vector2 from, float delay = 0f, float duration = 0.5f)
|
||||
{
|
||||
e.style.translate = new Translate(from.x, from.y);
|
||||
e.style.opacity = 0f;
|
||||
Tween.Run(e, duration, k =>
|
||||
{
|
||||
e.style.translate = new Translate(Mathf.LerpUnclamped(from.x, 0, k), Mathf.LerpUnclamped(from.y, 0, k));
|
||||
e.style.opacity = Mathf.Clamp01(k * 1.5f);
|
||||
}, Ease.OutBack, delay);
|
||||
}
|
||||
|
||||
public static void Punch(VisualElement e, float amount = 0.25f, float duration = 0.35f)
|
||||
{
|
||||
Tween.Kill(e);
|
||||
// it may have cut a pop-in short: never leave the element see-through
|
||||
e.style.opacity = 1f;
|
||||
Tween.Run(e, duration, k =>
|
||||
{
|
||||
float s = 1f + Mathf.Sin(k * Mathf.PI * 2.5f) * (1f - k) * amount;
|
||||
e.style.scale = new Scale(new Vector3(s, s, 1));
|
||||
}, Ease.Linear, 0f, () => e.style.scale = new Scale(Vector3.one));
|
||||
}
|
||||
|
||||
public static void Fade(VisualElement e, float to, float duration, Action done = null)
|
||||
{
|
||||
float from = e.resolvedStyle.opacity;
|
||||
Tween.Kill(e);
|
||||
Tween.Run(e, duration, k => e.style.opacity = Mathf.Lerp(from, to, k), Ease.InOutQuad, 0f, done);
|
||||
}
|
||||
|
||||
/// <summary>Grass pays in cents, so small sums show them. Separators follow the interface language.</summary>
|
||||
public static string Money(double v)
|
||||
{
|
||||
if (v >= 100_000d) return Money((long)v);
|
||||
return "$" + v.ToString(System.Math.Abs(v - System.Math.Round(v)) < 0.005d ? "N0" : "N2", Loc.Culture);
|
||||
}
|
||||
|
||||
public static string Money(long v)
|
||||
{
|
||||
var c = Loc.Culture;
|
||||
if (v >= 1_000_000) return Loc.F("${0}M", (v / 1_000_000f).ToString(v >= 10_000_000 ? "0.#" : "0.##", c));
|
||||
if (v >= 100_000) return Loc.F("${0}K", (v / 1000f).ToString("0", c));
|
||||
return "$" + v.ToString("N0", c);
|
||||
}
|
||||
|
||||
/// <summary>A percentage the way the language writes it: "45%", "45 %", "%45".</summary>
|
||||
public static string Pct(float v01) => Loc.F("{0}%", Mathf.RoundToInt(v01 * 100f));
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/UIK.cs.meta
Normal file
2
Assets/Scripts/UI/UIK.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 941344d09614f514a824e4c923c6dae8
|
||||
348
Assets/Scripts/UI/UIRoot.Settings.cs
Normal file
348
Assets/Scripts/UI/UIRoot.Settings.cs
Normal file
@ -0,0 +1,348 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/UIRoot.Settings.cs.meta
Normal file
2
Assets/Scripts/UI/UIRoot.Settings.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4743269f1d14d9b4280cab1569e15127
|
||||
801
Assets/Scripts/UI/UIRoot.cs
Normal file
801
Assets/Scripts/UI/UIRoot.cs
Normal file
@ -0,0 +1,801 @@
|
||||
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) 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;
|
||||
|
||||
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 · AppID {SteamManager.AppId}" : Loc.T("Offline"), "t-small t-muted", pill, false);
|
||||
UIK.Text(Loc.F("v{0} · early build", 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/UI/UIRoot.cs.meta
Normal file
2
Assets/Scripts/UI/UIRoot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aa1fac4c21dc4c04da4128f182552b50
|
||||
Reference in New Issue
Block a user