- Map: the sectors are wound the screen's way (most were wound the other way and culled, leaving a blank chart), kept inside the chart, and drawn as ball, sectors and marks layers; the scale bar is no longer sized mid-draw. - Players' save keys are replicated, so a client's garage finds its machines and their upgrades; two players under one key get separate ones. - The grass train sends its mowing to the clients; moving the depot or resizing the planet relays its line. - A hard floor under vehicle springs: hard landings, steep rises and hand-overs no longer sink a machine. - Tests: -demosink, -demorep host|client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
835 lines
38 KiB
C#
835 lines
38 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; when they reach as far as they can it
|
|
/// lays the track on to the next station and works that stretch, until the line has been to every station it can reach.
|
|
/// Each station on the line has a yard at the end of the rails where machines unload: the train picks that up as it
|
|
/// passes and brings it home with what it cut, paid when it gets back. Anyone can ride in the cab and drive it (W, S).
|
|
/// Every upgrade adds a wagon, and the wagons hold more. 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 static readonly List<Train> All = new List<Train>();
|
|
|
|
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>Off the stretch it is mowing it runs this much faster; with a driver in the cab, this much.</summary>
|
|
const float Express = 3f, DriveSpeed = 2.5f;
|
|
/// <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, Gap = 5.2f, Gauge = 1.62f;
|
|
/// <summary>The top of the rails above the track line: the models' wheels stand on their origin.</summary>
|
|
const float RailTop = 0.27f;
|
|
/// <summary>What one wagon holds, what a yard holds waiting for the train, and how close a machine unloads at one.</summary>
|
|
const float PerWagon = 2000f, YardHolds = 20000f, YardRadius = 9f;
|
|
const int BaseWagons = 3;
|
|
const ulong NoRider = ulong.MaxValue;
|
|
|
|
/// <summary>The first station it lays track to (255: not chosen yet).</summary>
|
|
public readonly NetworkVariable<byte> Target = new NetworkVariable<byte>(255);
|
|
/// <summary>The stations after the first, in order: a four-bit count, then four bits each.</summary>
|
|
public readonly NetworkVariable<ulong> Legs = new NetworkVariable<ulong>();
|
|
/// <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 newest stretch 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>();
|
|
/// <summary>Who drives it from the cab (NoRider: nobody), and the lever: -1 back, 0 stop, 1 on.</summary>
|
|
public readonly NetworkVariable<ulong> Rider = new NetworkVariable<ulong>(NoRider);
|
|
public readonly NetworkVariable<sbyte> Drive = new NetworkVariable<sbyte>();
|
|
/// <summary>Grass unloaded in each station's yard, waiting for the train (one entry per station).</summary>
|
|
public NetworkList<float> Bins;
|
|
|
|
readonly List<Vector3> _pts = new List<Vector3>();
|
|
readonly List<float> _cum = new List<float>();
|
|
/// <summary>The stations on the line in order, where the track reaches each (metres), and where the stretch to each starts.</summary>
|
|
readonly List<int> _line = new List<int>();
|
|
readonly List<float> _stopAt = new List<float>();
|
|
readonly List<float> _legStart = new List<float>();
|
|
readonly List<Vector3> _yardAt = new List<Vector3>();
|
|
float _length, _wait, _shown = -1f;
|
|
bool _noMore;
|
|
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>Wagons on the train: three, and one more for every upgrade.</summary>
|
|
int WagonCount => Mathf.Min(wagons != null ? wagons.Length : 0, BaseWagons + (Piece ? Piece.Tier.Value : 0));
|
|
float Hold => PerWagon * Mathf.Max(1, WagonCount);
|
|
/// <summary>Where the train stands at home: far enough along for every wagon to be on the rails.</summary>
|
|
float HomeAt => Mathf.Min(_length, WagonCount * Gap + 2.5f);
|
|
/// <summary>Where the stretch it is working on starts: the side cutters only mow from here on.</summary>
|
|
float WorkFrom => _legStart.Count > 0 ? _legStart[_legStart.Count - 1] : 0f;
|
|
float Inner => Strip * 0.5f + (Runs.Value - 1) * Arm;
|
|
bool Laying => Laid.Value < _length - 0.01f;
|
|
bool Cutting => Inner < MaxOut;
|
|
public bool Ridden => Rider.Value != NoRider;
|
|
int Last => _line.Count > 0 ? _line[_line.Count - 1] : Target.Value;
|
|
|
|
// ───────────────────────── life ─────────────────────────
|
|
|
|
readonly List<(Transform t, Quaternion rest, float r)> _wheels = new List<(Transform, Quaternion, float)>();
|
|
readonly List<(Transform t, Vector3 rest)> _heaps = new List<(Transform, Vector3)>();
|
|
Transform _reel;
|
|
Quaternion _reelRest;
|
|
float _rolled, _reelAngle, _lastShown = -1f;
|
|
GameObject _cab;
|
|
BoxCollider _cabHit;
|
|
Vector3 _locoAt;
|
|
Quaternion _locoTurn = Quaternion.identity;
|
|
|
|
void Awake()
|
|
{
|
|
Bins = new NetworkList<float>();
|
|
// the prefab has three wagons: the rest are copies of the last, shown as the train is upgraded
|
|
var list = new List<Transform>((wagons ?? new Transform[0]).Where(w => w));
|
|
while (list.Count > 0 && list.Count < BaseWagons + GameDefs.MaxTier)
|
|
{
|
|
var src = list[list.Count - 1];
|
|
var copy = Instantiate(src.gameObject, src.parent).transform;
|
|
copy.name = src.name + "_" + list.Count;
|
|
list.Add(copy);
|
|
}
|
|
wagons = list.ToArray();
|
|
// the wheels turn as it goes, the cutter reel on the nose spins while it cuts, the heaps grow as it fills
|
|
foreach (var root in new[] { loco }.Concat(wagons))
|
|
{
|
|
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));
|
|
// how far the axles reach fore and aft: the model sits on the rails at its end axles
|
|
var lp = Vector3.Scale(root.InverseTransformPoint(t.position), root.localScale);
|
|
float z = Mathf.Abs((root.localRotation * lp).z);
|
|
_axles[root] = Mathf.Max(_axles.TryGetValue(root, out var had) ? had : 0f, z);
|
|
}
|
|
else if (t.name == "Reel") { _reel = t; _reelRest = t.localRotation; }
|
|
else if (t.name == "Grass" && root != loco) _heaps.Add((t, t.localScale));
|
|
}
|
|
}
|
|
// something to aim at and stand by: E on the locomotive gets you in the cab
|
|
if (loco)
|
|
{
|
|
_cab = new GameObject("Cab");
|
|
_cab.transform.SetParent(transform, false);
|
|
_cabHit = _cab.AddComponent<BoxCollider>();
|
|
_cabHit.center = new Vector3(0f, 1.45f, 0f);
|
|
_cabHit.size = new Vector3(2.1f, 2.5f, 4.7f);
|
|
var rb = _cab.AddComponent<Rigidbody>();
|
|
rb.isKinematic = true;
|
|
rb.useGravity = false;
|
|
}
|
|
}
|
|
|
|
public override void OnNetworkSpawn()
|
|
{
|
|
if (!All.Contains(this)) All.Add(this);
|
|
Target.OnValueChanged += (_, __) => Route();
|
|
Legs.OnValueChanged += (_, __) => Route();
|
|
Planet.Rescaled += Route;
|
|
if (IsServer)
|
|
{
|
|
while (Bins.Count < Stations.Count) Bins.Add(0f);
|
|
if (Target.Value == 255) Target.Value = Pick(-1);
|
|
}
|
|
Route();
|
|
}
|
|
|
|
/// <summary>Everyone: the depot was picked up and set down elsewhere. The line starts from there now, so it is laid again.</summary>
|
|
public void Moved()
|
|
{
|
|
if (IsServer)
|
|
{
|
|
Laid.Value = 0f;
|
|
At.Value = 0f;
|
|
Runs.Value = 0;
|
|
_wait = 0f;
|
|
_noMore = false;
|
|
}
|
|
_shown = 0f;
|
|
Route();
|
|
}
|
|
|
|
public override void OnNetworkDespawn()
|
|
{
|
|
Planet.Rescaled -= Route;
|
|
All.Remove(this);
|
|
if (_track) Destroy(_track);
|
|
}
|
|
|
|
public override void OnDestroy()
|
|
{
|
|
All.Remove(this);
|
|
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;
|
|
}
|
|
|
|
/// <summary>The station to lay on to from the end of the line: next door to it, not on the line yet, the most straight on.</summary>
|
|
int NextStation()
|
|
{
|
|
if (_line.Count == 0) return -1;
|
|
int home = Stations.Nearest(transform.position);
|
|
int last = _line[_line.Count - 1];
|
|
var at = Stations.Dir(last);
|
|
var from = _line.Count > 1 ? Stations.Dir(_line[_line.Count - 2]) : Planet.Up(transform.position);
|
|
var on = Vector3.ProjectOnPlane(at - from, at).normalized;
|
|
int best = -1;
|
|
float score = -2f;
|
|
for (int i = 0; i < Stations.Count; i++)
|
|
{
|
|
if (i == home || _line.Contains(i)) continue;
|
|
var d = Stations.Dir(i);
|
|
if (Vector3.Dot(d, at) < 0.3f) continue;
|
|
float s = Vector3.Dot(Vector3.ProjectOnPlane(d - at, at).normalized, on);
|
|
if (s > score) { score = s; best = i; }
|
|
}
|
|
return best;
|
|
}
|
|
|
|
static float Angle(Vector3 a, Vector3 b) => Mathf.Acos(Mathf.Clamp(Vector3.Dot(a, b), -1f, 1f));
|
|
|
|
void Add(Vector3 p)
|
|
{
|
|
if (_pts.Count > 0) _length += Vector3.Distance(_pts[_pts.Count - 1], p);
|
|
_pts.Add(p);
|
|
_cum.Add(_length);
|
|
}
|
|
|
|
void Route()
|
|
{
|
|
_pts.Clear();
|
|
_cum.Clear();
|
|
_line.Clear();
|
|
_stopAt.Clear();
|
|
_legStart.Clear();
|
|
_yardAt.Clear();
|
|
_length = 0f;
|
|
ClearTrack();
|
|
if (Target.Value >= Stations.Count) return;
|
|
_line.Add(Target.Value);
|
|
ulong legs = Legs.Value;
|
|
int extra = (int)(legs & 0xF);
|
|
for (int k = 0; k < extra; k++) _line.Add((int)((legs >> (4 + 4 * k)) & 0xF));
|
|
|
|
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;
|
|
Add(Vector3.Lerp(a, g, Mathf.SmoothStep(0f, 1f, t)));
|
|
}
|
|
var from = Planet.Up(lead);
|
|
for (int k = 0; k < _line.Count; k++)
|
|
{
|
|
var to = Stations.Dir(_line[k]);
|
|
if (k > 0)
|
|
{
|
|
// round the station it just reached, at the edge of its yard, and off toward the next one
|
|
var c = Stations.Dir(_line[k - 1]);
|
|
float sep = Angle(c, to);
|
|
var exit = Vector3.Slerp(c, to, Mathf.Clamp01(StopShort / Planet.Radius / Mathf.Max(1e-4f, sep)));
|
|
float turn = Vector3.SignedAngle(Vector3.ProjectOnPlane(from, c), Vector3.ProjectOnPlane(exit, c), c);
|
|
int steps = Mathf.Max(1, Mathf.CeilToInt(Mathf.Abs(turn) * Mathf.Deg2Rad * StopShort / Step));
|
|
for (int j = 1; j <= steps; j++) Add(Planet.OnSurface(Quaternion.AngleAxis(turn * j / steps, c) * from));
|
|
from = Planet.Up(_pts[_pts.Count - 1]);
|
|
}
|
|
_legStart.Add(k == 0 ? 0f : _length);
|
|
// the great circle to the station, stopping short of its yard
|
|
float full = Angle(from, to) * Planet.Radius, arc = Mathf.Max(Step, full - StopShort);
|
|
int m = Mathf.Max(1, Mathf.CeilToInt(arc / Step));
|
|
for (int j = k == 0 ? 0 : 1; j <= m; j++) Add(Planet.OnSurface(Vector3.Slerp(from, to, j * arc / m / full)));
|
|
_stopAt.Add(_length);
|
|
_yardAt.Add(_pts[_pts.Count - 1]);
|
|
from = Planet.Up(_pts[_pts.Count - 1]);
|
|
}
|
|
}
|
|
|
|
/// <summary>The point this far along the track, carried on straight past either end.</summary>
|
|
Vector3 PosOn(float d)
|
|
{
|
|
if (d < 0f) return Pos(0f) - Ahead(0f) * -d;
|
|
if (d > _length) return Pos(_length) + Ahead(_length) * (d - _length);
|
|
return Pos(d);
|
|
}
|
|
|
|
/// <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;
|
|
|
|
// ───────────────────────── yards ─────────────────────────
|
|
|
|
/// <summary>Is this spot in the yard of a station on some train's line (with room left)? Which train, which station.</summary>
|
|
public static bool YardAt(Vector3 p, out Train train, out int station)
|
|
{
|
|
foreach (var t in All)
|
|
{
|
|
if (!t || !t.IsSpawned) continue;
|
|
for (int k = 0; k < t._yardAt.Count; k++)
|
|
{
|
|
if (!t.YardOpen(k) || (t._yardAt[k] - p).sqrMagnitude > YardRadius * YardRadius) continue;
|
|
train = t;
|
|
station = t._line[k];
|
|
return true;
|
|
}
|
|
}
|
|
train = null;
|
|
station = -1;
|
|
return false;
|
|
}
|
|
|
|
/// <summary>Every yard a machine can unload in now, with its name, for the markers and the autopilot.</summary>
|
|
public static void Yards(List<(Vector3 at, string name)> into)
|
|
{
|
|
foreach (var t in All)
|
|
{
|
|
if (!t || !t.IsSpawned) continue;
|
|
for (int k = 0; k < t._yardAt.Count; k++)
|
|
if (t.YardOpen(k)) into.Add((t._yardAt[k], Loc.F("Train yard: {0}", Stations.Name(t._line[k]))));
|
|
}
|
|
}
|
|
|
|
/// <summary>The track has got there and the yard isn't full.</summary>
|
|
bool YardOpen(int k) => k < _stopAt.Count && Laid.Value >= _stopAt[k] - 1f && _line[k] < Bins.Count && Bins[_line[k]] < YardHolds;
|
|
|
|
/// <summary>A machine unloads in a yard: it waits there for the train.</summary>
|
|
[Rpc(SendTo.Server)]
|
|
public void FillRpc(byte station, float kg)
|
|
{
|
|
if (station < Bins.Count && kg > 0f) Bins[station] += kg;
|
|
}
|
|
|
|
float Waiting()
|
|
{
|
|
float sum = 0f;
|
|
foreach (int s in _line) if (s < Bins.Count) sum += Bins[s];
|
|
return sum;
|
|
}
|
|
|
|
/// <summary>Passing a yard between a and b: what waits there goes on board, as much as fits.</summary>
|
|
void Pickup(float a, float b)
|
|
{
|
|
float lo = Mathf.Min(a, b) - 0.5f, hi = Mathf.Max(a, b) + 0.5f;
|
|
for (int k = 0; k < _stopAt.Count; k++)
|
|
{
|
|
float at = _stopAt[k];
|
|
int s = _line[k];
|
|
if (at < lo || at > hi || s >= Bins.Count) continue;
|
|
float have = Bins[s], take = Mathf.Min(have, Hold - Hopper.Value);
|
|
if (take <= 0.01f) continue;
|
|
Bins[s] = have - take;
|
|
Hopper.Value += take;
|
|
}
|
|
}
|
|
|
|
// ───────────────────────── the host runs it ─────────────────────────
|
|
|
|
void Update()
|
|
{
|
|
if (!IsSpawned) return;
|
|
if (IsServer && _length > 0f) Run(Time.deltaTime);
|
|
if (IsServer && _sendW > 0f && Time.time - _sendT > 0.25f) SendCut();
|
|
Draw();
|
|
}
|
|
|
|
void Run(float dt)
|
|
{
|
|
if (Ridden)
|
|
{
|
|
if (!NetworkManager.ConnectedClients.ContainsKey(Rider.Value)) { Rider.Value = NoRider; Drive.Value = 0; }
|
|
else { Driven(dt); return; }
|
|
}
|
|
if (_wait > 0f)
|
|
{
|
|
_wait -= dt;
|
|
Pickup(At.Value, At.Value);
|
|
return;
|
|
}
|
|
if (Laying)
|
|
{
|
|
// out to the head of the track first: after a ride, or with a new stretch to lay
|
|
if (At.Value < Laid.Value - 0.5f) { Roll(Laid.Value, RunSpeed * Mul * Express, dt); return; }
|
|
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 cutting = Cutting;
|
|
// the stretch is mown as far as the cutters reach: on to the next station
|
|
if (!cutting && TryExtend()) return;
|
|
// odd runs come home, even ones go out; with nothing to fetch and nothing to cut it waits at home
|
|
bool home = Runs.Value % 2 == 1;
|
|
if (!cutting && Hopper.Value < 1f && Waiting() < 1f && At.Value <= HomeAt + 0.5f) { _wait = 3f; return; }
|
|
float goal = home ? HomeAt : _length;
|
|
float a = At.Value;
|
|
bool working = cutting && a >= WorkFrom - 1f;
|
|
float b = Roll(goal, RunSpeed * Mul * (working ? 1f : Express), dt);
|
|
if (cutting)
|
|
{
|
|
float lo = Mathf.Max(Mathf.Min(a, b), WorkFrom), hi = Mathf.Max(a, b);
|
|
if (hi > lo + 1e-3f) Cut(lo, hi, Inner, Mathf.Min(Arm, MaxOut - Inner));
|
|
}
|
|
if (Mathf.Abs(b - goal) < 0.01f)
|
|
{
|
|
if (home) Ship();
|
|
Arrive(Runs.Value + 1);
|
|
}
|
|
}
|
|
|
|
/// <summary>Moves the train toward a point along the track, picking up at the yards it passes. Where it got to.</summary>
|
|
float Roll(float goal, float speed, float dt)
|
|
{
|
|
float a = At.Value, b = Mathf.MoveTowards(a, goal, speed * dt);
|
|
if (b != a) At.Value = b;
|
|
Pickup(a, b);
|
|
return b;
|
|
}
|
|
|
|
/// <summary>Someone in the cab has the lever: on up the line as far as the rails go, or back home.</summary>
|
|
void Driven(float dt)
|
|
{
|
|
if (Drive.Value == 0) return;
|
|
float lo = Mathf.Min(HomeAt, Laid.Value), hi = Laid.Value;
|
|
float b = Roll(Drive.Value > 0 ? hi : lo, RunSpeed * Mul * DriveSpeed, dt);
|
|
if (b <= lo + 0.5f) Ship();
|
|
}
|
|
|
|
void Arrive(int nextRun)
|
|
{
|
|
_wait = WaitAtEnd;
|
|
Runs.Value = nextRun;
|
|
}
|
|
|
|
bool TryExtend()
|
|
{
|
|
if (_noMore) return false;
|
|
int next = NextStation();
|
|
ulong legs = Legs.Value;
|
|
int count = (int)(legs & 0xF);
|
|
if (next < 0 || count >= 11) { _noMore = true; return false; }
|
|
legs = (legs & ~0xFUL) | (ulong)(count + 1);
|
|
legs |= (ulong)next << (4 + 4 * count);
|
|
Runs.Value = 0;
|
|
Legs.Value = legs;
|
|
if (Ts) Ts.AnnounceRpc(Loc.Pack("The Grass Train lays track on to {0}", Stations.Names[next]));
|
|
return true;
|
|
}
|
|
|
|
void Ship()
|
|
{
|
|
if (Hopper.Value <= 0.01f || !Ts) return;
|
|
Ts.DepositRpc(Hopper.Value, (byte)CargoKind.Grass, Pos(At.Value));
|
|
Hopper.Value = 0f;
|
|
}
|
|
|
|
/// <summary>Host: mows along the track from a to b into the hopper, and has everyone else mow the same.</summary>
|
|
void Cut(float a, float b, float offset, float width)
|
|
{
|
|
if (width <= 0.05f || Mathf.Abs(b - a) < 1e-4f) return;
|
|
Hopper.Value = Mathf.Min(Hold, Hopper.Value + Mow(a, b, offset, width) * GameDefs.GrassDensity);
|
|
// each peer cuts its own copy of the meadow: the stroke goes out to the others, joined up into a few a second
|
|
if (_sendW > 0f && (_sendOff != offset || _sendW != width || Mathf.Abs(_sendB - a) > 0.01f || (b > a) != (_sendB > _sendA))) SendCut();
|
|
if (_sendW <= 0f) { _sendA = a; _sendOff = offset; _sendW = width; _sendT = Time.time; }
|
|
_sendB = b;
|
|
if (Time.time - _sendT > 0.25f) SendCut();
|
|
}
|
|
|
|
float _sendA, _sendB, _sendOff, _sendW, _sendT;
|
|
|
|
void SendCut()
|
|
{
|
|
if (_sendW > 0f && Mathf.Abs(_sendB - _sendA) > 1e-4f) CutRpc(_sendA, _sendB, _sendOff, _sendW);
|
|
_sendW = 0f;
|
|
}
|
|
|
|
[Rpc(SendTo.NotServer)]
|
|
void CutRpc(float a, float b, float offset, float width) => Mow(a, b, offset, width);
|
|
|
|
/// <summary>Mows along the track from a to b: under it (offset 0), or a strip either side starting this far out. The kilos cut.</summary>
|
|
float Mow(float a, float b, float offset, float width)
|
|
{
|
|
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);
|
|
}
|
|
return kg;
|
|
}
|
|
|
|
// ───────────────────────── riding ─────────────────────────
|
|
|
|
/// <summary>Where someone in the cab stands, and which way the locomotive faces.</summary>
|
|
public Vector3 CabFloor => _locoAt + _locoTurn * new Vector3(0f, 0.55f, -1.15f);
|
|
public Quaternion CabTurn => _locoTurn;
|
|
/// <summary>Beside the locomotive, where someone getting off steps down.</summary>
|
|
public Vector3 StepOff => _locoAt + _locoTurn * new Vector3(2.4f, 0f, -1.15f);
|
|
|
|
bool AimingCab => _cabHit && PlayerAgent.Local && PlayerAgent.Local.HasAim && PlayerAgent.Local.AimHit.collider == _cabHit;
|
|
|
|
[Rpc(SendTo.Server)]
|
|
void BoardRpc(RpcParams rpc = default)
|
|
{
|
|
ulong who = rpc.Receive.SenderClientId;
|
|
var p = TeamState.PlayerOf(who);
|
|
if (Ridden || !p || p.Driving.Value || (p.transform.position - _locoAt).sqrMagnitude > 144f) return;
|
|
Drive.Value = 0;
|
|
Rider.Value = who;
|
|
}
|
|
|
|
[Rpc(SendTo.Server)]
|
|
void LeaveRpc(RpcParams rpc = default)
|
|
{
|
|
if (Rider.Value != rpc.Receive.SenderClientId) return;
|
|
Rider.Value = NoRider;
|
|
Drive.Value = 0;
|
|
}
|
|
|
|
[Rpc(SendTo.Server)]
|
|
public void DriveRpc(sbyte lever, RpcParams rpc = default)
|
|
{
|
|
if (Rider.Value == rpc.Receive.SenderClientId) Drive.Value = (sbyte)Mathf.Clamp(lever, -1, 1);
|
|
}
|
|
|
|
public void Leave() => LeaveRpc();
|
|
|
|
/// <summary>For tests: the host gets in its own cab.</summary>
|
|
public void ServerBoard(ulong who)
|
|
{
|
|
if (!IsServer || Ridden) return;
|
|
Drive.Value = 0;
|
|
Rider.Value = who;
|
|
}
|
|
|
|
public float LineLength => _length;
|
|
public int Stops => _line.Count;
|
|
|
|
// ───────────────────────── 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 * Express + Mathf.Abs(at - _shown) * 4f) * Time.deltaTime);
|
|
Place(loco, _shown, true);
|
|
int count = WagonCount;
|
|
if (wagons != null)
|
|
for (int i = 0; i < wagons.Length; i++)
|
|
{
|
|
float d = _shown - (i + 1) * Gap;
|
|
bool on = i < count && d >= 0f;
|
|
if (wagons[i] && wagons[i].gameObject.activeSelf != on) wagons[i].gameObject.SetActive(on);
|
|
if (on) Place(wagons[i], d, true);
|
|
}
|
|
Heaps();
|
|
Lay(Laid.Value);
|
|
Spin();
|
|
}
|
|
|
|
/// <summary>The wagons fill from the front: each heap shows how full its wagon is (heaps are in wagon order).</summary>
|
|
void Heaps()
|
|
{
|
|
float fill = Hopper.Value / PerWagon;
|
|
for (int i = 0; i < _heaps.Count; i++)
|
|
{
|
|
var (t, rest) = _heaps[i];
|
|
if (!t) continue;
|
|
float f = Mathf.Clamp01(fill - i);
|
|
bool show = f > 0.02f;
|
|
if (t.gameObject.activeSelf != show) t.gameObject.SetActive(show);
|
|
if (show) t.localScale = rest * Mathf.Lerp(0.45f, 1f, f);
|
|
}
|
|
}
|
|
|
|
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 && (Laying || Cutting))
|
|
{
|
|
_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>();
|
|
readonly Dictionary<Transform, float> _axles = new Dictionary<Transform, float>();
|
|
|
|
/// <summary>
|
|
/// Stands a model on the rails: its front and back axles both on the track, so it leans up and down the slopes
|
|
/// with the rails instead of standing level and hanging off one end.
|
|
/// </summary>
|
|
void Place(Transform t, float d, bool onRails)
|
|
{
|
|
if (!t) return;
|
|
if (!_rest.TryGetValue(t, out var rest)) _rest[t] = rest = t.localRotation;
|
|
float half = _axles.TryGetValue(t, out var ax) && ax > 0.2f ? ax : 1.5f;
|
|
var back = PosOn(d - half);
|
|
var front = PosOn(d + half);
|
|
var f = front - back;
|
|
if (f.sqrMagnitude < 1e-4f) f = Ahead(d);
|
|
f.Normalize();
|
|
var mid = (back + front) * 0.5f;
|
|
var up = Vector3.ProjectOnPlane(Planet.Up(mid), f);
|
|
if (up.sqrMagnitude < 1e-6f) up = Planet.Up(mid);
|
|
up.Normalize();
|
|
var at = mid + up * (onRails ? RailTop : 0f);
|
|
var turn = Quaternion.LookRotation(f, up);
|
|
t.SetPositionAndRotation(at, turn * rest);
|
|
if (t == loco)
|
|
{
|
|
_locoAt = at;
|
|
_locoTurn = turn;
|
|
if (_cab) _cab.transform.SetPositionAndRotation(at, turn);
|
|
}
|
|
}
|
|
|
|
// ───────────────────────── 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
|
|
{
|
|
var def = GameDefs.Piece(PieceId.Train);
|
|
string where = Last < Stations.Count ? Stations.Name(Last) : "?";
|
|
string s;
|
|
if (Laying)
|
|
{
|
|
s = Loc.F("{0}: laying track to {1}, {2} of {3} m", def.name, where, Mathf.RoundToInt(Laid.Value), Mathf.RoundToInt(_length));
|
|
if (Laid.Value < Lead && _line.Count <= 1) s += " · " + Loc.T("E: another station");
|
|
}
|
|
else if (!Cutting) s = Loc.F("{0}: carrying grass home from the stations on its line, {1} on board, {2} waiting", def.name, GameDefs.Kilos(Hopper.Value), GameDefs.Kilos(Waiting()));
|
|
else s = 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));
|
|
if (AimingCab && !Ridden) s = Loc.T("E: ride in the cab") + " · " + s;
|
|
return s;
|
|
}
|
|
}
|
|
|
|
public bool CanInteract => (AimingCab && !Ridden) || (Laying && Laid.Value < Lead && _line.Count <= 1);
|
|
|
|
public void Interact()
|
|
{
|
|
if (AimingCab && !Ridden) BoardRpc();
|
|
else OtherWayRpc();
|
|
}
|
|
|
|
[Rpc(SendTo.Server)]
|
|
void OtherWayRpc()
|
|
{
|
|
if (!Laying || Laid.Value >= Lead || Legs.Value != 0) return;
|
|
Laid.Value = 0f;
|
|
At.Value = 0f;
|
|
Target.Value = Pick(Target.Value);
|
|
}
|
|
|
|
/// <summary>Saved: where to, how far laid, where it is, the run, the load, the line on from there (two 24-bit halves), the yards.</summary>
|
|
public float[] State
|
|
{
|
|
get
|
|
{
|
|
var s = new float[7 + Stations.Count];
|
|
s[0] = Target.Value; s[1] = Laid.Value; s[2] = At.Value; s[3] = Runs.Value; s[4] = Hopper.Value;
|
|
s[5] = Legs.Value & 0xFFFFFF; s[6] = (Legs.Value >> 24) & 0xFFFFFF;
|
|
for (int i = 0; i < Stations.Count; i++) s[7 + i] = i < Bins.Count ? Bins[i] : 0f;
|
|
return s;
|
|
}
|
|
set
|
|
{
|
|
if (value == null || value.Length < 5 || !IsServer) return;
|
|
if (value.Length >= 7) Legs.Value = (ulong)value[5] | ((ulong)value[6] << 24);
|
|
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];
|
|
while (Bins.Count < Stations.Count) Bins.Add(0f);
|
|
for (int i = 0; i < Stations.Count && 7 + i < value.Length; i++) Bins[i] = value[7 + i];
|
|
}
|
|
}
|
|
}
|
|
}
|