Files
grass-cutters/Assets/Scripts/Gameplay/Mowbot.cs
NiemandKG df55b5e417 Smaller planets, 93% sectors, dearer late game, automation perks, autopilot, grass train
Not yet tried in the game: Unity could not get a licence (Unity Hub isn't
running), so this was only type-checked with Roslyn.

- Planets by area: the hard one half the old whole planet, normal a third of
  that, easy a sixth. Saves keep the size set they were made on (sizeGen 0).
- A sector closes at 93% mown.
- Mid and late prices go up (perks, machines, vehicles, tunes); the early
  game stays as it was.
- AUTOMATION perk tree: Long Leash (robot reach), Overdrive Motors, Bigger
  Hoppers, Long-Range Drones and Hive Mind.
- Autopilot, a garage tune for mowers: C hands the machine over. It mows the
  fields around in strokes, unloads at the nearest pad or the base yard and
  comes back. Getting in takes it back; it carries on after a load.
- Grass Train: lays its own track to a station next door, mowing under it,
  then runs back and forth cutting wider each run. Models in gc_train.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 11:39:02 +06:00

418 lines
18 KiB
C#

using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
public enum RobotMood : byte { Mowing, Travelling, Unloading, Waiting, Finished, NoCatcher }
/// <summary>
/// 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.
/// </summary>
public abstract class Mowbot : NetworkBehaviour, IInteractable, IPieceState
{
public static readonly List<Mowbot> All = new List<Mowbot>();
/// <summary>The demo's fast forward, on the server.</summary>
public static float Haste = 1f;
const float Tick = 0.2f, Overrun = 0.6f, IdleWait = 5f, TravelMul = 2.5f;
const float EngineVolume = 0.16f;
const int SearchLimit = 4000;
public readonly NetworkVariable<Vector3> At = new NetworkVariable<Vector3>();
public readonly NetworkVariable<bool> Mowing = new NetworkVariable<bool>();
public readonly NetworkVariable<float> Hopper = new NetworkVariable<float>();
public readonly NetworkVariable<byte> Mood = new NetworkVariable<byte>();
static readonly Dictionary<int, Mowbot> s_held = new Dictionary<int, Mowbot>();
static readonly Queue<(int id, int ring)> s_queue = new Queue<(int, int)>();
static readonly HashSet<int> s_seen = new HashSet<int>();
static readonly List<Vector3> s_rows = new List<Vector3>();
readonly List<Vector3> _way = new List<Vector3>();
readonly HashSet<int> _empty = new HashSet<int>();
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;
/// <summary>Where the body is drawn, smooth between the ticks that move At.</summary>
public Vector3 Shown => _shown;
/// <summary>For the test bots: how the body stands, as the eye sees it.</summary>
public Transform ShownBody => Body;
AudioSource _engine;
protected Vector3 Dir;
protected bool Homing;
public RobotDef Def => _def ?? (_def = GameDefs.Robot(GetComponent<BuildPiece>().piece));
BuildPiece _bp;
/// <summary>The dock's upgrade level makes the robot faster and its hopper bigger.</summary>
protected float Boost => (_bp ? _bp : (_bp = GetComponent<BuildPiece>())) ? _bp.TierMul : 1f;
public float HopperCap => Def.hopper * Boost * (TeamState.Instance ? TeamState.Instance.BotHopperMul : 1f);
/// <summary>The crew's automation perks.</summary>
protected float PerkSpeed => TeamState.Instance ? TeamState.Instance.BotSpeedMul : 1f;
public RobotMood Doing => (RobotMood)Mood.Value;
protected abstract Transform Body { get; }
/// <summary>The body's model has its nose on local -Z, so it is turned the other way round to go nose first.</summary>
protected virtual bool NoseOnBack => false;
protected abstract Vector3 Origin { get; }
protected abstract int Reach { get; }
protected virtual Vector3 HomeDir => Dir;
/// <summary>Unloading, or out of room: true keeps it where it is for this tick.</summary>
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;
_bobPhase = Random.value * 6.28f;
// each bot thinks on a frame of its own: two dozen robots planning their rows at once was a hitch
_clock = Random.value * Tick;
At.OnValueChanged += Heard;
_engine = Sfx.Loop(Def.hover > 0f ? "drone_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);
}
/// <summary>The hammer put it somewhere else: everything it had planned is off.</summary>
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;
}
/// <summary>The host cuts for real as it goes: the rest of the crew repeat the stroke they hear about.</summary>
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<BuildPiece>())) && _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;
// the heading is kept apart from the body: a flyer's lean and sway go on top of it when it is drawn, and must
// never be fed back in, or they pile up frame after frame and it rolls over
if (!_headed) { _heading = body.rotation; _headed = true; }
if (flat.sqrMagnitude < 0.01f) flat = Vector3.ProjectOnPlane(_heading * Vector3.forward * nose, up);
if (flat.sqrMagnitude < 1e-4f) return;
var was = _heading;
var turn = Quaternion.Slerp(was, Quaternion.LookRotation(flat * nose, up), 1f - Mathf.Exp(-6f * Time.deltaTime));
_heading = turn;
var pose = turn;
// it glides: no shake, no bob, the moving parts do the living
bool going = _leg < 1f && (_to - _from).sqrMagnitude > 1e-4f;
// a flyer hangs over the grass, bobbing a little, and leans into the way it goes
var at = _shown;
if (Def.hover > 0f)
{
at += up * (Def.hover + Mathf.Sin(Time.time * 1.9f + _bobPhase) * 0.15f);
_lean = Mathf.MoveTowards(_lean, going ? 6f : 0f, Time.deltaTime * 12f);
pose = turn * Quaternion.Euler(_lean * -nose, 0f, Mathf.Sin(Time.time * 1.3f + _bobPhase) * 1.5f);
}
body.SetPositionAndRotation(at, pose);
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<Transform> _sway = new List<Transform>();
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;
float _bobPhase, _lean;
Quaternion _heading;
bool _headed;
void Animate(Transform body, float turnRate, bool going)
{
if (!_parts)
{
_parts = true;
foreach (var c in body.GetComponentsInChildren<Transform>(true))
{
if (c.name.StartsWith("Spin") || c.name.StartsWith("Rotor")) _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<Renderer>();
_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);
}
}
// a flyer's rotors never stop: it would fall out of the sky
_spun += Time.deltaTime * (Def.hover > 0f ? 1900f : 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;
// on the way somewhere (to a sector, home to unload) it goes faster than it mows
float step = Def.speed * Boost * PerkSpeed * (Homing || _travel ? TravelMul : 1f) * 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;
}
/// <summary>Off to unload, then back to the very spot it left.</summary>
protected void GoHome()
{
if (_next < _way.Count) _way.Insert(_next, Dir);
_travel = true;
Homing = true;
}
// ───────────────────────── planning ─────────────────────────
/// <summary>Sectors around where it started, rings out to its reach.</summary>
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<int, bool> 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;
}
/// <summary>Rows across the sector, edge to edge, and only where there is something to cut.</summary>
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;
}
}