using System.Collections.Generic; using Unity.Netcode; using UnityEngine; namespace GrassCutter { /// Where cargo enters or leaves a piece, in world space. public struct Port { public Vector3 at, dir; public bool input; } /// Anything with ports a belt can be joined to. public interface IPorts { void Ports(List into); } /// /// A belt with a real queue. Cargo that lands on it locks onto the centre line (server-owned, kinematic) and rides along /// a fixed path at belt speed, keeping to the item ahead. At the end it is handed to whatever stands /// at the exit: the next belt, a machine's port, a belt it runs into from the side, or dropped off onto the ground. If /// none of those can take it right now it simply waits at the end and the line behind it queues up. No piles, no jams. /// public class Conveyor : MonoBehaviour, IPorts { public float speed = 1.6f; /// Built belts follow the team's Fast Belts perk instead of a fixed speed. public bool usePerkSpeed; /// Belt texture repeats per metre of belt (matches the material's V tiling). public float uvPerMetre = 2f; public Renderer[] belts; /// Gap between item centres along the belt. public const float Spacing = 0.58f; /// Height of a junction's surface above what it stands on. public const float Top = 0.35f; protected class Slot { public Cargo c; public float d; public int route; public Vector3 from; public float blend; /// Has it settled which way it's going? public bool set; /// Where it was last put, and for how many steps it hasn't moved: a jammed line is left alone. public float placedD = -1f; public int still; } struct Link { public Conveyor belt; public int port; public bool side; public float at; public ICargoSink sink; } public static readonly List All = new List(); /// Front of the belt first (largest d). protected readonly List Items = new List(); MaterialPropertyBlock _mpb; float _offset; BuildPiece _piece; Link[] _links; int _found, _linkVersion = -1; static readonly int BaseMapST = Shader.PropertyToID("_BaseMap_ST"); static readonly List s_out = new List(); static readonly Collider[] s_hits = new Collider[8]; public float Speed => Piece && Piece.Switched ? 0f : (usePerkSpeed && TeamState.Instance ? GameDefs.BeltSpeed : speed) * (Piece ? Piece.TierMul : 1f); public BuildPiece Piece => _piece ? _piece : (_piece = GetComponentInParent()); public int Count => Items.Count; protected int Mode => Piece ? Piece.Mode.Value : 0; /// Could something come in through a port right now? public bool HasRoom => MinD >= Spacing; protected static bool Server => NetworkManager.Singleton && NetworkManager.Singleton.IsServer; protected virtual void Start() { _mpb = new MaterialPropertyBlock(); } void OnEnable() { All.Add(this); } void OnDisable() { All.Remove(this); // the piece is going away: whatever rides on it falls off where it is if (Server) for (int i = Items.Count - 1; i >= 0; i--) Release(Items[i], transform.up * 0.5f); Items.Clear(); } protected virtual void Update() { if (belts == null || belts.Length == 0 || _mpb == null) return; // belt meshes carry V in metres and run +V along the flow _offset = Mathf.Repeat(_offset - Speed * Time.deltaTime * uvPerMetre, 1f); foreach (var b in belts) { if (!b) continue; b.GetPropertyBlock(_mpb); _mpb.SetVector(BaseMapST, new Vector4(1, uvPerMetre, 0, _offset)); b.SetPropertyBlock(_mpb); } } // ───────────────────────── path (local XZ, +Z = flow) ───────────────────────── protected virtual int RouteCount => 1; /// Height of the moving surface in local space. protected virtual float Surface => Top; /// Does this belt take items from the side? protected virtual bool Sides => false; protected virtual float Length(int route) => 1f; /// Point on the centre line, d metres from where items come in. protected virtual Vector2 PathAt(float d, int route) => new Vector2(0f, d - 0.5f); /// How far the centre line rises above the piece's own level d metres along (a belt that rounds over a crest). protected virtual float HeightAt(float d, int route) => 0f; /// Server: route for an item that comes in through a port. protected virtual int EntryRoute(Cargo c, int port) => 0; /// Server: route for an item dropped onto the belt at a local point. protected virtual int RouteAt(Vector2 local, Cargo c) => EntryRoute(c, 0); /// Server: is it this port's turn to send something in? protected virtual bool Takes(int port) => true; /// How far along an item goes before it has to settle on a route. protected virtual float Turn => 0f; /// Server: an item at the turn settles on a route, or waits there (false). protected virtual bool Choose(Slot s) => true; /// Items on separate ways don't keep their distance. protected virtual bool Apart(Slot ahead, Slot s) => false; /// Is anything joined to the end of this route? protected bool Connected(int route) { var l = LinkOf(route); return l.belt || l.sink != null; } /// The point of the path nearest to somewhere in the world, for the sound. public Vector3 NearestPoint(Vector3 world) { var p = ToLocal(world); Project(new Vector2(p.x, p.z), out int route, out float d); return WorldOnPath(d, route, 0f); } public virtual void Ports(List into) { into.Add(new Port { at = WorldOnPath(0f, 0, 0f), dir = Tangent(0f, 0), input = true }); for (int r = 0; r < RouteCount; r++) { float L = Length(r); into.Add(new Port { at = WorldOnPath(L, r, 0f), dir = Tangent(L, r) }); } } protected Vector3 WorldOnPath(float d, int route, float lift) { var l = PathAt(d, route); return transform.position + transform.rotation * new Vector3(l.x, Surface + lift + HeightAt(d, route), l.y); } /// Where the other end of a route meets whatever it hands over to. protected virtual Vector3 ExitAt(int route) => WorldOnPath(Length(route), route, 0f); // a piece that has just landed is still bouncing: its scale says nothing about where the path runs Vector3 ToLocal(Vector3 world) => Quaternion.Inverse(transform.rotation) * (world - transform.position); protected Vector3 Tangent(float d, int route) { float L = Length(route); float d0 = Mathf.Clamp(d - 0.02f, 0f, L), d1 = Mathf.Clamp(d + 0.02f, 0f, L); var a = PathAt(d0, route); var b = PathAt(d1, route); var t = transform.TransformDirection(new Vector3(b.x - a.x, HeightAt(d1, route) - HeightAt(d0, route), b.y - a.y)); return t.sqrMagnitude > 1e-6f ? t.normalized : transform.forward; } /// Nearest point on any route to a local point. protected virtual void Project(Vector2 local, out int route, out float d) { route = 0; d = 0f; float best = float.MaxValue; for (int r = 0; r < RouteCount; r++) { float L = Length(r); for (int k = 0; k <= 16; k++) { float dd = L * k / 16f; float e = (PathAt(dd, r) - local).sqrMagnitude; if (e < best) { best = e; route = r; d = dd; } } } } bool FreeAt(float d) { foreach (var s in Items) if (Mathf.Abs(s.d - d) < Spacing) return false; return true; } float MinD => Items.Count > 0 ? Items[Items.Count - 1].d : float.MaxValue; // ───────────────────────── what stands at the exit ───────────────────────── /// Links are looked up the first time they're needed after anything was built, moved or removed. Link LinkOf(int route) { if (_links == null) _links = new Link[RouteCount]; if (_linkVersion != BuildPiece.Version) { _linkVersion = BuildPiece.Version; _found = 0; } if ((_found >> route & 1) == 0) { _links[route] = Find(route); _found |= 1 << route; } return _links[route]; } Link Find(int route) { var end = ExitAt(route); if (BeltNet.Nearest(end, true, BeltNet.Joined, Piece, out var piece, out int port, out _)) { var conv = piece.GetComponentInChildren(); if (conv) return new Link { belt = conv, port = port }; var sink = piece.GetComponentInChildren(); if (sink != null) return new Link { sink = sink }; } foreach (var b in All) { if (b == this || !b.Sides) continue; var l = b.ToLocal(end); if (Mathf.Abs(l.x) < 0.6f && Mathf.Abs(l.y) < 0.6f && l.z > 0.3f && l.z < b.Length(0) - 0.3f) return new Link { belt = b, side = true, at = l.z }; } return default; } /// Could the exit of this route take an item right now? protected bool ExitOpen(int route) { var l = LinkOf(route); return !l.belt || (l.side ? l.belt.FreeAt(l.at) : l.belt.MinD >= Spacing); } // ───────────────────────── server API ───────────────────────── /// Could an item be put on this belt at a world point right now? public bool CanInsert(Vector3 world) { var p = ToLocal(world); Project(new Vector2(p.x, p.z), out _, out float d); return FreeAt(d); } /// Server: lock an item onto the belt at the nearest point of its path (false: no room there yet). public bool ServerTryInsert(Cargo c, Vector3 world) { if (!Server || !c || !c.IsSpawned || c.Belt) return false; var p = ToLocal(world); var local = new Vector2(p.x, p.z); Project(local, out int route, out float d); if (!FreeAt(d)) return false; route = RouteCount > 1 ? RouteAt(local, c) : route; Insert(c, d, route); return true; } /// Server: accept an item handed over through a port. public bool ServerAcceptPort(Cargo c, int port) { bool turn = Takes(port); if (!turn || MinD < Spacing) return false; Insert(c, 0f, EntryRoute(c, port)); return true; } /// Server: accept an item from a belt that runs into this one's side. bool ServerSideLoad(Cargo c, float d) { if (!FreeAt(d)) return false; Insert(c, d, 0); return true; } void Insert(Cargo c, float d, int route) { var g = c.Grab; if (c.OwnerClientId != NetworkManager.ServerClientId) c.NetworkObject.ChangeOwnership(NetworkManager.ServerClientId); g.Body.linearVelocity = Vector3.zero; g.Body.isKinematic = true; c.Belt = this; var s = new Slot { c = c, d = d, route = route, from = c.transform.position, blend = 0f, set = d > Turn }; int i = 0; while (i < Items.Count && Items[i].d > d) i++; Items.Insert(i, s); _idle = 0; } /// Server: take an item off this belt (a player grabbed it, it got despawned). public void ServerRemove(Cargo c, Vector3 velocity) { for (int i = 0; i < Items.Count; i++) if (Items[i].c == c) { var s = Items[i]; Items.RemoveAt(i); Release(s, velocity); return; } if (c && c.Belt == this) c.Belt = null; } void Release(Slot s, Vector3 velocity) { var c = s.c; if (!c) return; if (c.Belt == this) c.Belt = null; if (!c.IsSpawned) return; var rb = c.Grab.Body; rb.isKinematic = false; rb.linearVelocity = velocity; rb.angularVelocity = Vector3.zero; } // ───────────────────────── simulation (server) ───────────────────────── void FixedUpdate() { if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return; // a line that hasn't moved for a while only looks again every few steps whether the front can go on if (_idle > 40 && ++_idleSkip % 6 != 0) return; bool moved = false; float dt = Time.fixedDeltaTime * (_idle > 40 ? 6f : 1f); float step = Speed * dt; for (int i = 0; i < Items.Count; i++) { var s = Items[i]; if (!s.c || !s.c.IsSpawned || s.c.Loaded || s.c.Belt != this || s.c.Grab.IsHeld) { Items.RemoveAt(i--); if (s.c && s.c.Belt == this) s.c.Belt = null; continue; } float L = Length(s.route); float limit = Room(i, ref L); if (s.d < limit - 1e-5f) { s.d = Mathf.Min(s.d + step, limit); moved = true; } if ((i == 0 || RouteCount > 1) && s.d >= L - 1e-4f && HandOff(s)) { Items.RemoveAt(i--); moved = true; continue; } // stuck behind the one ahead: once it has come square and settled there is nothing to move if (s.blend >= 1f && Mathf.Abs(s.d - s.placedD) < 1e-5f) { if (++s.still > 40) continue; } else s.still = 0; Place(s, dt); s.placedD = s.d; if (s.blend < 1f) moved = true; } _idle = moved ? 0 : _idle + 1; } int _idle, _idleSkip; /// How far an item can go: to the turn until it has chosen, then the end of its route, and never into the one ahead. float Room(int i, ref float L) { var s = Items[i]; float limit = L; if (!s.set) { if (s.d < Turn - 1e-4f || !Choose(s)) limit = Turn; else { s.set = true; L = limit = Length(s.route); } } for (int k = i - 1; k >= 0; k--) { if (Apart(Items[k], s)) continue; return Mathf.Min(limit, Items[k].d - Spacing); } return limit; } void Place(Slot s, float dt) { var c = s.c; var rb = c.Grab.Body; var target = WorldOnPath(s.d, s.route, c.halfHeight); s.blend = Mathf.MoveTowards(s.blend, 1f, dt * 6f); var pos = s.blend < 1f ? Vector3.Lerp(s.from, target, Easing.Apply(Ease.OutCubic, s.blend)) : target; // square the item up with the flow var want = Quaternion.LookRotation(Tangent(s.d, s.route), transform.up); var rot = Quaternion.RotateTowards(rb.rotation, want, 540f * dt); rb.MovePosition(pos); rb.MoveRotation(rot); } /// The front item reached the end of its route: pass it on if anything can take it. bool HandOff(Slot s) { var c = s.c; float L = Length(s.route); var link = LinkOf(s.route); var dir = Tangent(L, s.route); if (link.belt) { c.Belt = null; if (link.side ? link.belt.ServerSideLoad(c, link.at) : link.belt.ServerAcceptPort(c, link.port)) return true; c.Belt = this; return false; } if (link.sink != null) { c.Belt = null; var rb = c.Grab.Body; if (link.sink.ServerAccept(c, WorldOnPath(L, s.route, c.halfHeight), dir)) return true; c.Belt = this; rb.isKinematic = true; return false; } // nothing there: drop it off the end, but only onto a free spot (one item waits there at a time) var land = WorldOnPath(L, s.route, 0f) + dir * 0.45f; int n = Physics.OverlapSphereNonAlloc(land, 0.3f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore); for (int k = 0; k < n; k++) { var other = s_hits[k].GetComponentInParent(); if (other && other != c) return false; } Release(s, dir * Mathf.Max(1.2f, Speed) + transform.up * 0.4f); return true; } // ───────────────────────── catching loose cargo ───────────────────────── protected void OnTriggerStay(Collider other) { if (!Server) return; var rb = other.attachedRigidbody; if (!rb) return; var c = rb.GetComponent(); if (!c || !c.IsSpawned || c.Belt || c.Loaded || c.Grab.IsHeld || c.Grab.Consumed) return; // still flying up from a throw: let it come down first if (Vector3.Dot(rb.linearVelocity, transform.up) > 1.5f) return; if (transform.InverseTransformPoint(c.transform.position).y - c.halfHeight > Surface + 0.8f) return; ServerTryInsert(c, c.transform.position); } } /// A piece that swallows cargo handed to it by a belt or a machine. public interface ICargoSink { /// Server: take the item (true) or refuse it for now (false: it waits). bool ServerAccept(Cargo c, Vector3 from, Vector3 dir); } /// Finding ports among everything that's built. public static class BeltNet { /// A belt end this close to a port feeds it. Laying one snaps it exactly, so this only forgives rounding. public const float Joined = 0.4f; /// How close to a port you have to aim for a belt to snap onto it. public const float Snap = 1.2f; static readonly List s_list = new List(); static readonly List s_out = new List(); static readonly Collider[] s_hits = new Collider[8]; public static bool Nearest(Vector3 near, bool input, float within, BuildPiece skip, out BuildPiece piece, out int index, out Port port) { piece = null; index = -1; port = default; float best = within * within; foreach (var p in BuildPiece.All) { if (!p || p == skip || !p.IsSpawned) continue; s_list.Clear(); p.Ports(s_list); for (int i = 0; i < s_list.Count; i++) { if (s_list[i].input != input) continue; float d = (s_list[i].at - near).sqrMagnitude; if (d >= best) continue; best = d; piece = p; index = i; port = s_list[i]; } } return piece; } /// Server: one kilo leaves a machine through a port, onto the belt there or, with no belt, onto clear ground. public static bool Send(BuildPiece from, Port way, CargoKind kind) { Conveyor belt = null; int port = 0; if (Nearest(way.at, true, Joined, from, out var next, out int index, out _)) { belt = next.GetComponentInChildren(); port = index; if (belt && !belt.HasRoom) return false; } else if (Physics.OverlapSphereNonAlloc(way.at + way.dir * 0.5f, 0.45f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore) > 0) return false; var made = Spawner.Instance.SpawnCargo(kind, way.at + way.dir * 0.2f + from.transform.up * 0.35f, from.transform.rotation, way.dir * 1.6f); if (!made) return false; if (belt) belt.ServerAcceptPort(made, port); return true; } /// A port at the front of a piece, just clear of its solid box. public static Port Front(Transform piece) { var box = piece.Find("Solid")?.GetComponent(); float reach = box ? box.transform.localPosition.z + box.size.z * 0.5f + 0.25f : 1.7f; return new Port { at = piece.position + piece.up * GameDefs.BeltLowest + piece.forward * reach, dir = piece.forward }; } /// Server: one kilo out of a silo, through whichever port has room. Ports take turns. public static bool Drain(BuildPiece from, NetworkVariable silo, ref int turn) { if (silo.Value < 1f) return false; s_out.Clear(); from.Ports(s_out); for (int i = 0; i < s_out.Count; i++) { turn = (turn + 1) % s_out.Count; if (s_out[turn].input || !Send(from, s_out[turn], CargoKind.Grass)) continue; silo.Value -= 1f; return true; } return false; } static readonly List s_belted = new List(); /// Does a belt leave any of this piece's hatches? public static bool Belted(BuildPiece piece) { if (!piece) return false; s_belted.Clear(); piece.Ports(s_belted); foreach (var p in s_belted) if (!p.input && Nearest(p.at, true, Joined, piece, out var next, out _, out _) && next.GetComponentInChildren()) return true; return false; } /// /// Server: a silo with no belt out sends what it holds straight to Earth, a batch every few seconds (one payment /// and one message per batch, not one per kilo). A belt is for more money (bales, bricks), never a must. /// public static void Ship(NetworkVariable silo, Vector3 at, ref float next) { if (silo.Value < 1f || Time.time < next) return; next = Time.time + 3f; var ts = TeamState.Instance; if (!ts) return; ts.ServerDeposit(silo.Value, CargoKind.Grass, at); silo.Value = 0f; } /// Does a belt already end here? public static bool Taken(Vector3 at) { foreach (var c in Conveyor.All) if (c is BeltRun r && (r.End - at).sqrMagnitude < Joined * Joined) return true; return false; } } }