Train lines that grow, station yards, a cab to ride, a wagon per upgrade; autopilot unloads where it can
- The grass train lays on to the next station by itself once its newest stretch is mown as far as the cutters reach, rounding each station at the edge of its yard, until no station is left within reach; it runs three times as fast over the stretches already mown. - Every station on a line has a yard at the end of the rails: machines (the autopilot too) unload there, the train picks it up as it passes and it is paid when the train gets home. With nothing left to cut it carries for the yards. - E on the locomotive puts you in the cab: W on up the line, S back home, E to get off; it carries on by itself after. - Three wagons, one more per upgrade (six at Mk IV), 2 t each; the heaps grow as they fill. The upgrade text says so. - The autopilot only drives to places a machine can unload (garage pads, unload bays, the yard, train yards), not to drone pads, binders or catchers, where it used to stop and stand; at a spot that won't take it, it tries the next. The HUD unload markers skip those too. - -demotrain checks the line growing, a yard filling and emptying, the cab ride and six wagons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
110
Assets/Scripts/Core/DemoBot.Train.cs
Normal file
110
Assets/Scripts/Core/DemoBot.Train.cs
Normal file
@ -0,0 +1,110 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public partial class DemoBot
|
||||
{
|
||||
/// <summary>
|
||||
/// -demotrain: a fresh planet; a grass train at Mk IV (six wagons), its first stretch finished at once so it lays on
|
||||
/// to the next station, a full tractor unloading in the first station's yard, the train picking that up and bringing
|
||||
/// it home, and the host riding in the cab and driving it.
|
||||
/// </summary>
|
||||
IEnumerator TrainDemo()
|
||||
{
|
||||
TeamState.DeleteSave();
|
||||
yield return new WaitForSeconds(2f);
|
||||
NetSession.Instance.HostLocal();
|
||||
while (!Me || !Ts) yield return null;
|
||||
yield return new WaitForSeconds(3f);
|
||||
Clock(11f);
|
||||
Ts.ServerSetMoney(500000d);
|
||||
Quaternion Face(Vector3 p, Vector3 way) => Quaternion.LookRotation(Vector3.ProjectOnPlane(way, Planet.Up(p)), Planet.Up(p));
|
||||
|
||||
var sAt = Soil17(-40f, -70f);
|
||||
var piece = Spawner.Instance.SpawnPiece(PieceId.Train, sAt, Face(sAt, Vector3.ProjectOnPlane(sAt - Planet.FromBase(0f, 0f) * Planet.Radius, Planet.Up(sAt))), sAt, true);
|
||||
yield return new WaitForSeconds(1f);
|
||||
var train = piece ? piece.GetComponent<Train>() : null;
|
||||
if (!train) { Log("train MISSING"); Application.Quit(); yield break; }
|
||||
piece.Tier.Value = GameDefs.MaxTier;
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
int wagonsOn = 0;
|
||||
foreach (var w in train.wagons) if (w && w.gameObject.activeSelf) wagonsOn++;
|
||||
Log($"train: Mk {piece.Tier.Value + 1}, {train.wagons.Length} wagons made, {wagonsOn} on the rails, line {train.LineLength:0} m to {train.Stops} station(s)");
|
||||
|
||||
// the first stretch done at once: laid, and the side cutters out as far as they go
|
||||
float first = train.LineLength;
|
||||
train.State = new[] { (float)train.Target.Value, first, first, 99f, 0f };
|
||||
yield return new WaitForSeconds(1f);
|
||||
Log($"extended: {train.Stops} stations, line {train.LineLength:0} m (was {first:0}), laying {train.Laid.Value:0} m, runs {train.Runs.Value}");
|
||||
|
||||
// and the second laid too: it starts mowing that stretch on the way home
|
||||
float whole = train.LineLength;
|
||||
train.State = new[] { (float)train.Target.Value, whole, whole, 1f, 0f, (float)(train.Legs.Value & 0xFFFFFF), (float)((train.Legs.Value >> 24) & 0xFFFFFF) };
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
var yards = new List<(Vector3 at, string name)>();
|
||||
Train.Yards(yards);
|
||||
Log($"yards: {yards.Count} ({string.Join(", ", yards.ConvertAll(y => y.name))})");
|
||||
if (yards.Count == 0) { Application.Quit(); yield break; }
|
||||
|
||||
// a full tractor unloads in the first yard
|
||||
var yAt = yards[0].at;
|
||||
var tractor = Spawner.Instance.SpawnVehicle(VehicleKind.Tractor, Me.SaveId, yAt + Planet.Up(yAt) * 1.2f, Face(yAt, Vector3.right));
|
||||
yield return new WaitForSeconds(1f);
|
||||
if (tractor)
|
||||
{
|
||||
tractor.Tank.Value = tractor.Capacity;
|
||||
float full = tractor.Tank.Value;
|
||||
yield return new WaitForSeconds(8f);
|
||||
float waiting = 0f;
|
||||
foreach (var b in train.Bins) waiting += b;
|
||||
Log($"tractor unloaded {full - tractor.Tank.Value:0} kg in the yard (unloading {tractor.Unloading}), {waiting:0} kg waiting for the train");
|
||||
}
|
||||
else Log("tractor NOT spawned");
|
||||
|
||||
// where the line turns round the first station
|
||||
var up0 = Planet.Up(yAt);
|
||||
yield return Look("train_junction", yAt + up0 * 45f + Vector3.ProjectOnPlane(Vector3.forward, up0).normalized * -30f, yAt, 1f);
|
||||
|
||||
// the train comes home through the yard, picks it up, and ships it all at the base
|
||||
double money = Ts.Money.Value;
|
||||
Time.timeScale = 8f;
|
||||
float picked = 0f;
|
||||
for (int i = 0; i < 90 && train.At.Value > 40f; i++)
|
||||
{
|
||||
yield return new WaitForSecondsRealtime(1f);
|
||||
picked = Mathf.Max(picked, train.Hopper.Value);
|
||||
}
|
||||
yield return new WaitForSecondsRealtime(3f);
|
||||
Time.timeScale = 1f;
|
||||
Log($"home: at {train.At.Value:0} m, most on board {picked:0} kg, now {train.Hopper.Value:0} kg, earned {Ts.Money.Value - money:0}");
|
||||
var lp = train.loco.position;
|
||||
var lu = Planet.Up(lp);
|
||||
yield return Look("train_six_wagons", lp + lu * 7f + Vector3.Cross(lu, train.loco.forward).normalized * 16f - train.loco.forward * 14f, lp - train.loco.forward * 14f, 1f);
|
||||
|
||||
// the host gets in the cab and drives it up the line
|
||||
train.ServerBoard(Unity.Netcode.NetworkManager.Singleton.LocalClientId);
|
||||
yield return new WaitForSeconds(1f);
|
||||
Log($"in the cab: {(Me.RidingTrain == train ? "yes" : "NO")}, {Vector3.Distance(Me.transform.position, train.CabFloor):0.00} m from the cab floor");
|
||||
float from = train.At.Value;
|
||||
train.DriveRpc(1);
|
||||
yield return new WaitForSeconds(4f);
|
||||
Log($"driven: {train.At.Value - from:0} m on in 4 s, rider still {Vector3.Distance(Me.transform.position, train.CabFloor):0.00} m from the floor");
|
||||
BotCapture.From = null;
|
||||
yield return Shot("train_cab");
|
||||
train.DriveRpc(0);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
float stopped = train.At.Value;
|
||||
yield return new WaitForSeconds(1f);
|
||||
Log($"lever back: moved {train.At.Value - stopped:0.0} m in a second");
|
||||
train.Leave();
|
||||
yield return new WaitForSeconds(1f);
|
||||
Log($"off: riding {(Me.RidingTrain ? "STILL" : "no")}, {Vector3.Distance(Me.transform.position, train.loco.position):0.0} m from the loco, altitude {Planet.Altitude(Me.transform.position):0.00} m, rider {(train.Ridden ? "STILL" : "none")}");
|
||||
yield return new WaitForSeconds(3f);
|
||||
Log($"on its own again: at {train.At.Value:0} m, runs {train.Runs.Value}");
|
||||
Log("train done");
|
||||
Application.Quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/DemoBot.Train.cs.meta
Normal file
2
Assets/Scripts/Core/DemoBot.Train.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 242ecd8155aa4caf865239337df2727d
|
||||
@ -3013,6 +3013,11 @@ namespace GrassCutter
|
||||
yield return Perf(int.Parse(perfSlot));
|
||||
yield break;
|
||||
}
|
||||
if (CommandLine.Has("-demotrain"))
|
||||
{
|
||||
yield return TrainDemo();
|
||||
yield break;
|
||||
}
|
||||
if (CommandLine.Has("-demoshop"))
|
||||
{
|
||||
yield return ShopDemo(int.TryParse(CommandLine.Get("-demoshop"), out int shopSlot) ? shopSlot : 0);
|
||||
|
||||
@ -440,6 +440,13 @@ namespace GrassCutter
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a piece gets at a tier: the train also gets a wagon for each.</summary>
|
||||
public static string TierEffect(PieceId id, UpgradeKind k, int tier)
|
||||
{
|
||||
if (id == PieceId.Train) return Loc.F("x{0:0.#} speed and reach, {1} wagons", TierMul(k, tier), 3 + Mathf.Clamp(tier, 0, MaxTier));
|
||||
return TierEffect(k, tier);
|
||||
}
|
||||
|
||||
public static double UpgradePrice(BuildPiece p, int tier)
|
||||
{
|
||||
double basis = p.Run ? Math.Max(20d, p.Run.Metres * 4d) : Math.Max(20d, p.Def.price);
|
||||
|
||||
@ -8,12 +8,17 @@ 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).
|
||||
/// 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;
|
||||
|
||||
@ -21,50 +26,92 @@ namespace GrassCutter
|
||||
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, Hold = 6000f, Gap = 5.2f, Gauge = 1.62f;
|
||||
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 station it is laying track to (255: not chosen yet).</summary>
|
||||
/// <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 track was finished: run n cuts the n-th strip out either side.</summary>
|
||||
/// <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, (wagons != null ? wagons.Length : 0) * Gap + 2.5f);
|
||||
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 RouteDone => !Laying && Runs.Value > 0 && Inner >= MaxOut;
|
||||
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()
|
||||
{
|
||||
// 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]))
|
||||
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))
|
||||
@ -80,24 +127,45 @@ namespace GrassCutter
|
||||
_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();
|
||||
if (IsServer && Target.Value == 255) Target.Value = Pick(-1);
|
||||
Legs.OnValueChanged += (_, __) => Route();
|
||||
if (IsServer)
|
||||
{
|
||||
while (Bins.Count < Stations.Count) Bins.Add(0f);
|
||||
if (Target.Value == 255) Target.Value = Pick(-1);
|
||||
}
|
||||
Route();
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
if (_track) Destroy(_track);
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
if (_track) Destroy(_track);
|
||||
base.OnDestroy();
|
||||
}
|
||||
@ -125,13 +193,53 @@ namespace GrassCutter
|
||||
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
|
||||
@ -143,18 +251,32 @@ namespace GrassCutter
|
||||
{
|
||||
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)));
|
||||
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];
|
||||
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>
|
||||
@ -182,6 +304,71 @@ namespace GrassCutter
|
||||
|
||||
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()
|
||||
@ -193,9 +380,21 @@ namespace GrassCutter
|
||||
|
||||
void Run(float dt)
|
||||
{
|
||||
if (_wait > 0f) { _wait -= dt; return; }
|
||||
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;
|
||||
@ -204,26 +403,67 @@ namespace GrassCutter
|
||||
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));
|
||||
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 (done) Ship();
|
||||
else Arrive(Runs.Value + 1);
|
||||
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)
|
||||
{
|
||||
Ship();
|
||||
_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;
|
||||
@ -252,6 +492,53 @@ namespace GrassCutter
|
||||
Hopper.Value = Mathf.Min(Hold, Hopper.Value + kg * GameDefs.GrassDensity);
|
||||
}
|
||||
|
||||
// ───────────────────────── 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()
|
||||
@ -259,19 +546,37 @@ namespace GrassCutter
|
||||
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);
|
||||
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;
|
||||
if (wagons[i]) wagons[i].gameObject.SetActive(d >= 0f);
|
||||
if (d >= 0f) Place(wagons[i], d, true);
|
||||
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;
|
||||
@ -280,7 +585,7 @@ namespace GrassCutter
|
||||
_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)
|
||||
if (_reel && Mathf.Abs(moved) > 1e-4f && (Laying || Cutting))
|
||||
{
|
||||
_reelAngle += Time.deltaTime * 720f;
|
||||
_reel.localRotation = _reelRest * Quaternion.AngleAxis(_reelAngle, Vector3.right);
|
||||
@ -289,7 +594,6 @@ namespace GrassCutter
|
||||
|
||||
/// <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>
|
||||
@ -310,7 +614,15 @@ namespace GrassCutter
|
||||
var up = Vector3.ProjectOnPlane(Planet.Up(mid), f);
|
||||
if (up.sqrMagnitude < 1e-6f) up = Planet.Up(mid);
|
||||
up.Normalize();
|
||||
t.SetPositionAndRotation(mid + up * (onRails ? RailTop : 0f), Quaternion.LookRotation(f, up) * rest);
|
||||
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 ─────────────────────────
|
||||
@ -422,42 +734,60 @@ namespace GrassCutter
|
||||
{
|
||||
get
|
||||
{
|
||||
string where = Target.Value < Stations.Count ? Stations.Name(Target.Value) : "?";
|
||||
var def = GameDefs.Piece(PieceId.Train);
|
||||
string where = Last < Stations.Count ? Stations.Name(Last) : "?";
|
||||
string s;
|
||||
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;
|
||||
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");
|
||||
}
|
||||
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));
|
||||
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 => Laying && Laid.Value < Lead;
|
||||
public bool CanInteract => (AimingCab && !Ridden) || (Laying && Laid.Value < Lead && _line.Count <= 1);
|
||||
|
||||
public void Interact() => OtherWayRpc();
|
||||
public void Interact()
|
||||
{
|
||||
if (AimingCab && !Ridden) BoardRpc();
|
||||
else OtherWayRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
void OtherWayRpc()
|
||||
{
|
||||
if (!Laying || Laid.Value >= Lead) return;
|
||||
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 => new[] { Target.Value, Laid.Value, At.Value, Runs.Value, Hopper.Value };
|
||||
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,6 +35,9 @@ namespace GrassCutter
|
||||
float _bestDist, _bestAt;
|
||||
int _goalKey = -1;
|
||||
Vector3 _unloadAt;
|
||||
/// <summary>Pads it got to and couldn't unload on this trip (walled in, say): it tries the next place.</summary>
|
||||
readonly HashSet<SiloPiece> _badPads = new HashSet<SiloPiece>();
|
||||
float _thereSince = -1f;
|
||||
|
||||
/// <summary>
|
||||
/// An autopilot touches nothing, so nothing can wedge it, climb it or tip it: it rides on the soil and on the base
|
||||
@ -121,6 +124,7 @@ namespace GrassCutter
|
||||
}
|
||||
|
||||
static readonly List<Vector2Int> s_fields = new List<Vector2Int>();
|
||||
static readonly List<(Vector3 at, string name)> s_yards = new List<(Vector3, string)>();
|
||||
static readonly Collider[] s_block = new Collider[4];
|
||||
|
||||
/// <summary>The driver hands over: they step off, it carries on.</summary>
|
||||
@ -282,12 +286,18 @@ namespace GrassCutter
|
||||
var p = transform.position;
|
||||
foreach (var s in SiloPiece.Pads)
|
||||
{
|
||||
if (!s || !s.IsSpawned) continue;
|
||||
// only what a machine can drive onto (a garage, an unload bay): a drone pad or a binder holds grass too
|
||||
if (!s || !s.IsSpawned || !s.OnPad(s.PadSpot) || _badPads.Contains(s)) continue;
|
||||
float d = (s.PadSpot - p).sqrMagnitude;
|
||||
if (d < best) { best = d; at = s.PadSpot; }
|
||||
}
|
||||
if (!s_dock) { var dz = GameObject.Find("DockZone"); s_dock = dz ? dz.transform : null; }
|
||||
if (s_dock && (s_dock.position - p).sqrMagnitude < best) { best = (s_dock.position - p).sqrMagnitude; at = s_dock.position; }
|
||||
// a yard at a station on a train's line: the train takes it home
|
||||
s_yards.Clear();
|
||||
Train.Yards(s_yards);
|
||||
foreach (var y in s_yards)
|
||||
if ((y.at - p).sqrMagnitude < best) { best = (y.at - p).sqrMagnitude; at = y.at; }
|
||||
return best < float.MaxValue;
|
||||
}
|
||||
|
||||
@ -309,8 +319,22 @@ namespace GrassCutter
|
||||
if (job == AutoJob.Unloading)
|
||||
{
|
||||
// on the pad: stand still until it's empty, then back to work
|
||||
if (Unloading) return Vector2.zero;
|
||||
if (Tank.Value <= 0.1f) { Auto.Value = (byte)AutoJob.Mowing; _stuckTimes = 0; return Vector2.zero; }
|
||||
if (Unloading) { _thereSince = -1f; return Vector2.zero; }
|
||||
if (Tank.Value <= 0.1f) { Auto.Value = (byte)AutoJob.Mowing; _stuckTimes = 0; _badPads.Clear(); return Vector2.zero; }
|
||||
// at the spot and still not unloading: that place won't take it, so the next one
|
||||
if (Vector3.ProjectOnPlane(_unloadAt - p, up).sqrMagnitude < 25f)
|
||||
{
|
||||
if (_thereSince < 0f) _thereSince = Time.time;
|
||||
else if (Time.time - _thereSince > 4f)
|
||||
{
|
||||
_thereSince = -1f;
|
||||
var bad = SiloPiece.Pads.Find(s => s && (s.PadSpot - _unloadAt).sqrMagnitude < 1f);
|
||||
if (bad) _badPads.Add(bad);
|
||||
if (!bad) Hop(_unloadAt, 5f); // the yard: right onto the spot
|
||||
else if (!FindUnload(out _unloadAt)) { Auto.Value = (byte)AutoJob.Done; return Vector2.zero; }
|
||||
}
|
||||
}
|
||||
else _thereSince = -1f;
|
||||
}
|
||||
|
||||
Vector3 goal;
|
||||
|
||||
@ -369,11 +369,17 @@ namespace GrassCutter
|
||||
}
|
||||
if (Slurping.Value != mowing) Slurping.Value = mowing;
|
||||
|
||||
// unload: in the yard at the base it's paid as it comes off, on a garage's pad or an unload bay it fills the bin
|
||||
// unload: in the yard at the base it's paid as it comes off, on a garage's pad or an unload bay it fills the bin,
|
||||
// in a train yard at a station on a line it waits there for the train
|
||||
var pad = Tank.Value > 0.1f ? SiloPiece.PadUnder(transform.position) : null;
|
||||
bool dock = Tank.Value > 0.1f && !pad && NearDock();
|
||||
Train yard = null;
|
||||
int yardOf = -1;
|
||||
if (Tank.Value > 0.1f && !pad && !dock) Train.YardAt(transform.position, out yard, out yardOf);
|
||||
bool into = pad || dock || yard;
|
||||
if (Def.bales && (driving || auto)) Bale(dt);
|
||||
Unloading = Tank.Value > 0.1f && (pad || NearDock());
|
||||
if (Tank.Value > 0.1f && (pad || NearDock()) && Ts)
|
||||
Unloading = Tank.Value > 0.1f && into;
|
||||
if (Tank.Value > 0.1f && into && Ts)
|
||||
{
|
||||
float give = Mathf.Min(Tank.Value, GameDefs.DockRate(Level(TuneId.Release)) * (Ts.Has(PerkId.ExpressDepot) ? 2f : 1f) * dt);
|
||||
Tank.Value -= give;
|
||||
@ -381,6 +387,7 @@ namespace GrassCutter
|
||||
if (_unloadCarry > 40f || Tank.Value <= 0.1f)
|
||||
{
|
||||
if (pad) pad.TakeRpc(_unloadCarry);
|
||||
else if (yard) yard.FillRpc((byte)yardOf, _unloadCarry);
|
||||
else Ts.DepositRpc(_unloadCarry, (byte)CargoKind.Grass, transform.position);
|
||||
_unloadCarry = 0f;
|
||||
}
|
||||
|
||||
@ -118,6 +118,12 @@ namespace GrassCutter
|
||||
Vector3 _climbFrom, _climbTo;
|
||||
float _jumpTapAt = -9f, _dashAt = -9f;
|
||||
Vehicle _vehicle;
|
||||
/// <summary>The train whose cab this player rides in, and the lever as last sent.</summary>
|
||||
Train _train;
|
||||
sbyte _lever;
|
||||
public Train RidingTrain => _train;
|
||||
/// <summary>In a seat of some kind: a machine's, or a train's cab.</summary>
|
||||
bool Seated => _vehicle || _train;
|
||||
|
||||
public bool Flying { get; private set; }
|
||||
public float CheatSpeed = 1f;
|
||||
@ -126,7 +132,7 @@ namespace GrassCutter
|
||||
|
||||
public void SetFlying(bool on)
|
||||
{
|
||||
if (!IsOwner || _vehicle || Flying == on) return;
|
||||
if (!IsOwner || Seated || Flying == on) return;
|
||||
Flying = on;
|
||||
Body.enabled = !on;
|
||||
_vel = Vector3.zero;
|
||||
@ -301,7 +307,7 @@ namespace GrassCutter
|
||||
transform.rotation = _frame;
|
||||
// everyone else sees a jump too, not a glide straight through the planet
|
||||
if (_net && _net.IsSpawned && _settled) _net.Teleport(pos, _frame, transform.localScale);
|
||||
Body.enabled = !Flying && !_vehicle;
|
||||
Body.enabled = !Flying && !Seated;
|
||||
_vel = Vector3.zero;
|
||||
_climbT = -1f;
|
||||
}
|
||||
@ -383,15 +389,16 @@ namespace GrassCutter
|
||||
}
|
||||
Look();
|
||||
if (_vehicle) UpdateRiding();
|
||||
else if (_train) RideTrain();
|
||||
else if (Flying) Fly();
|
||||
else if (_climbT >= 0f) Climb();
|
||||
else Move();
|
||||
UpdateAim();
|
||||
if (Ctl.InteractPressed) DoInteract();
|
||||
// T on anything built opens its upgrades and switches (the hammer keeps T for moving pieces)
|
||||
if (Ctl.MovePressed && !_vehicle && AimPiece && !(PlayerBuild.Local && PlayerBuild.Local.Active)) UIRoot.I?.OpenPiece(AimPiece);
|
||||
if (Ctl.MovePressed && !Seated && AimPiece && !(PlayerBuild.Local && PlayerBuild.Local.Active)) UIRoot.I?.OpenPiece(AimPiece);
|
||||
// never lost under the soil
|
||||
if (!Flying && !_vehicle && Planet.Altitude(transform.position) < -3f) Teleport(Planet.Surface(transform.position) + Planet.Up(transform.position) * 0.1f);
|
||||
if (!Flying && !Seated && Planet.Altitude(transform.position) < -3f) Teleport(Planet.Surface(transform.position) + Planet.Up(transform.position) * 0.1f);
|
||||
if (Swimming.Value != _swimming) Swimming.Value = _swimming;
|
||||
var cp = Tools.CutPoint;
|
||||
var cut = Tools.IsCutting && Ts ? new Vector4(cp.x, cp.y, cp.z, Ts.ToolWidth(Tools.Current)) : Vector4.zero;
|
||||
@ -405,14 +412,14 @@ namespace GrassCutter
|
||||
var up = _frame * Vector3.up;
|
||||
_frame = Quaternion.AngleAxis(l.x, up) * _frame;
|
||||
_pitch = Mathf.Clamp(_pitch - l.y, -85f, 85f);
|
||||
if (!_vehicle) transform.rotation = _frame;
|
||||
if (!Seated) transform.rotation = _frame;
|
||||
float flat = Vector3.ProjectOnPlane(_vel, up).magnitude;
|
||||
float bob = (Grounded || _swimming) && !_vehicle ? Mathf.Sin(_bobPhase * 2f) * (_swimming ? 0.05f : 0.035f) * Mathf.Clamp01(flat / sprintSpeed + (_swimming ? 0.4f : 0f)) : 0f;
|
||||
float bob = (Grounded || _swimming) && !Seated ? Mathf.Sin(_bobPhase * 2f) * (_swimming ? 0.05f : 0.035f) * Mathf.Clamp01(flat / sprintSpeed + (_swimming ? 0.4f : 0f)) : 0f;
|
||||
float roll = -Ctl.Move.x * 1.5f;
|
||||
if (_swimming) roll += Mathf.Sin(Time.time * 1.3f) * 2f;
|
||||
_landDip = Mathf.Lerp(_landDip, 0f, Time.deltaTime * 8f);
|
||||
head.localPosition = new Vector3(0, eyeHeight + bob - _landDip, 0);
|
||||
if (_vehicle)
|
||||
if (Seated)
|
||||
{
|
||||
// look is relative to the vehicle heading
|
||||
head.rotation = _frame * Quaternion.Euler(_pitch, 0f, 0f);
|
||||
@ -588,7 +595,7 @@ namespace GrassCutter
|
||||
AimInteractable = null;
|
||||
AimGrabbable = null;
|
||||
HasAim = false;
|
||||
if (!cam || _vehicle) return;
|
||||
if (!cam || Seated) return;
|
||||
var ray = new Ray(cam.transform.position, cam.transform.forward);
|
||||
float tether = Ts ? Ts.Level(PerkId.BundleLine) * 1.5f : 0f;
|
||||
if (Physics.Raycast(ray, out var hit, Reach + tether + (InGrass ? 0.6f : 0f), Layers.InteractMask, QueryTriggerInteraction.Ignore))
|
||||
@ -606,6 +613,7 @@ namespace GrassCutter
|
||||
|
||||
void DoInteract()
|
||||
{
|
||||
if (_train) { _train.Leave(); return; }
|
||||
if (_vehicle) { _vehicle.RequestExit(); return; }
|
||||
if (Grab.Holding)
|
||||
{
|
||||
@ -639,9 +647,77 @@ namespace GrassCutter
|
||||
}
|
||||
else if (!_vehicle.LocalDriving) ExitVehicle();
|
||||
if (_vehicle) FollowSeat();
|
||||
// the train: the host says who is in its cab
|
||||
if (!_train)
|
||||
{
|
||||
if (!_vehicle)
|
||||
foreach (var t in Train.All)
|
||||
if (t && t.IsSpawned && t.Rider.Value == OwnerClientId) { EnterTrain(t); break; }
|
||||
}
|
||||
else if (!_train.IsSpawned || _train.Rider.Value != OwnerClientId) ExitTrain();
|
||||
if (_train) FollowCab();
|
||||
Boom();
|
||||
}
|
||||
|
||||
// ───────────────────────── the train's cab ─────────────────────────
|
||||
|
||||
void EnterTrain(Train t)
|
||||
{
|
||||
SetFlying(false);
|
||||
_train = t;
|
||||
_lever = 0;
|
||||
Body.enabled = false;
|
||||
_swimming = false;
|
||||
_climbT = -1f;
|
||||
Grab.Drop();
|
||||
_heading = CabHeading(t);
|
||||
_frame = _heading;
|
||||
Sfx.Play("build_place", 0.5f, 1.3f);
|
||||
Hud.Toast(Loc.T("In the cab: W forward · S back · E to get off"), Hud.ToastKind.Info);
|
||||
}
|
||||
|
||||
void ExitTrain()
|
||||
{
|
||||
var t = _train;
|
||||
_train = null;
|
||||
_lever = 0;
|
||||
var at = t ? t.StepOff : transform.position;
|
||||
var up = Planet.Up(at);
|
||||
var pos = Planet.Surface(at) + up * 0.1f;
|
||||
if (Physics.Raycast(at + up * 2f, -up, out var hit, 6f, (1 << Layers.Default) | (1 << Layers.Build), QueryTriggerInteraction.Ignore)) pos = hit.point + up * 0.1f;
|
||||
Teleport(pos);
|
||||
}
|
||||
|
||||
/// <summary>The lever: W on up the line, S back toward home, neither to stop.</summary>
|
||||
void RideTrain()
|
||||
{
|
||||
if (!_train) return;
|
||||
var m = Ctl.Move;
|
||||
sbyte lever = (sbyte)(m.y > 0.3f ? 1 : m.y < -0.3f ? -1 : 0);
|
||||
if (lever != _lever)
|
||||
{
|
||||
_lever = lever;
|
||||
_train.DriveRpc(lever);
|
||||
}
|
||||
CameraFx.FovTarget(lever != 0 ? 6f : 0f);
|
||||
}
|
||||
|
||||
static Quaternion CabHeading(Train t)
|
||||
{
|
||||
var up = Planet.Up(t.CabFloor);
|
||||
var f = Vector3.ProjectOnPlane(t.CabTurn * Vector3.forward, up);
|
||||
return Quaternion.LookRotation(f.sqrMagnitude > 1e-6f ? f.normalized : Vector3.ProjectOnPlane(Vector3.forward, up).normalized, up);
|
||||
}
|
||||
|
||||
void FollowCab()
|
||||
{
|
||||
transform.position = _train.CabFloor;
|
||||
var heading = CabHeading(_train);
|
||||
_frame = heading * Quaternion.Inverse(_heading) * _frame;
|
||||
_heading = heading;
|
||||
transform.rotation = heading;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The chase view: the camera orbits the machine with the mouse, the wheel pulls it closer or further, and it never ends up
|
||||
/// in the ground or behind a wall. Leaving the seat puts it back on the eyes.
|
||||
|
||||
@ -709,7 +709,8 @@ namespace GrassCutter
|
||||
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));
|
||||
if (pad && pad.IsSpawned && pad.OnPad(pad.PadSpot) && _dropSpots.Count < 12) _dropSpots.Add((pad.PadSpot, pad.PadName));
|
||||
Train.Yards(_dropSpots);
|
||||
// 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));
|
||||
|
||||
@ -53,14 +53,14 @@ namespace GrassCutter
|
||||
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);
|
||||
UIK.Text(tier == 0 ? Loc.T("As built.") : Loc.F("Now {0}.", GameDefs.TierEffect(_p.piece, kind, tier)), "tune-effect", names, false);
|
||||
if (tier < GameDefs.MaxTier)
|
||||
{
|
||||
double price = GameDefs.UpgradePrice(_p, tier);
|
||||
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.Text(Loc.F("{0}.", Cap(GameDefs.TierEffect(_p.piece, kind, tier + 1))), "tune-effect", upNames, false);
|
||||
UIK.Costs(UIK.Btn(UIK.Money(price), () =>
|
||||
{
|
||||
if (!UIK.CanPay(price)) { Sfx.Play("error", 0.7f); return; }
|
||||
|
||||
Reference in New Issue
Block a user