using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
///
/// Shared, server-owned crew progress: wallet, kilos shipped to Earth (= how much of Herbaria-7 is mown), the upgrade
/// matrix, deck tiles and the save game. Tools, belt slots and gear are personal, and the host's save remembers them.
///
public partial class TeamState : NetworkBehaviour
{
public static TeamState Instance { get; private set; }
public readonly NetworkVariable Money = new NetworkVariable();
public readonly NetworkVariable Shipped = new NetworkVariable();
/// Square metres mown, as the host counts them.
public readonly NetworkVariable Mown = new NetworkVariable();
/// Sectors mown clean.
public readonly NetworkVariable Closed = new NetworkVariable();
/// Every coin the crew has ever been paid (grass, sectors, stakes, tips), spent or not.
public readonly NetworkVariable Earned = new NetworkVariable();
/// Seconds this world has been running, over every session.
public readonly NetworkVariable Played = new NetworkVariable();
public NetworkList Perks;
public NetworkList Tiles;
/// Stakes and survey points the crew has done.
public NetworkList Found;
public static event Action MoneyChanged;
public static event Action Purchased; // who, what
/// Added to the server clock to give the time of day.
public readonly NetworkVariable DayOffset = new NetworkVariable();
/// How big the ball is (): the host's save says, everyone builds on the same one.
public readonly NetworkVariable Size = new NetworkVariable();
public static event Action Announcement;
public static event Action Deposited; // where, money, kilos
public static event Action Changed;
public static event Action TilesChanged;
[Serializable] class PieceSave { public int id, cfg; public bool free; public Vector3 at, to; public Quaternion turn; public float[] state; }
[Serializable] class CrewSave { public string key; public int owned, slots, current = 255; public int[] belt; public float[] bins; }
[Serializable] class CargoSave { public int kind; public float kg; public Vector3 at; }
[Serializable]
class SaveData
{
/// 0: pieces stood on the old 1 m grid.
public int ver;
/// How big the ball is: 0 the whole planet (every save from before there was a choice), 1 half, 2 a third.
public int level;
/// Which set of planet sizes (): 0 for every save from before.
public int sizeGen;
public double money, shipped, mown;
/// All money ever paid in, and seconds played (0 in saves from before they were counted).
public double earned, played;
/// Time of day: the first morning begins here.
public float day = 0.75f;
public int[] perks;
public int[] tiles;
public int[] found;
public int[] stations;
public List banned = new List();
public List pieces = new List();
public List crew = new List();
public List cargo = new List();
public List vehicles = new List();
}
static readonly long[][] OldFleet = { new long[] { 1000 }, new long[] { 6000 }, new long[] { 250, 600, 1500 }, new long[] { 200, 500, 1200 }, new long[] { 150, 400 } };
/// A crew that leaves more lying around than this loses the rest on a restart.
const int MaxSavedBundles = 4000;
List _crew = new List();
void Awake()
{
Instance = this;
Perks = new NetworkList();
Tiles = new NetworkList();
Found = new NetworkList();
Opened = new NetworkList();
}
public override void OnNetworkSpawn()
{
Instance = this;
// the wallet has its own event: cards that rebuilt on every coin lost their scroll and their clicks
Money.OnValueChanged += (a, b) => MoneyChanged?.Invoke(a, b);
Perks.OnListChanged += _ => Changed?.Invoke();
Opened.OnListChanged += _ => Changed?.Invoke();
Tiles.OnListChanged += _ => { TilesChanged?.Invoke(); Changed?.Invoke(); };
if (!IsServer)
{
Difficulties.ApplyWire(Size.Value);
MowMap.Reset(); // the host sends what has been cut
}
WatchSectors();
if (IsServer)
{
for (int i = 0; i < (int)PerkId.Count; i++) Perks.Add(0);
Load();
}
TilesChanged?.Invoke();
Changed?.Invoke();
}
public override void OnNetworkDespawn()
{
if (Instance == this) Instance = null;
UnwatchSectors();
}
// ───────────────────────── queries ─────────────────────────
public int Level(PerkId id) => Perks != null && (int)id < Perks.Count ? Perks[(int)id] : 0;
public bool Has(PerkId id) => Level(id) > 0;
public bool PerkAvailable(PerkDef d)
{
foreach (var r in d.requires) if (Level(r) < d.requireLevel) return false;
return true;
}
/// Matrix installs so far, out of ; the uplink in the middle comes free.
public int Installs
{
get { int n = 1; foreach (var d in GameDefs.Perks) n += Level(d.id); return n; }
}
public static int TotalInstalls
{
get { int n = 1; foreach (var d in GameDefs.Perks) n += d.maxLevel; return n; }
}
public double Mown01 => Mown.Value / GameDefs.PlanetArea;
/// Whole days (sunrise to sunrise) this world has run.
public int Days => (int)(Played.Value / GameDefs.DayLength);
public float ToolCap(ToolId t) => GameDefs.IsBlade(t) ? GameDefs.ToolCap(t, GameDefs.HasBinPerk(t) ? Level(GameDefs.BinPerk(t)) : 0, Level(PerkId.Compactor)) : 0f;
/// The strip this tool cuts right now, in metres.
public float ToolWidth(ToolId t) => GameDefs.Tool(t).width * (1f + GameDefs.WidthBonus(Level(PerkId.WiderBlades))) * (1f + Level(PerkId.DeepSwath) * 0.06f) * (Has(PerkId.WhetSteel) ? 1.1f : 1f);
public float ToolDepthMul => (1f + Level(PerkId.DeepSwath) * 0.12f) * (Has(PerkId.WhetSteel) ? 1.1f : 1f);
public float ToolReach => GameDefs.ToolReach + Level(PerkId.LongHandles) * 0.75f + (Has(PerkId.WhetSteel) ? 0.5f : 0f);
public float BundleSeconds => GameDefs.BundleSeconds(Level(PerkId.QuickTwine), Level(PerkId.ExpressDepot));
/// Rings a robot starts further out, from Long Leash.
public int BotReachRings => Level(PerkId.BotReach);
/// How far out a robot may roam, against its own limit.
public float BotRoamMul => 1f + Level(PerkId.BotReach) * 0.25f;
public float BotSpeedMul => (1f + Level(PerkId.BotSpeed) * 0.12f) * (Has(PerkId.HiveMind) ? 1.2f : 1f);
public float BotHopperMul => 1f + Level(PerkId.BotHopper) * 0.25f;
public float DroneReachAdd => Level(PerkId.DroneRange) * GameDefs.DroneReachStep;
public float DroneSpeedMul => Has(PerkId.HiveMind) ? 1.2f : 1f;
public float PayoutMul => GameDefs.PayoutMul(Level(PerkId.EarthPrices), Level(PerkId.GreenExchange));
public double ToolPrice(ToolDef d) => d.id == ToolId.Hammer ? d.price : Math.Round(d.price * (double)GameDefs.ToolPriceMul(Level(PerkId.SupplyDeals)), 2);
public bool HasTile(int tx, int tz) => Tiles != null && Tiles.Contains(PackTile(tx, tz));
public bool OnDeck(Vector3 world) => Planet.InNorthCap(world) && HasTile(TileOf(world.x), TileOf(world.z));
public static int TileOf(float w) => Mathf.FloorToInt((w + GameDefs.TileSize * 0.5f) / GameDefs.TileSize);
public static int PackTile(int tx, int tz) => ((tx + 512) << 10) | (tz + 512);
public static Vector2Int UnpackTile(int p) => new Vector2Int((p >> 10) - 512, (p & 1023) - 512);
public static Vector3 TileCenter(int tx, int tz) => new Vector3(tx * GameDefs.TileSize, 0f, tz * GameDefs.TileSize);
// ───────────────────────── server: grass & money ─────────────────────────
/// Server: this much grass reached a depot. Pays at once and it is on its way to Earth.
public double ServerDeposit(float kg, CargoKind kind, Vector3 at)
{
if (!IsServer || kg <= 0f) return 0d;
double pay = kg * GameDefs.PerKg(kind) * PayoutMul;
Money.Value += pay;
Earned.Value += pay;
Shipped.Value += kg;
DepositedRpc(at, pay, kg);
return pay;
}
[Rpc(SendTo.Server)]
public void DepositRpc(float kg, byte kind, Vector3 at, RpcParams rpc = default)
{
if (kind > (byte)CargoKind.Brick) return;
ServerDeposit(Mathf.Clamp(kg, 0f, 50000f), (CargoKind)kind, at);
}
[Rpc(SendTo.Everyone)]
void DepositedRpc(Vector3 at, double pay, double kg) => Deposited?.Invoke(at, pay, kg);
/// Tie grass from a tool into a bundle at this spot.
[Rpc(SendTo.Server)]
public void BundleRpc(float kg, Vector3 at, Vector3 velocity, RpcParams rpc = default)
{
if (Spawner.Instance) Spawner.Instance.SpawnCargo(CargoKind.Grass, at, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f), velocity, Mathf.Clamp(kg, 0.01f, GameDefs.BundleKg));
}
// ───────────────────────── matrix ─────────────────────────
[Rpc(SendTo.Server)]
public void BuyPerkRpc(int perk, RpcParams rpc = default)
{
if (perk < 0 || perk >= (int)PerkId.Count) return;
var def = GameDefs.Perk((PerkId)perk);
int lvl = Level(def.id);
if (lvl >= def.maxLevel || !PerkAvailable(def) || Money.Value < def.PriceFor(lvl) || Demo.Over) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
Money.Value -= def.PriceFor(lvl);
Perks[perk] = (byte)(lvl + 1);
PurchasedRpc(PlayerName(rpc.Receive.SenderClientId), def.maxLevel > 1 ? Loc.Key(def.nameEn, GameDefs.ToRoman(lvl + 1)) : Loc.Key(def.nameEn));
Save();
}
[Rpc(SendTo.SpecifiedInParams)]
public void DeniedRpc(RpcParams p = default)
{
Sfx.Play("error");
if (Demo.Over) Hud.Toast(Loc.T("That's the end of the demo: the full game has the rest of the planet."), Hud.ToastKind.Warn);
}
[Rpc(SendTo.Everyone)]
void PurchasedRpc(FixedString64Bytes who, FixedString64Bytes what) => Purchased?.Invoke(who.ToString(), what.ToString());
public string PlayerName(ulong client)
{
var p = PlayerOf(client);
return p ? p.DisplayName : Loc.N("Someone");
}
public static PlayerAgent PlayerOf(ulong client)
{
foreach (var p in PlayerAgent.All) if (p.OwnerClientId == client) return p;
return null;
}
// ───────────────────────── supply wall (personal) ─────────────────────────
[Rpc(SendTo.Server)]
public void BuyToolRpc(byte tool, RpcParams rpc = default)
{
var who = PlayerOf(rpc.Receive.SenderClientId);
if (!who || tool >= GameDefs.ToolCount) return;
var d = GameDefs.Tool((ToolId)tool);
double price = ToolPrice(d);
if (who.Owns((ToolId)tool) || Money.Value < price || Demo.Over) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
Money.Value -= price;
who.Owned.Value |= (ushort)(1 << tool);
SaveCrew(who);
}
[Rpc(SendTo.Server)]
public void BuyBeltSlotRpc(RpcParams rpc = default)
{
var who = PlayerOf(rpc.Receive.SenderClientId);
if (!who) return;
long price = GameDefs.BeltSlotPrice(who.BeltSlots.Value);
if (who.BeltSlots.Value >= GameDefs.MaxBeltSlots || Money.Value < price || Demo.Over) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
Money.Value -= price;
who.BeltSlots.Value++;
SaveCrew(who);
}
[Rpc(SendTo.Server)]
public void BuyGearRpc(byte gear, RpcParams rpc = default)
{
var who = PlayerOf(rpc.Receive.SenderClientId);
if (!who || gear < (byte)GearId.Jetpack || gear > (byte)GearId.NightVision) return;
long price = GameDefs.GearPrice((GearId)gear);
if (who.HasGear((GearId)gear) || Money.Value < price || Demo.Over) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
Money.Value -= price;
who.Owned.Value |= (ushort)(1 << gear);
SaveCrew(who);
}
/// Server: someone joined: give them back their tools, or nothing at all on the first day.
public void ServerRestoreCrew(PlayerAgent p)
{
foreach (var c in _crew)
if (c.key == p.SaveId)
{
p.Owned.Value = (ushort)c.owned;
p.BeltSlots.Value = (byte)Mathf.Clamp(c.slots, 1, GameDefs.MaxBeltSlots);
if (c.owned != 0 && c.belt != null && c.bins != null) p.RestoreToolsRpc(c.owned, c.bins, c.belt, c.current);
return;
}
}
CrewSave CrewOf(PlayerAgent p)
{
var c = _crew.Find(x => x.key == p.SaveId);
if (c == null) { c = new CrewSave { key = p.SaveId }; _crew.Add(c); }
c.owned = p.Owned.Value;
c.slots = p.BeltSlots.Value;
return c;
}
void SaveCrew(PlayerAgent p)
{
CrewOf(p);
Save();
}
/// Server: what this player's tools hold, for the next save.
public void ServerStoreTools(PlayerAgent p, float[] bins, int[] belt, int current)
{
if (!p.ClaimedSave) return;
var c = CrewOf(p);
c.bins = bins;
c.belt = belt;
c.current = current;
}
// ───────────────────────── tick ─────────────────────────
float _saveTimer, _backupAt = 60f;
float _powerTimer;
public void ServerSetPhase(float phase) => DayOffset.Value = Sun.OffsetFor(phase);
void Update()
{
if (!IsServer || !IsSpawned) return;
Played.Value += Time.unscaledDeltaTime;
TickSectors();
TickWeather();
_powerTimer += Time.deltaTime;
if (_powerTimer > 0.25f) { PowerGrid.Tick(_powerTimer); _powerTimer = 0f; }
_saveTimer += Time.deltaTime;
if (_saveTimer > 30f) { _saveTimer = 0f; Save(); }
if (Time.time > _backupAt)
{
_backupAt = Time.time + 1800f;
Save();
SaveSlots.Backup();
}
}
[Rpc(SendTo.Everyone)]
public void AnnounceRpc(FixedString128Bytes text) => Announcement?.Invoke(text.ToString());
// ───────────────────────── persistence (host) ─────────────────────────
public void Save()
{
if (!IsServer) return;
var d = new SaveData { ver = 6, level = (int)Difficulties.Current, sizeGen = Difficulties.Gen, money = Money.Value, shipped = Shipped.Value, mown = Mown.Value, earned = Earned.Value, played = Played.Value, crew = _crew, day = Sun.Phase, vehicles = PackVehicles(), banned = _banned };
d.perks = new int[Perks.Count];
for (int i = 0; i < Perks.Count; i++) d.perks[i] = Perks[i];
d.tiles = new int[Tiles.Count];
for (int i = 0; i < Tiles.Count; i++) d.tiles[i] = Tiles[i];
d.found = new int[Found.Count];
for (int i = 0; i < Found.Count; i++) d.found[i] = Found[i];
d.stations = new int[Opened.Count];
for (int i = 0; i < Opened.Count; i++) d.stations[i] = Opened[i];
foreach (var p in BuildPiece.All)
if (p && p.IsSpawned) d.pieces.Add(new PieceSave { id = (int)p.piece, at = p.transform.position, turn = p.transform.rotation, to = p.To.Value, cfg = p.Setting, free = p.Free.Value, state = p.GetComponent()?.State });
foreach (var c in Cargo.All)
if (c && c.IsSpawned && !c.Grab.Consumed && d.cargo.Count < MaxSavedBundles)
d.cargo.Add(new CargoSave { kind = (int)c.kind, kg = c.Kg.Value, at = c.transform.position });
SaveSlots.Write(() => JsonUtility.ToJson(d), MowMap.SerializeLater());
}
void Load()
{
var json = SaveSlots.Read();
SaveData d = null;
if (!string.IsNullOrEmpty(json))
{
try { d = JsonUtility.FromJson(json); }
catch (Exception e) { Debug.LogWarning("[Save] corrupt save, starting fresh: " + e.Message); }
}
bool fresh = d == null || d.tiles == null || d.tiles.Length == 0;
if (d == null) d = new SaveData();
// the ball first: the mow map, the stakes and every piece go down on it
var level = fresh ? Difficulties.Chosen : (Difficulty)d.level;
if (fresh && CommandLine.Get("-difficulty") is string forced && byte.TryParse(forced, out byte f)) level = (Difficulty)f;
Difficulties.Apply(level, fresh ? Difficulties.NewGen : d.sizeGen);
Size.Value = Difficulties.Wire;
MowMap.Reset();
if (!fresh) LoadMow();
Money.Value = d.money;
Shipped.Value = d.shipped;
// saves from before the crew's pay was counted start from what they have shipped
Earned.Value = d.earned > 0d ? d.earned : d.money;
Played.Value = d.played;
ServerSetPhase(d.day);
Mown.Value = MownNow();
MowMap.Count();
Closed.Value = MowMap.Finished;
if (d.found != null) foreach (int id in d.found) Found.Add(id);
if (d.stations != null) foreach (int id in d.stations) Opened.Add((byte)id);
_banned = d.banned ?? new List();
_crew = d.crew ?? new List();
if (d.perks != null) for (int i = 0; i < d.perks.Length && i < Perks.Count; i++) Perks[i] = (byte)d.perks[i];
// machines used to be crew upgrades after the last perk: what was paid for them comes back
if (d.perks != null && d.ver < 2)
for (int i = Perks.Count; i < d.perks.Length && i - Perks.Count < OldFleet.Length; i++)
for (int l = 0; l < d.perks[i] && l < OldFleet[i - Perks.Count].Length; l++) Money.Value += OldFleet[i - Perks.Count][l];
if (fresh)
{
for (int x = -1; x <= 1; x++) for (int z = -1; z <= 1; z++) Tiles.Add(PackTile(x, z));
TilesChanged?.Invoke();
Spawner.Instance?.ServerSpawnStarter();
}
else
{
foreach (var t in d.tiles) Tiles.Add(t);
TilesChanged?.Invoke();
if (d.ver < 1)
{
// what stood on the old grid can't be placed any more: the crew gets its money back
if (d.pieces != null) foreach (var p in d.pieces) if (!p.free) Money.Value += p.id == 4 ? 5d : 0.5d;
Spawner.Instance?.ServerSpawnStarter();
}
else if (d.pieces != null)
foreach (var p in d.pieces)
if (p.id >= 0 && p.id < GameDefs.Pieces.Length) ServerSpawnPiece((PieceId)p.id, p.at, p.turn, p.to, p.cfg, p.free, p.state);
// bundles lie where they were left; those on a belt climb back on by themselves
if (d.cargo != null && Spawner.Instance)
foreach (var c in d.cargo)
if (c.kind >= 0 && c.kind <= (int)CargoKind.Brick && c.kg > 0f) Spawner.Instance.SpawnCargo((CargoKind)c.kind, c.at, Quaternion.identity, Vector3.zero, c.kg);
}
if (d.ver < 3) ServerSpawnStations();
if (d.ver < 4) ServerSpawnIntakes();
else if (d.ver < 5) ServerSwapIntakes();
else if (d.ver < 6) ServerRespawnIntakes();
if (!fresh) UnpackVehicles(d.vehicles);
foreach (var p in PlayerAgent.All) if (p.ClaimedSave) ServerRestoreCrew(p);
}
/// The slot's own map, or the newest backup that can still be read.
static void LoadMow()
{
if (MowMap.LoadFile(SaveSlots.MapPath)) return;
foreach (var path in SaveSlots.OlderMaps())
{
MowMap.Reset();
if (MowMap.LoadFile(path)) return;
}
MowMap.Reset();
}
public static void DeleteSave() => SaveSlots.Delete(SaveSlots.Current);
}
}