Files
grass-cutters/Assets/Scripts/Gameplay/Conveyor.cs
NiemandKG 57d0f4d31a Frame time on a big farm: batched grass, sleeping bundles, no light probes
Measured in a real 2560x1440 window on the player's Mommy save (RTX 4090):
the GPU took ~5 ms, the main thread the rest.

- Grass: a fully mown sector draws only its floor (one draw, not up to six);
  untouched and fully mown sectors share a mow map look, so the fur pile
  draws them all in one instanced call per pile (GC_SECTOR_BUFFER, sector
  frames from a structured buffer). Grass draws 1112 -> 337 at the base,
  876 -> 439 in the meadow.
- Bundles: loose ones sleep when they come to rest (our gravity kept ~600
  bodies awake), ones on belts skip the ground checks, and all of them are
  stepped from one CargoTick instead of two Unity messages each.
- Belts leave a jammed line alone and only look every few steps whether it
  can move; splitters test distance before transforming every bundle.
- Light probes off on everything (the planet has none) and the GPU Resident
  Drawer off: both cost CPU per moving renderer for nothing.
- -demogpu N -onscreen measures frame time with one feature off at a time.

Base view 17-19 ms -> 14-15 ms, meadow 14-16 ms -> 11.5-12 ms.

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

580 lines
24 KiB
C#

using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>Where cargo enters or leaves a piece, in world space.</summary>
public struct Port
{
public Vector3 at, dir;
public bool input;
}
/// <summary>Anything with ports a belt can be joined to.</summary>
public interface IPorts
{
void Ports(List<Port> into);
}
/// <summary>
/// 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 <see cref="Spacing"/> 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.
/// </summary>
public class Conveyor : MonoBehaviour, IPorts
{
public float speed = 1.6f;
/// <summary>Built belts follow the team's Fast Belts perk instead of a fixed speed.</summary>
public bool usePerkSpeed;
/// <summary>Belt texture repeats per metre of belt (matches the material's V tiling).</summary>
public float uvPerMetre = 2f;
public Renderer[] belts;
/// <summary>Gap between item centres along the belt.</summary>
public const float Spacing = 0.58f;
/// <summary>Height of a junction's surface above what it stands on.</summary>
public const float Top = 0.35f;
protected class Slot
{
public Cargo c;
public float d;
public int route;
public Vector3 from;
public float blend;
/// <summary>Has it settled which way it's going?</summary>
public bool set;
/// <summary>Where it was last put, and for how many steps it hasn't moved: a jammed line is left alone.</summary>
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<Conveyor> All = new List<Conveyor>();
/// <summary>Front of the belt first (largest d).</summary>
protected readonly List<Slot> Items = new List<Slot>();
MaterialPropertyBlock _mpb;
float _offset;
BuildPiece _piece;
Link[] _links;
int _found, _linkVersion = -1;
static readonly int BaseMapST = Shader.PropertyToID("_BaseMap_ST");
static readonly List<Port> s_out = new List<Port>();
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<BuildPiece>());
public int Count => Items.Count;
protected int Mode => Piece ? Piece.Mode.Value : 0;
/// <summary>Could something come in through a port right now?</summary>
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;
/// <summary>Height of the moving surface in local space.</summary>
protected virtual float Surface => Top;
/// <summary>Does this belt take items from the side?</summary>
protected virtual bool Sides => false;
protected virtual float Length(int route) => 1f;
/// <summary>Point on the centre line, d metres from where items come in.</summary>
protected virtual Vector2 PathAt(float d, int route) => new Vector2(0f, d - 0.5f);
/// <summary>How far the centre line rises above the piece's own level d metres along (a belt that rounds over a crest).</summary>
protected virtual float HeightAt(float d, int route) => 0f;
/// <summary>Server: route for an item that comes in through a port.</summary>
protected virtual int EntryRoute(Cargo c, int port) => 0;
/// <summary>Server: route for an item dropped onto the belt at a local point.</summary>
protected virtual int RouteAt(Vector2 local, Cargo c) => EntryRoute(c, 0);
/// <summary>Server: is it this port's turn to send something in?</summary>
protected virtual bool Takes(int port) => true;
/// <summary>How far along an item goes before it has to settle on a route.</summary>
protected virtual float Turn => 0f;
/// <summary>Server: an item at the turn settles on a route, or waits there (false).</summary>
protected virtual bool Choose(Slot s) => true;
/// <summary>Items on separate ways don't keep their distance.</summary>
protected virtual bool Apart(Slot ahead, Slot s) => false;
/// <summary>Is anything joined to the end of this route?</summary>
protected bool Connected(int route)
{
var l = LinkOf(route);
return l.belt || l.sink != null;
}
/// <summary>The point of the path nearest to somewhere in the world, for the sound.</summary>
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<Port> 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);
}
/// <summary>Where the other end of a route meets whatever it hands over to.</summary>
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;
}
/// <summary>Nearest point on any route to a local point.</summary>
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 ─────────────────────────
/// <summary>Links are looked up the first time they're needed after anything was built, moved or removed.</summary>
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<Conveyor>();
if (conv) return new Link { belt = conv, port = port };
var sink = piece.GetComponentInChildren<ICargoSink>();
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;
}
/// <summary>Could the exit of this route take an item right now?</summary>
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 ─────────────────────────
/// <summary>Could an item be put on this belt at a world point right now?</summary>
public bool CanInsert(Vector3 world)
{
var p = ToLocal(world);
Project(new Vector2(p.x, p.z), out _, out float d);
return FreeAt(d);
}
/// <summary>Server: lock an item onto the belt at the nearest point of its path (false: no room there yet).</summary>
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;
}
/// <summary>Server: accept an item handed over through a port.</summary>
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;
}
/// <summary>Server: accept an item from a belt that runs into this one's side.</summary>
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;
}
/// <summary>Server: take an item off this belt (a player grabbed it, it got despawned).</summary>
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;
/// <summary>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.</summary>
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);
}
/// <summary>The front item reached the end of its route: pass it on if anything can take it.</summary>
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<Cargo>();
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<Cargo>();
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);
}
}
/// <summary>A piece that swallows cargo handed to it by a belt or a machine.</summary>
public interface ICargoSink
{
/// <summary>Server: take the item (true) or refuse it for now (false: it waits).</summary>
bool ServerAccept(Cargo c, Vector3 from, Vector3 dir);
}
/// <summary>Finding ports among everything that's built.</summary>
public static class BeltNet
{
/// <summary>A belt end this close to a port feeds it. Laying one snaps it exactly, so this only forgives rounding.</summary>
public const float Joined = 0.4f;
/// <summary>How close to a port you have to aim for a belt to snap onto it.</summary>
public const float Snap = 1.2f;
static readonly List<Port> s_list = new List<Port>();
static readonly List<Port> s_out = new List<Port>();
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;
}
/// <summary>Server: one kilo leaves a machine through a port, onto the belt there or, with no belt, onto clear ground.</summary>
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<Conveyor>();
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;
}
/// <summary>A port at the front of a piece, just clear of its solid box.</summary>
public static Port Front(Transform piece)
{
var box = piece.Find("Solid")?.GetComponent<BoxCollider>();
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 };
}
/// <summary>Server: one kilo out of a silo, through whichever port has room. Ports take turns.</summary>
public static bool Drain(BuildPiece from, NetworkVariable<float> 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<Port> s_belted = new List<Port>();
/// <summary>Does a belt leave any of this piece's hatches?</summary>
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<Conveyor>()) return true;
return false;
}
/// <summary>
/// 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.
/// </summary>
public static void Ship(NetworkVariable<float> 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;
}
/// <summary>Does a belt already end here?</summary>
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;
}
}
}