Files
grass-cutters/Assets/Scripts/Gameplay/Train.cs
NiemandKG 29485df9e1 Train and autopilot tried in the game: prefab, wagons upright, no circling
The train piece is in the scene's prefab list, its icon is made, and the
wagons keep the axis turn their FBX root brings. The autopilot gives up on a
point it has circled for seven seconds without getting closer, and takes sharp
turns close by slowly. -demoauto: on the easy planet the tractor unloads and
goes back to mowing, and the train lays 826 m of track to Timothy, closes 532
sectors and earns about 13.7k by the time its reach is mown.

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

439 lines
20 KiB
C#

using System.Collections.Generic;
using System.Linq;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The grass train. Built at a base, it lays its own track to a station next door (the one most in front of it, E picks
/// another while the track is short), mowing a strip under the rails all the way. Once the track gets there it runs
/// back and forth, its side cutters reaching one strip further out on every run until they reach as far as they can,
/// and what it cuts is paid for at either end. The host moves it; every peer draws the track and the train from the
/// same few numbers (where to, how much is laid, where the head is).
/// </summary>
public class Train : NetworkBehaviour, IInteractable, IPieceState
{
public Transform loco;
public Transform[] wagons;
/// <summary>Track points every two metres; the first stretch runs straight off the platform.</summary>
const float Step = 2f, Lead = 24f, StopShort = 16f;
/// <summary>Metres a second laying track and running on it, at Mk I.</summary>
const float LaySpeed = 2.4f, RunSpeed = 8f;
/// <summary>Strip cut under the rails, and the width each side cutter adds on a run.</summary>
const float Strip = 3.4f, Arm = 3f;
/// <summary>How far out the side cutters reach at Mk I, either side of the track.</summary>
const float Reach = 18f;
const float WaitAtEnd = 6f, Hold = 6000f, Gap = 5.2f, Gauge = 1.5f;
/// <summary>The station it is laying track to (255: not chosen yet).</summary>
public readonly NetworkVariable<byte> Target = new NetworkVariable<byte>(255);
/// <summary>Metres of track down.</summary>
public readonly NetworkVariable<float> Laid = new NetworkVariable<float>();
/// <summary>Where the locomotive is along the track, in metres from the platform.</summary>
public readonly NetworkVariable<float> At = new NetworkVariable<float>();
/// <summary>Runs since the track was finished: run n cuts the n-th strip out either side.</summary>
public readonly NetworkVariable<int> Runs = new NetworkVariable<int>();
public readonly NetworkVariable<float> Hopper = new NetworkVariable<float>();
readonly List<Vector3> _pts = new List<Vector3>();
readonly List<float> _cum = new List<float>();
float _length, _wait, _shown = -1f;
BuildPiece _bp;
BuildPiece Piece => _bp ? _bp : (_bp = GetComponent<BuildPiece>());
TeamState Ts => TeamState.Instance;
float Mul => (Piece ? Piece.TierMul : 1f) * (Ts ? Ts.BotSpeedMul : 1f);
float MaxOut => Reach * (Piece ? Piece.TierMul : 1f);
/// <summary>Where the train stands at home: far enough along for every wagon to be on the rails.</summary>
float HomeAt => Mathf.Min(_length, (wagons != null ? wagons.Length : 0) * Gap + 1f);
float Inner => Strip * 0.5f + (Runs.Value - 1) * Arm;
bool Laying => Laid.Value < _length - 0.01f;
bool RouteDone => !Laying && Runs.Value > 0 && Inner >= MaxOut;
// ───────────────────────── life ─────────────────────────
readonly List<(Transform t, Quaternion rest, float r)> _wheels = new List<(Transform, Quaternion, float)>();
Transform _reel;
Quaternion _reelRest;
float _rolled, _reelAngle, _lastShown = -1f;
void Awake()
{
// the wheels turn as it goes, the cutter reel on the nose spins while it cuts
foreach (var root in new[] { loco }.Concat(wagons ?? new Transform[0]))
{
if (!root) continue;
foreach (var t in root.GetComponentsInChildren<Transform>(true))
{
if (t.name.StartsWith("Wheel"))
{
var mf = t.GetComponent<MeshFilter>();
float rad = mf && mf.sharedMesh ? Mathf.Max(0.1f, mf.sharedMesh.bounds.extents.y) : 0.4f;
_wheels.Add((t, t.localRotation, rad));
}
else if (t.name == "Reel") { _reel = t; _reelRest = t.localRotation; }
}
}
}
public override void OnNetworkSpawn()
{
Target.OnValueChanged += (_, __) => Route();
if (IsServer && Target.Value == 255) Target.Value = Pick(-1);
Route();
}
public override void OnNetworkDespawn()
{
if (_track) Destroy(_track);
}
public override void OnDestroy()
{
if (_track) Destroy(_track);
base.OnDestroy();
}
/// <summary>A station next to the one this stands by, the most in front of it after <paramref name="after"/>.</summary>
byte Pick(int after)
{
var p = transform.position;
var up = Planet.Up(p);
var fwd = Vector3.ProjectOnPlane(transform.forward, up).normalized;
int home = Stations.Nearest(p);
var near = new List<(int i, float score)>();
for (int i = 0; i < Stations.Count; i++)
{
if (i == home) continue;
var d = Stations.Dir(i);
// the twelve stations stand on an icosahedron: the five next door are a dot of 0.447 away
if (Vector3.Dot(d, Stations.Dir(home)) < 0.3f) continue;
near.Add((i, Vector3.Dot(Vector3.ProjectOnPlane(d - up, up).normalized, fwd)));
}
if (near.Count == 0) return (byte)(home == 0 ? 1 : 0);
near.Sort((a, b) => b.score.CompareTo(a.score));
if (after < 0) return (byte)near[0].i;
int k = near.FindIndex(n => n.i == after);
return (byte)near[(k + 1) % near.Count].i;
}
void Route()
{
_pts.Clear();
_cum.Clear();
_length = 0f;
ClearTrack();
if (Target.Value >= Stations.Count) return;
var up = Planet.Up(transform.position);
var fwd = Vector3.ProjectOnPlane(transform.forward, up).normalized;
// from the buffer stop at the back of the platform
var a = transform.position - fwd * 3.6f;
var lead = Planet.Surface(a + fwd * Lead);
// off the platform in a straight ramp down to the ground
int n = Mathf.CeilToInt(Lead / Step);
for (int i = 0; i < n; i++)
{
var g = Planet.Surface(Vector3.Lerp(a, lead, i / (float)n));
float t = i / (float)n;
_pts.Add(Vector3.Lerp(a, g, Mathf.SmoothStep(0f, 1f, t)));
}
// then the great circle to the station, stopping short of its yard
var from = Planet.Up(lead);
var to = Stations.Dir(Target.Value);
float ang = Mathf.Acos(Mathf.Clamp(Vector3.Dot(from, to), -1f, 1f));
float full = ang * Planet.Radius, arc = Mathf.Max(Step, full - StopShort);
int m = Mathf.Max(1, Mathf.CeilToInt(arc / Step));
for (int j = 0; j <= m; j++) _pts.Add(Planet.OnSurface(Vector3.Slerp(from, to, j * arc / m / full)));
_cum.Add(0f);
for (int i = 1; i < _pts.Count; i++) _cum.Add(_cum[i - 1] + Vector3.Distance(_pts[i - 1], _pts[i]));
_length = _cum[_cum.Count - 1];
}
/// <summary>The point this far along the track.</summary>
Vector3 Pos(float d)
{
if (_pts.Count == 0) return transform.position;
d = Mathf.Clamp(d, 0f, _length);
int lo = 0, hi = _cum.Count - 1;
while (hi - lo > 1)
{
int mid = (lo + hi) >> 1;
if (_cum[mid] <= d) lo = mid; else hi = mid;
}
float seg = _cum[hi] - _cum[lo];
return Vector3.Lerp(_pts[lo], _pts[hi], seg > 1e-4f ? (d - _cum[lo]) / seg : 0f);
}
Vector3 Ahead(float d) => (Pos(d + 1f) - Pos(d - 1f)).normalized;
// ───────────────────────── the host runs it ─────────────────────────
void Update()
{
if (!IsSpawned) return;
if (IsServer && _length > 0f) Run(Time.deltaTime);
Draw();
}
void Run(float dt)
{
if (_wait > 0f) { _wait -= dt; return; }
if (Laying)
{
float was = Laid.Value, now = Mathf.Min(_length, was + LaySpeed * Mul * dt);
Laid.Value = now;
At.Value = now;
Cut(was, now, 0f, Strip);
if (!Laying) Arrive(1);
return;
}
if (Runs.Value <= 0) { Runs.Value = 1; return; }
bool done = RouteDone;
// odd runs come home, even ones go out; with nothing left in reach it goes home and waits there
float goal = done || Runs.Value % 2 == 1 ? HomeAt : _length;
float a = At.Value, b = Mathf.MoveTowards(a, goal, RunSpeed * Mul * dt);
if (b != a) At.Value = b;
if (!done) Cut(a, b, Inner, Mathf.Min(Arm, MaxOut - Inner));
if (Mathf.Abs(b - goal) < 0.01f)
{
if (done) Ship();
else Arrive(Runs.Value + 1);
}
}
void Arrive(int nextRun)
{
Ship();
_wait = WaitAtEnd;
Runs.Value = nextRun;
}
void Ship()
{
if (Hopper.Value <= 0.01f || !Ts) return;
Ts.DepositRpc(Hopper.Value, (byte)CargoKind.Grass, Pos(At.Value));
Hopper.Value = 0f;
}
/// <summary>Mows along the track from a to b: under it (offset 0), or a strip either side starting this far out.</summary>
void Cut(float a, float b, float offset, float width)
{
if (width <= 0.05f || Mathf.Abs(b - a) < 1e-4f) return;
float kg = 0f;
int n = Mathf.Max(1, Mathf.CeilToInt(Mathf.Abs(b - a) / Step));
for (int k = 0; k < n; k++)
{
float d0 = Mathf.Lerp(a, b, k / (float)n), d1 = Mathf.Lerp(a, b, (k + 1) / (float)n);
var p0 = Pos(d0);
var p1 = Pos(d1);
if (offset <= 0f) { kg += MowMap.Cut(Planet.Surface(p0), Planet.Surface(p1), width, 0f, MowMap.PaintFeather); continue; }
var up = Planet.Up(p0);
var side = Vector3.Cross(up, Ahead(d0)).normalized;
float o = offset + width * 0.5f;
kg += MowMap.Cut(Planet.Surface(p0 + side * o), Planet.Surface(p1 + side * o), width, 0f, MowMap.PaintFeather);
kg += MowMap.Cut(Planet.Surface(p0 - side * o), Planet.Surface(p1 - side * o), width, 0f, MowMap.PaintFeather);
}
Hopper.Value = Mathf.Min(Hold, Hopper.Value + kg * GameDefs.GrassDensity);
}
// ───────────────────────── what everyone sees ─────────────────────────
void Draw()
{
if (_length <= 0f) return;
float at = At.Value;
if (IsServer || _shown < 0f || Mathf.Abs(_shown - at) > 30f) _shown = at;
else _shown = Mathf.MoveTowards(_shown, at, (RunSpeed * 2.5f + Mathf.Abs(at - _shown) * 4f) * Time.deltaTime);
Place(loco, _shown, true);
if (wagons != null)
for (int i = 0; i < wagons.Length; i++)
{
float d = _shown - (i + 1) * Gap;
if (wagons[i]) wagons[i].gameObject.SetActive(d >= 0f);
if (d >= 0f) Place(wagons[i], d, true);
}
Lay(Laid.Value);
Spin();
}
void Spin()
{
float moved = _lastShown < 0f ? 0f : _shown - _lastShown;
_lastShown = _shown;
if (Mathf.Abs(moved) > 20f) moved = 0f;
_rolled += moved;
foreach (var (t, rest, r) in _wheels)
if (t) t.localRotation = rest * Quaternion.AngleAxis(_rolled / r * Mathf.Rad2Deg, Vector3.right);
if (_reel && Mathf.Abs(moved) > 1e-4f && !RouteDone)
{
_reelAngle += Time.deltaTime * 720f;
_reel.localRotation = _reelRest * Quaternion.AngleAxis(_reelAngle, Vector3.right);
}
}
/// <summary>How each model stands in its own frame (an FBX with one root object brings its axis turn on that root).</summary>
readonly Dictionary<Transform, Quaternion> _rest = new Dictionary<Transform, Quaternion>();
void Place(Transform t, float d, bool onRails)
{
if (!t) return;
if (!_rest.TryGetValue(t, out var rest)) _rest[t] = rest = t.localRotation;
var p = Pos(d);
var up = Planet.Up(p);
var f = Vector3.ProjectOnPlane(Ahead(d), up);
if (f.sqrMagnitude < 1e-6f) f = Vector3.ProjectOnPlane(transform.forward, up);
t.SetPositionAndRotation(p + up * (onRails ? 0.22f : 0f), Quaternion.LookRotation(f.normalized, up) * rest);
}
// ───────────────────────── the track ─────────────────────────
const int ChunkPts = 32;
GameObject _track;
readonly List<Mesh> _chunks = new List<Mesh>();
int _drawnSeg = -1;
void ClearTrack()
{
if (_track) Destroy(_track);
_track = null;
_chunks.Clear();
_drawnSeg = -1;
}
/// <summary>Rails and sleepers up to this many metres, a chunk of track at a time.</summary>
void Lay(float upto)
{
int seg = 0;
while (seg + 1 < _cum.Count && _cum[seg + 1] <= upto + 0.01f) seg++;
if (seg == _drawnSeg) return;
if (!_track)
{
_track = new GameObject("Track_" + NetworkObjectId);
_drawnSeg = -1;
}
int from = Mathf.Max(0, _drawnSeg) / ChunkPts, to = seg / ChunkPts;
for (int c = from; c <= to; c++) Chunk(c, seg);
_drawnSeg = seg;
}
void Chunk(int c, int lastSeg)
{
while (_chunks.Count <= c)
{
var go = new GameObject("Rails");
go.transform.SetParent(_track.transform, false);
var mesh = new Mesh { name = "Track" };
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var mr = go.AddComponent<MeshRenderer>();
var bank = AssetBank.I;
mr.sharedMaterials = new[] { bank ? bank.Mat("M_Steel") : null, bank ? bank.Mat("M_Wood") : null };
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
_chunks.Add(mesh);
}
var v = new List<Vector3>();
var nrm = new List<Vector3>();
var uv = new List<Vector2>();
var rails = new List<int>();
var ties = new List<int>();
int s0 = c * ChunkPts, s1 = Mathf.Min(lastSeg, s0 + ChunkPts);
for (int s = s0; s < s1; s++)
{
var a = _pts[s];
var b = _pts[s + 1];
var up = Planet.Up(a);
var f = (b - a).normalized;
var side = Vector3.Cross(up, f).normalized;
// two steel rails a little proud of the sleepers, one sleeper per two metres
for (int r = -1; r <= 1; r += 2)
{
var o = side * (r * Gauge * 0.5f) + up * 0.16f;
Box(v, nrm, uv, rails, a + o, b + o, side, up, 0.09f, 0.11f);
}
var mid = (a + b) * 0.5f + up * 0.06f;
Box(v, nrm, uv, ties, mid - f * 0.14f, mid + f * 0.14f, side, up, 2.2f, 0.12f);
}
var mesh2 = _chunks[c];
mesh2.Clear();
mesh2.SetVertices(v);
mesh2.SetNormals(nrm);
mesh2.SetUVs(0, uv);
mesh2.subMeshCount = 2;
mesh2.SetTriangles(rails, 0);
mesh2.SetTriangles(ties, 1);
mesh2.RecalculateBounds();
}
/// <summary>A box from a to b, this wide and this tall, standing on the line (no bottom face).</summary>
static void Box(List<Vector3> v, List<Vector3> n, List<Vector2> uv, List<int> tris, Vector3 a, Vector3 b, Vector3 side, Vector3 up, float w, float h)
{
var s = side * (w * 0.5f);
var t = up * h;
var f = (b - a).normalized;
Quad(v, n, uv, tris, a - s + t, a + s + t, b + s + t, b - s + t, up);
Quad(v, n, uv, tris, a + s, b + s, b + s + t, a + s + t, side);
Quad(v, n, uv, tris, b - s, a - s, a - s + t, b - s + t, -side);
Quad(v, n, uv, tris, a - s, a + s, a + s + t, a - s + t, -f);
Quad(v, n, uv, tris, b + s, b - s, b - s + t, b + s + t, f);
}
static void Quad(List<Vector3> v, List<Vector3> n, List<Vector2> uv, List<int> tris, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 normal)
{
int i = v.Count;
v.Add(p0); v.Add(p1); v.Add(p2); v.Add(p3);
for (int k = 0; k < 4; k++) n.Add(normal);
uv.Add(new Vector2(0, 0)); uv.Add(new Vector2(1, 0)); uv.Add(new Vector2(1, 1)); uv.Add(new Vector2(0, 1));
// Unity's front face: Cross(b - a, c - a) points at the viewer
var cross = Vector3.Cross(p1 - p0, p2 - p0);
if (Vector3.Dot(cross, normal) > 0f) { tris.Add(i); tris.Add(i + 1); tris.Add(i + 2); tris.Add(i); tris.Add(i + 2); tris.Add(i + 3); }
else { tris.Add(i); tris.Add(i + 2); tris.Add(i + 1); tris.Add(i); tris.Add(i + 3); tris.Add(i + 2); }
}
// ───────────────────────── talking to it ─────────────────────────
public string Prompt
{
get
{
string where = Target.Value < Stations.Count ? Stations.Name(Target.Value) : "?";
var def = GameDefs.Piece(PieceId.Train);
if (Laying)
{
string s = Loc.F("{0}: laying track to {1}, {2} of {3} m", def.name, where, Mathf.RoundToInt(Laid.Value), Mathf.RoundToInt(_length));
return Laid.Value < Lead ? s + " · " + Loc.T("E: another station") : s;
}
if (RouteDone) return Loc.F("{0}: the line to {1} is mown clean as far as it reaches. An upgrade reaches further.", def.name, where);
return Loc.F("{0}: running to {1} and back, cutting {2} m out either side, {3} on board", def.name, where, Mathf.RoundToInt(Inner + Arm), GameDefs.Kilos(Hopper.Value));
}
}
public bool CanInteract => Laying && Laid.Value < Lead;
public void Interact() => OtherWayRpc();
[Rpc(SendTo.Server)]
void OtherWayRpc()
{
if (!Laying || Laid.Value >= Lead) return;
Laid.Value = 0f;
At.Value = 0f;
Target.Value = Pick(Target.Value);
}
public float[] State
{
get => new[] { Target.Value, Laid.Value, At.Value, Runs.Value, Hopper.Value };
set
{
if (value == null || value.Length < 5 || !IsServer) return;
if (value[0] < Stations.Count) Target.Value = (byte)value[0];
Laid.Value = value[1];
At.Value = value[2];
Runs.Value = (int)value[3];
Hopper.Value = value[4];
}
}
}
}