using System.Collections.Generic; using Unity.Netcode; using UnityEngine; namespace GrassCutter { public enum RobotMood : byte { Mowing, Travelling, Unloading, Waiting, Finished, NoCatcher } /// /// A mower that drives itself. Only the server decides where it goes: it takes the nearest sector it may work and nobody else /// has, walks it row by row and says where it is five times a second. Every peer cuts what it hears, so the grass goes for all. /// public abstract class Mowbot : NetworkBehaviour, IInteractable, IPieceState { public static readonly List All = new List(); /// The demo's fast forward, on the server. public static float Haste = 1f; const float Tick = 0.2f, Overrun = 0.6f, IdleWait = 5f; const float EngineVolume = 0.16f; const int SearchLimit = 4000; public readonly NetworkVariable At = new NetworkVariable(); public readonly NetworkVariable Mowing = new NetworkVariable(); public readonly NetworkVariable Hopper = new NetworkVariable(); public readonly NetworkVariable Mood = new NetworkVariable(); static readonly Dictionary s_held = new Dictionary(); static readonly Queue<(int id, int ring)> s_queue = new Queue<(int, int)>(); static readonly HashSet s_seen = new HashSet(); static readonly List s_rows = new List(); readonly List _way = new List(); readonly HashSet _empty = new HashSet(); int _next, _sector = -1; bool _travel; float _clock, _idleUntil; // the body runs from where it was to the latest tick's spot at an even pace over one tick Vector3 _shown, _from, _to; float _leg = 1f; RobotDef _def; /// Where the body is drawn, smooth between the ticks that move At. public Vector3 Shown => _shown; /// For the test bots: how the body stands, as the eye sees it. public Transform ShownBody => Body; AudioSource _engine; protected Vector3 Dir; protected bool Homing; public RobotDef Def => _def ?? (_def = GameDefs.Robot(GetComponent().piece)); BuildPiece _bp; /// The dock's upgrade level makes the robot faster and its hopper bigger. protected float Boost => (_bp ? _bp : (_bp = GetComponent())) ? _bp.TierMul : 1f; public float HopperCap => Def.hopper * Boost; public RobotMood Doing => (RobotMood)Mood.Value; protected abstract Transform Body { get; } /// The body's model has its nose on local -Z, so it is turned the other way round to go nose first. protected virtual bool NoseOnBack => false; protected abstract Vector3 Origin { get; } protected abstract int Reach { get; } protected virtual Vector3 HomeDir => Dir; /// Unloading, or out of room: true keeps it where it is for this tick. protected abstract bool Stay(float dt); protected virtual void Arrived() { } protected abstract void NoWork(); public abstract string Prompt { get; } public bool CanInteract => true; public void Interact() => Sfx.Play("ui_click", 0.6f); public virtual float[] State { get => new[] { Hopper.Value, Dir.x, Dir.y, Dir.z }; set { if (value == null || value.Length < 4) return; Hopper.Value = value[0]; Seat(new Vector3(value[1], value[2], value[3]).normalized); } } protected string MoodText { get { switch (Doing) { case RobotMood.Mowing: return Loc.T("mowing"); case RobotMood.Unloading: return Loc.T("unloading"); case RobotMood.Waiting: return Loc.T("waiting for room, connect a belt"); case RobotMood.Finished: return Loc.T("everything in reach is mown"); case RobotMood.NoCatcher: return Loc.T("hopper full, needs a catcher with room"); default: return Loc.T("on the move"); } } } public override void OnNetworkSpawn() { All.Add(this); if (IsServer) Seat(Planet.Up(transform.position)); _shown = _from = _to = At.Value; At.OnValueChanged += Heard; _engine = Sfx.Loop("robot_mower_loop", Body, 0f); } public override void OnNetworkDespawn() { All.Remove(this); At.OnValueChanged -= Heard; Release(); if (_engine) Destroy(_engine.gameObject); } public override void OnDestroy() { All.Remove(this); Release(); base.OnDestroy(); } void Seat(Vector3 dir) { Dir = dir; At.Value = Planet.OnSurface(dir); } /// The hammer put it somewhere else: everything it had planned is off. public virtual void Moved(Vector3 at) { _empty.Clear(); _way.Clear(); _next = 0; if (IsServer) Release(); } protected void Teleported(Vector3 at) { _shown = _from = _to = at; _leg = 1f; if (IsServer) Seat(Planet.Up(at)); } void Release() { if (_sector >= 0 && s_held.TryGetValue(_sector, out var who) && who == this) s_held.Remove(_sector); _sector = -1; } /// The host cuts for real as it goes: the rest of the crew repeat the stroke they hear about. void Heard(Vector3 was, Vector3 now) { // a jump of more than a few ticks' walk is a teleport: no running there bool far = (now - _shown).sqrMagnitude > 400f; _from = far ? now : _shown; _to = now; _leg = far ? 1f : 0f; if (!IsServer && Mowing.Value && (now - was).sqrMagnitude < 400f) MowMap.Cut(was, now, Def.width, 0f, MowMap.PaintFeather); } void Update() { if (!IsSpawned) return; if (IsServer) { _clock += Time.deltaTime; if (_clock >= Tick) { _clock -= Tick; float dt = Tick * Haste; // stopped from its settings: it waits where it is if ((_bp ? _bp : (_bp = GetComponent())) && _bp.Switched) { Mowing.Value = false; Mood.Value = (byte)RobotMood.Waiting; } else if (!Stay(dt)) Walk(dt); } } Show(); if (_engine) { _engine.volume = Mathf.MoveTowards(_engine.volume, (Doing == RobotMood.Mowing ? EngineVolume : Doing == RobotMood.Travelling ? EngineVolume * 0.6f : 0f) * Sfx.SfxVolume, Time.deltaTime * 0.5f); _engine.pitch = Mathf.Lerp(1.5f, 1.1f, Def.width / 2f); } } void Show() { var body = Body; if (!body) return; var aim = _to; var up = Planet.Up(aim); var flat = Vector3.ProjectOnPlane(aim - _from, up); _leg = Mathf.Min(1f, _leg + Time.deltaTime / Tick); _shown = Vector3.Lerp(_from, _to, _leg); // the nose, where the cutter is, goes first float nose = NoseOnBack ? -1f : 1f; if (flat.sqrMagnitude < 0.01f) flat = Vector3.ProjectOnPlane(body.forward * nose, up); if (flat.sqrMagnitude < 1e-4f) return; var was = body.rotation; var turn = Quaternion.Slerp(was, Quaternion.LookRotation(flat * nose, up), 1f - Mathf.Exp(-6f * Time.deltaTime)); // it glides: no shake, no bob, the moving parts do the living bool going = _leg < 1f && (_to - _from).sqrMagnitude > 1e-4f; body.SetPositionAndRotation(_shown, turn); Animate(body, Vector3.SignedAngle(was * Vector3.forward, turn * Vector3.forward, up) / Mathf.Max(1e-3f, Time.deltaTime), going); } // ───────────────────────── looks ───────────────────────── // parts named for it by the model: Spin* turns while it mows, Blink* shuts now and then, Sway* springs about on its base readonly List<(Transform t, int axis)> _spin = new List<(Transform, int)>(); readonly List<(Transform t, int axis, Vector3 size)> _blink = new List<(Transform, int, Vector3)>(); readonly List _sway = new List(); readonly List<(Transform t, int axis, float radius)> _wheels = new List<(Transform, int, float)>(); Transform _fill; int _fillAxis = 1; float _roll, _level; bool _parts; float _spun, _nextBlink = 2f, _blinkAt = -1f, _swayX, _swayV, _wasGoing, _go; void Animate(Transform body, float turnRate, bool going) { if (!_parts) { _parts = true; foreach (var c in body.GetComponentsInChildren(true)) { if (c.name.StartsWith("Spin")) _spin.Add((c, BaseRot.LocalAxisFor(c, body.up))); else if (c.name.StartsWith("Blink")) _blink.Add((c, BaseRot.LocalAxisFor(c, body.up), c.localScale)); else if (c.name.StartsWith("Sway")) _sway.Add(c); else if (c.name.StartsWith("Wheel_")) { var r = c.GetComponent(); _wheels.Add((c, BaseRot.LocalAxisFor(c, body.right), r ? Mathf.Max(0.05f, r.bounds.extents.y) : 0.2f)); } else if (c.name == "Fill") { _fill = c; _fillAxis = BaseRot.LocalAxisFor(c, body.up); } if (c != body) BaseRot.Of(c); } } _spun += Time.deltaTime * (Mowing.Value ? 1400f : 0f); foreach (var (t, axis) in _spin) t.localRotation = BaseRot.Of(t) * Quaternion.AngleAxis(_spun, axis == 0 ? Vector3.right : axis == 1 ? Vector3.up : Vector3.forward); // the wheels roll with the ground going by, the clippings rise in the hopper // eased, so the frame between two steps doesn't read as a stop and a start _go = Mathf.MoveTowards(_go, going ? 1f : 0f, Time.deltaTime * 2.5f); float speed = (_to - _from).magnitude / Tick * _go; _roll += speed * Time.deltaTime * Mathf.Rad2Deg; foreach (var (t, axis, radius) in _wheels) t.localRotation = BaseRot.Of(t) * Quaternion.AngleAxis(_roll / radius, axis == 0 ? Vector3.right : axis == 1 ? Vector3.up : Vector3.forward); if (_fill) { _level = Mathf.Lerp(_level, Mathf.Clamp01(Hopper.Value / Mathf.Max(1f, HopperCap)), Time.deltaTime * 3f); var f = _fill.localScale; f[_fillAxis] = Mathf.Max(0.001f, _level); _fill.localScale = f; } // blink: shut over a tenth of a second, open again, every two to six seconds if (Time.time > _nextBlink) { _blinkAt = Time.time; _nextBlink = Time.time + Random.Range(2f, 6f); } float b = _blinkAt < 0f ? 1f : Mathf.Clamp01(Mathf.Abs(Time.time - _blinkAt - 0.08f) / 0.08f); foreach (var (t, axis, size) in _blink) { var s = size; s[axis] *= Mathf.Max(0.05f, b); t.localScale = s; } // the antenna whips back when it sets off or stops, and leans out of the turns float kick = _go - _wasGoing; _wasGoing = _go; _swayV += (-90f * _swayX - 5f * _swayV) * Time.deltaTime - kick * 2.5f + Mathf.Clamp(turnRate, -200f, 200f) * 0.0004f; _swayX += _swayV * Time.deltaTime; foreach (var t in _sway) t.localRotation = Quaternion.AngleAxis(_swayX * 40f, t.parent.InverseTransformDirection(body.right)) * BaseRot.Of(t); } // ───────────────────────── walking ───────────────────────── void Walk(float dt) { if (!Homing && _next >= _way.Count) { if (Time.time < _idleUntil) return; if (!FindWork()) { _idleUntil = Time.time + IdleWait; NoWork(); if (!Homing) return; } } var goal = Homing ? HomeDir : _way[_next]; var from = Planet.OnSurface(Dir); // not RotateTowards: it calls anything under a tenth of a degree "there already", and that is 4 m on this ball var gap = goal - Dir; float step = Def.speed * Boost * dt / Planet.Radius; if (gap.magnitude > step) Dir = (Dir + gap.normalized * step).normalized; else { Dir = goal; if (Homing) { Homing = false; Arrived(); } else { _next++; _travel = false; } } var to = Planet.OnSurface(Dir); if (Mowing.Value) Hopper.Value += MowMap.Cut(from, to, Def.width, 0f, MowMap.PaintFeather) * GameDefs.GrassDensity; Mowing.Value = !Homing && !_travel && _next < _way.Count; Mood.Value = (byte)(Mowing.Value ? RobotMood.Mowing : RobotMood.Travelling); At.Value = to; } /// Off to unload, then back to the very spot it left. protected void GoHome() { if (_next < _way.Count) _way.Insert(_next, Dir); _travel = true; Homing = true; } // ───────────────────────── planning ───────────────────────── /// Sectors around where it started, rings out to its reach. public int Area() { Spread(HexGrid.SectorAt(Planet.Up(Origin)), id => false); return s_seen.Count; } bool FindWork() { Release(); return Spread(HexGrid.SectorAt(Planet.Up(Origin)), TryPlan); } bool TryPlan(int id) { if (_empty.Contains(id) || MowMap.Cleared(id) >= 1f) return false; if (s_held.TryGetValue(id, out var who) && who) return false; Plan(id); if (_way.Count == 0) { _empty.Add(id); return false; } _sector = id; s_held[id] = this; return true; } bool Spread(int start, System.Func take) { s_seen.Clear(); s_queue.Clear(); s_seen.Add(start); s_queue.Enqueue((start, 0)); while (s_queue.Count > 0 && s_seen.Count < SearchLimit) { var (id, ring) = s_queue.Dequeue(); if (take(id)) return true; if (ring >= Reach) continue; foreach (int n in HexGrid.Get(id).neighbours) if (s_seen.Add(n)) s_queue.Enqueue((n, ring + 1)); } return false; } /// Rows across the sector, edge to edge, and only where there is something to cut. void Plan(int id) { _way.Clear(); _next = 0; _travel = true; var s = HexGrid.Get(id); MowMap.Rows(id, Def.width, s_rows); bool flip = false; foreach (var r in s_rows) { var a = Flat(s, r.y - Overrun, r.x); var b = Flat(s, r.z + Overrun, r.x); _way.Add(flip ? b : a); _way.Add(flip ? a : b); flip = !flip; } if (_way.Count > 1 && Vector3.Dot(_way[_way.Count - 1], Dir) > Vector3.Dot(_way[0], Dir)) _way.Reverse(); } static Vector3 Flat(HexGrid.Sector s, float u, float v) => (s.c * Planet.Radius + s.e1 * u + s.e2 * v).normalized; } }