Files
grass-cutters/Assets/Scripts/World/MowMap.cs
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:44:40 +06:00

692 lines
31 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// What has been cut on Herbaria-7, sector by sector. A sector nobody has touched costs nothing; a touched one keeps a
/// 128² map in its own flat frame: how much grass is left in each cell (what a blade sweeps is exactly what lands in
/// its container) and how it looks (red: cut, green: nothing grows, under the deck and rocks). A finished sector shrinks
/// to a single flag, one far away to a compressed block. The host writes it all to disk; a late joiner gets it over the
/// wire. Every peer cuts for itself from the same strokes.
/// </summary>
public static class MowMap
{
public const int Res = 128;
/// <summary>The last scraps of a sector this nearly done go with the stroke that got it there.</summary>
// the last few scraps (behind rocks, along the seams) go by themselves: no hunting for the final percent
const float DoneAt = 0.97f;
const int MaxStampsPerCut = 28, MaxOpen = 300;
/// <summary>Less than this left in a cell is not worth a row of its own.</summary>
const ushort Scrap = 120;
const float MinPaintRadius = 0.15f;
public const float PaintFeather = 0.25f;
public class Mask
{
public HexGrid.Sector s;
public float cell, area; // one cell: its side, its square metres
public ushort[] left; // 65535 = untouched, null while packed
public byte[] rg; // r, g per cell
public byte[] packed;
public float total, mown; // square metres
public bool done;
public bool paid; // the host has paid out for it
public bool keep; // somebody cut here: it goes in the save
public bool dirty; // changed since it was last packed
public bool show; // the texture is out of date
public Texture2D tex;
}
class Bare { public bool round; public Vector3 center, dir; public float radius; public Vector2 half; }
static readonly Dictionary<int, Mask> s_masks = new Dictionary<int, Mask>();
static readonly Dictionary<int, List<Bare>> s_blocks = new Dictionary<int, List<Bare>>();
static readonly HashSet<int> s_deck = new HashSet<int>();
static readonly List<int> s_walk = new List<int>();
static readonly List<int> s_touched = new List<int>();
static Texture2D s_none, s_full;
/// <summary>This peer has just mown a sector clean.</summary>
public static event Action<int> SectorDone;
/// <summary>A sector is finished, by anyone, or by a save as it loads: the trees and bushes on it go too.</summary>
public static event Action<int> Bared;
/// <summary>Everything is uncut again, so whatever went with a finished sector stands again.</summary>
public static event Action Restarted;
public static IEnumerable<Mask> All => s_masks.Values;
/// <summary>The map of a sector with nothing on it.</summary>
public static Texture2D Blank => s_none;
public static int Started { get; private set; }
public static int Finished { get; private set; }
// ───────────────────────── sessions ─────────────────────────
/// <summary>A new game: nothing is cut yet (the rocks and the base stay).</summary>
public static void Reset()
{
foreach (var m in s_masks.Values) Drop(m);
s_masks.Clear();
Started = Finished = 0;
Restarted?.Invoke();
}
public static void ResetBlocks()
{
s_blocks.Clear();
s_deck.Clear();
}
static void Drop(Mask m)
{
if (m.tex) UnityEngine.Object.Destroy(m.tex);
m.tex = null;
}
// ───────────────────────── nothing grows here ─────────────────────────
/// <summary>Nothing grows inside this rectangle of the base (axis-aligned, only near the pole).</summary>
public static void Block(Vector3 center, Vector2 half) => Add(new Bare { center = center, half = half }, half.magnitude);
/// <summary>Nothing grows under this rock.</summary>
public static void BlockRound(Vector3 center, float radius) => Add(new Bare { round = true, center = center, dir = Planet.Up(center), radius = radius }, radius);
/// <summary>The deck can only grow: new tiles join the blocks.</summary>
public static void SetDeck(IEnumerable<int> tiles)
{
float h = GameDefs.TileSize * 0.5f + 0.15f;
foreach (int t in tiles)
if (s_deck.Add(t))
{
var c = TeamState.UnpackTile(t);
var ctr = TeamState.TileCenter(c.x, c.y);
Add(new Bare { center = ctr, half = new Vector2(h, h) }, h * 1.5f);
}
}
static void Add(Bare b, float reach)
{
// every sector it can touch, walking out from the one it stands in
s_walk.Clear();
int first = HexGrid.SectorAt(Planet.Up(b.center));
s_walk.Add(first);
var dir = Planet.Up(b.center);
for (int i = 0; i < s_walk.Count; i++)
{
var s = HexGrid.Get(s_walk[i]);
if ((s.c - dir).magnitude * Planet.Radius > reach + s.radius) continue;
if (!s_blocks.TryGetValue(s.id, out var list)) s_blocks[s.id] = list = new List<Bare>();
list.Add(b);
if (s_masks.TryGetValue(s.id, out var m) && m.left != null) Apply(m, b);
foreach (int n in s.neighbours) if (!s_walk.Contains(n)) s_walk.Add(n);
}
}
static void Apply(Mask m, Bare b)
{
var s = m.s;
// only the cells the block can reach: a base is hundreds of tiles, and a sector 16k cells, so looking at all of
// them for every tile stalled the frame each time a sector near the base was opened
Flat(s, Planet.Up(b.center), out float bu, out float bv);
float reach = (b.round ? b.radius : b.half.magnitude) * 1.5f + m.cell * 2f;
int x0 = Mathf.Max(0, Mathf.FloorToInt((bu - reach + s.half) / m.cell)), x1 = Mathf.Min(Res - 1, Mathf.CeilToInt((bu + reach + s.half) / m.cell));
int z0 = Mathf.Max(0, Mathf.FloorToInt((bv - reach + s.half) / m.cell)), z1 = Mathf.Min(Res - 1, Mathf.CeilToInt((bv + reach + s.half) / m.cell));
for (int z = z0; z <= z1; z++)
for (int x = x0; x <= x1; x++)
{
int i = z * Res + x;
if (m.rg[i * 2 + 1] != 0) continue;
var flat = s.c * Planet.Radius + s.e1 * Cell(m, x) + s.e2 * Cell(m, z);
var p = Planet.Center + flat;
// a rock is measured along the ground: the frame is flat, the soil isn't
bool hit = b.round
? (flat.normalized - b.dir).sqrMagnitude * Planet.Radius * Planet.Radius < b.radius * b.radius
: Mathf.Abs(p.x - b.center.x) < b.half.x && Mathf.Abs(p.z - b.center.z) < b.half.y;
if (!hit) continue;
m.rg[i * 2 + 1] = 255;
// nobody can cut what stands under a rock: it isn't part of the sector's grass
if (Owned(s, x, z, m)) m.total = Mathf.Max(0f, m.total - m.area);
m.left[i] = 0;
m.show = true;
}
}
static float Cell(Mask m, int i) => (i + 0.5f) * m.cell - m.s.half;
static bool Owned(HexGrid.Sector s, int x, int z, Mask m)
{
var p = s.c * Planet.Radius + s.e1 * Cell(m, x) + s.e2 * Cell(m, z);
foreach (var b in s.borders)
if (p.x * b.x + p.y * b.y + p.z * b.z > 0f) return false;
return true;
}
// ───────────────────────── opening a sector ─────────────────────────
static Mask Find(int id) => s_masks.TryGetValue(id, out var m) ? m : null;
/// <summary>The sector's map ready to read and write. Null when it is finished: nothing left to do there.</summary>
static Mask Open(int id)
{
var m = Find(id);
if (m == null)
{
var s = HexGrid.Get(id);
m = new Mask { s = s, cell = s.half * 2f / Res };
m.area = m.cell * m.cell;
s_masks[id] = m;
}
if (m.done) return null;
if (m.left == null) Unpack(m);
return m;
}
static void Fresh(Mask m)
{
m.left = new ushort[Res * Res];
m.rg = new byte[Res * Res * 2];
int owned = 0;
for (int z = 0; z < Res; z++)
for (int x = 0; x < Res; x++)
if (Owned(m.s, x, z, m)) { m.left[z * Res + x] = 65535; owned++; }
float total = owned * m.area;
if (m.total <= 0f) m.total = total;
m.show = true;
if (s_blocks.TryGetValue(m.s.id, out var list))
{
float kept = m.total;
m.total = total;
foreach (var b in list) Apply(m, b);
if (m.packed != null) m.total = kept;
}
}
static void Unpack(Mask m)
{
Fresh(m);
if (m.packed == null) return;
var raw = Inflate(m.packed);
System.Buffer.BlockCopy(raw, 0, m.left, 0, Res * Res * 2);
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = raw[Res * Res * 2 + i];
m.show = true;
}
static void Pack(Mask m)
{
var raw = new byte[Res * Res * 3];
System.Buffer.BlockCopy(m.left, 0, raw, 0, Res * Res * 2);
for (int i = 0; i < Res * Res; i++) raw[Res * Res * 2 + i] = m.rg[i * 2];
using (var mem = new MemoryStream())
{
using (var z = new DeflateStream(mem, System.IO.Compression.CompressionLevel.Fastest, true)) z.Write(raw, 0, raw.Length);
m.packed = mem.ToArray();
}
m.dirty = false;
}
static byte[] Inflate(byte[] packed)
{
var raw = new byte[Res * Res * 3];
using (var z = new DeflateStream(new MemoryStream(packed), CompressionMode.Decompress))
{
int at = 0, n;
while (at < raw.Length && (n = z.Read(raw, at, raw.Length - at)) > 0) at += n;
}
return raw;
}
/// <summary>Too many maps in memory: squeeze the ones furthest from here.</summary>
public static void Trim(Vector3 dir)
{
int open = 0;
foreach (var m in s_masks.Values) if (m.left != null) open++;
if (open <= MaxOpen) return;
var list = new List<Mask>();
foreach (var m in s_masks.Values) if (m.left != null) list.Add(m);
list.Sort((a, b) => (b.s.c - dir).sqrMagnitude.CompareTo((a.s.c - dir).sqrMagnitude));
for (int i = 0; i < open - MaxOpen; i++)
{
var m = list[i];
if (m.dirty || (m.keep && m.packed == null)) Pack(m);
// only the grass counts go: the look (and its texture) stays, because the overlay of worked ground still
// draws these sectors, and taking it away had every one of them unpacked again the very next frame
m.left = null;
}
}
// ───────────────────────── cutting ─────────────────────────
/// <summary>
/// Sweep a blade from one point to another. Returns the square metres of grass it actually cut: only what is still
/// standing counts, so the whole planet is worth exactly its area. minSweep lets a blade held still eat what is
/// under it, paint widens only what the eye sees, so that rows laid edge to edge show no seam.
/// </summary>
public static float Cut(Vector3 from, Vector3 to, float width, float minSweep = 0f, float paint = 0f)
{
var up = Planet.Up(to);
var flat = Vector3.ProjectOnPlane(to - from, up);
float len = flat.magnitude;
float sweep = Mathf.Max(len, minSweep);
float half = width * 0.5f;
float cut = 0f;
// every sector the stroke touches, each for the part of it that lies there
s_touched.Clear();
int points = Mathf.CeilToInt(len / 8f) + 1;
for (int i = 0; i < points; i++)
{
var d = Planet.Up(Vector3.Lerp(from, to, points > 1 ? (float)i / (points - 1) : 1f));
var s = HexGrid.Get(HexGrid.SectorAt(d));
if (!s_touched.Contains(s.id)) s_touched.Add(s.id);
for (int k = 0; k < s.neighbours.Count; k++)
if (-Vector3.Dot(d, s.borders[k]) < half + 0.5f && !s_touched.Contains(s.neighbours[k])) s_touched.Add(s.neighbours[k]);
}
var a = Planet.Up(from);
var b = Planet.Up(to);
foreach (int id in s_touched)
{
var m = Open(id);
if (m == null) continue;
cut += Sweep(m, a, b, half, sweep);
cut += Settle(m);
}
if (cut <= 0f) return 0f;
Critters.Disturb(to, half, cut);
float r = half + paint;
int stamps = Mathf.Clamp(Mathf.CeilToInt(len / Mathf.Max(r, 0.25f)) + 1, 1, MaxStampsPerCut);
for (int i = 0; i < stamps; i++) Stamp(Vector3.Lerp(from, to, stamps > 1 ? (float)i / (stamps - 1) : 1f), r);
return cut;
}
/// <summary>
/// Take what the strip covers out of each cell under it: the share of the cell across the strip times the share
/// along this stroke, so one full pass leaves nothing and strokes laid edge to edge leave no gap. Returns square metres.
/// </summary>
static float Sweep(Mask m, Vector3 a, Vector3 b, float half, float sweep)
{
var s = m.s;
Flat(s, a, out float u0, out float v0);
Flat(s, b, out float u1, out float v1);
float du = u1 - u0, dv = v1 - v0, len = Mathf.Sqrt(du * du + dv * dv);
float ux = len > 1e-4f ? du / len : 1f, uv = len > 1e-4f ? dv / len : 0f;
float extra = Mathf.Max(0f, sweep - len) * 0.5f;
float h = m.cell * 0.5f * (Mathf.Abs(ux) + Mathf.Abs(uv));
float reach = half + h + extra;
int x0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(u0, u1) - reach + s.half) / m.cell));
int x1 = Mathf.Min(Res - 1, Mathf.CeilToInt((Mathf.Max(u0, u1) + reach + s.half) / m.cell));
int z0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(v0, v1) - reach + s.half) / m.cell));
int z1 = Mathf.Min(Res - 1, Mathf.CeilToInt((Mathf.Max(v0, v1) + reach + s.half) / m.cell));
float top = Mathf.Min(half / h, 1f), slope = 1f / (2f * Mathf.Min(half, h));
float got = 0f;
for (int z = z0; z <= z1; z++)
for (int x = x0; x <= x1; x++)
{
int k = z * Res + x;
ushort has = m.left[k];
if (has == 0) continue;
float cu = Cell(m, x) - u0, cv = Cell(m, z) - v0;
float across = Mathf.Clamp01((half + h - Mathf.Abs(cv * ux - cu * uv)) * slope) * top;
if (across <= 0f) continue;
float t = cu * ux + cv * uv;
float along = (Mathf.Min(t + h, len + extra) - Mathf.Max(t - h, -extra)) / (2f * h);
if (along <= 0f) continue;
int take = Mathf.Min(has, Mathf.CeilToInt(across * Mathf.Min(along, 1f) * 65535f));
m.left[k] = (ushort)(has - take);
float area = take / 65535f * m.area;
m.mown += area;
got += area;
}
if (got > 0f) m.dirty = m.keep = true;
return got;
}
/// <summary>
/// Rows that would take all that still stands in a sector, laid edge to edge along its flat frame: x is where the row
/// lies across, y and z where it starts and ends, in metres. None when nothing is left.
/// </summary>
public static void Rows(int id, float width, List<Vector3> into)
{
into.Clear();
var m = Open(id);
if (m == null) return;
int bands = Mathf.CeilToInt(m.s.half * 2f / width);
var lo = new float[bands];
var hi = new float[bands];
for (int b = 0; b < bands; b++) { lo[b] = float.MaxValue; hi[b] = float.MinValue; }
for (int z = 0; z < Res; z++)
{
int band = Mathf.Min(bands - 1, (int)((Cell(m, z) + m.s.half) / width));
for (int x = 0; x < Res; x++)
{
if (m.left[z * Res + x] <= Scrap) continue;
float u = Cell(m, x);
lo[band] = Mathf.Min(lo[band], u);
hi[band] = Mathf.Max(hi[band], u);
}
}
for (int b = 0; b < bands; b++)
if (lo[b] <= hi[b]) into.Add(new Vector3((b + 0.5f) * width - m.s.half, lo[b], hi[b]));
}
/// <summary>The direction of the fullest cell still standing in a sector, and how many cells have anything left (for the test bot).</summary>
public static int Leftover(int id, out Vector3 dir)
{
dir = HexGrid.Get(id).c;
var m = Open(id);
if (m == null) return 0;
int count = 0, best = 0;
for (int z = 0; z < Res; z++)
for (int x = 0; x < Res; x++)
{
int left = m.left[z * Res + x];
if (left == 0 || !Owned(m.s, x, z, m)) continue;
count++;
if (left <= best) continue;
best = left;
dir = (m.s.c * Planet.Radius + m.s.e1 * Cell(m, x) + m.s.e2 * Cell(m, z)).normalized;
}
return count;
}
/// <summary>Where a direction falls in a sector's flat frame, in metres.</summary>
public static void Flat(HexGrid.Sector s, Vector3 d, out float u, out float v)
{
var p = d * (Planet.Radius / Mathf.Max(0.5f, Vector3.Dot(d, s.c))) - s.c * Planet.Radius;
u = Vector3.Dot(p, s.e1);
v = Vector3.Dot(p, s.e2);
}
/// <summary>Show a stroke on this sector and on any neighbour it spills onto.</summary>
static void Stamp(Vector3 at, float r)
{
var d = Planet.Up(at);
var s = HexGrid.Get(HexGrid.SectorAt(d));
Paint(s, d, r);
float reach = Mathf.Max(r, MinPaintRadius) + PaintFeather + 0.3f;
for (int k = 0; k < s.neighbours.Count; k++)
if (-Vector3.Dot(d, s.borders[k]) < reach) Paint(HexGrid.Get(s.neighbours[k]), d, r);
}
static void Paint(HexGrid.Sector s, Vector3 d, float r)
{
var m = Open(s.id);
if (m == null) return;
Flat(s, d, out float u, out float v);
float size = Mathf.Max(r, MinPaintRadius) + PaintFeather;
int x0 = Mathf.Max(0, Mathf.FloorToInt((u - size + s.half) / m.cell)), x1 = Mathf.Min(Res - 1, Mathf.CeilToInt((u + size + s.half) / m.cell));
int z0 = Mathf.Max(0, Mathf.FloorToInt((v - size + s.half) / m.cell)), z1 = Mathf.Min(Res - 1, Mathf.CeilToInt((v + size + s.half) / m.cell));
float reach = Mathf.Max(r, MinPaintRadius);
for (int z = z0; z <= z1; z++)
for (int x = x0; x <= x1; x++)
{
float dx = Cell(m, x) - u, dz = Cell(m, z) - v;
float f = Mathf.Clamp01((reach - Mathf.Sqrt(dx * dx + dz * dz)) / PaintFeather + 0.5f);
byte b = (byte)(f * 255f);
int i = (z * Res + x) * 2;
if (b > m.rg[i]) { m.rg[i] = b; m.show = m.dirty = m.keep = true; }
}
}
/// <summary>Is this sector as good as done? Then the last scraps go with this stroke. Returns their square metres.</summary>
static float Settle(Mask m)
{
if (m.done || m.total <= 0f || m.mown < m.total * DoneAt) return 0f;
float rest = m.total - m.mown;
Finish(m);
SectorDone?.Invoke(m.s.id);
return rest;
}
/// <summary>Host: this sector is done, whoever got there first. False when it has already been paid for.</summary>
public static bool Claim(int id)
{
var m = Open(id) ?? Find(id);
if (m.paid) return false;
if (!m.done) Finish(m);
m.paid = true;
return true;
}
/// <summary>The host says this sector is done.</summary>
public static void Close(int id)
{
var m = Open(id);
if (m != null) Finish(m);
}
static void Finish(Mask m)
{
m.done = m.keep = true;
m.dirty = false;
m.mown = m.total;
m.left = null;
m.packed = null;
if (s_blocks.ContainsKey(m.s.id) && m.rg != null)
{
// the rock keeps its bare patch
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = 255;
m.show = true;
}
else
{
m.rg = null;
Drop(m);
}
Bared?.Invoke(m.s.id);
}
/// <summary>Cheat: the whole sector goes at once. Returns the square metres that were still standing.</summary>
public static float CutSector(int id)
{
var m = Open(id);
if (m == null) return 0f;
float rest = m.total - m.mown;
Finish(m);
SectorDone?.Invoke(id);
return rest;
}
// ───────────────────────── reading ─────────────────────────
/// <summary>How much grass is left here: 1 = full meadow, 0 = mown (it never grows back).</summary>
public static float Yield(Vector3 at)
{
var d = Planet.Up(at);
var m = Find(HexGrid.SectorAt(d));
if (m == null) return 1f;
if (m.done) return 0f;
if (m.left == null) Unpack(m);
Flat(m.s, d, out float u, out float v);
int x = Mathf.FloorToInt((u + m.s.half) / m.cell), z = Mathf.FloorToInt((v + m.s.half) / m.cell);
if (x < 0 || z < 0 || x >= Res || z >= Res) return 1f;
return m.left[z * Res + x] / 65535f;
}
/// <summary>No grass standing here: it has been cut, or nothing ever grew. Things are only built on such ground.</summary>
public static bool Clear(Vector3 at)
{
var d = Planet.Up(at);
int id = HexGrid.SectorAt(d);
if (Find(id) == null && !s_blocks.ContainsKey(id)) return false;
var m = Open(id);
if (m == null) return true;
Flat(m.s, d, out float u, out float v);
int x = Mathf.FloorToInt((u + m.s.half) / m.cell), z = Mathf.FloorToInt((v + m.s.half) / m.cell);
return x >= 0 && z >= 0 && x < Res && z < Res && m.left[z * Res + x] < 16384;
}
static float Cleared(Mask m) => m.done ? 1f : m.total > 0f ? Mathf.Clamp01(m.mown / m.total) : 0f;
/// <summary>How much of a sector is mown, 0..1.</summary>
public static float Cleared(int id) => s_masks.TryGetValue(id, out var m) ? Cleared(m) : 0f;
/// <summary>Square metres mown on the whole planet, as this peer knows it.</summary>
public static float MownArea()
{
float sum = 0f;
foreach (var m in s_masks.Values) sum += m.mown;
return sum;
}
/// <summary>Grass in a sector when nobody has touched it, in square metres.</summary>
public static float Total(int id)
{
var m = Find(id);
if (m == null || m.total <= 0f) m = Open(id);
return m != null ? m.total : 0f;
}
/// <summary>The map as the shaders read it (the blank one for an untouched sector with nothing in the way).</summary>
public static Texture2D TextureFor(HexGrid.Sector s)
{
if (!s_none) s_none = Single(new Color32(0, 0, 0, 255));
if (!s_full) s_full = Single(new Color32(255, 0, 0, 255));
var m = Find(s.id);
if (m == null)
{
if (!s_blocks.ContainsKey(s.id)) return s_none;
m = Open(s.id);
}
if (m.done && m.rg == null)
{
if (!s_blocks.ContainsKey(s.id)) return s_full;
Fresh(m);
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = 255;
m.left = null;
m.show = true;
}
if (m.rg == null) Unpack(m);
if (!m.tex)
{
// the mips are the soft edge of a cut: the grass beside it reads them to stand lower
m.tex = new Texture2D(Res, Res, TextureFormat.RG16, true, true) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear };
m.show = true;
}
if (m.show)
{
m.tex.SetPixelData(m.rg, 0);
m.tex.Apply(true, false);
m.show = false;
}
return m.tex;
}
static Texture2D Single(Color32 c)
{
var t = new Texture2D(1, 1, TextureFormat.RG16, false, true) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Point };
t.SetPixelData(new[] { c.r, c.g }, 0);
t.Apply(false, true);
return t;
}
public static void Count()
{
Started = Finished = 0;
foreach (var m in s_masks.Values)
{
if (m.done) Finished++;
else if (m.keep) Started++;
}
}
// ───────────────────────── saving ─────────────────────────
const int Magic = 0x314D4347; // "GCM1"
/// <summary>Everything cut so far, as one block of bytes (the save file, and what a late joiner is sent).</summary>
public static byte[] Serialize()
{
using (var mem = new MemoryStream())
using (var w = new BinaryWriter(mem))
{
int count = 0;
foreach (var m in s_masks.Values) if (m.keep) count++;
w.Write(Magic);
w.Write(count);
foreach (var m in s_masks.Values)
{
if (!m.keep) continue;
if (!m.done && (m.dirty || m.packed == null) && m.left != null) Pack(m);
w.Write(m.s.id);
w.Write(m.total);
w.Write(m.mown);
w.Write(m.done);
int len = m.done || m.packed == null ? 0 : m.packed.Length;
w.Write(len);
if (len > 0) w.Write(m.packed);
}
w.Flush();
return mem.ToArray();
}
}
/// <summary>Take in a saved game. What this peer has cut in the meantime stays cut.</summary>
public static void Merge(byte[] data)
{
if (data == null || data.Length < 8) return;
using (var r = new BinaryReader(new MemoryStream(data)))
{
if (r.ReadInt32() != Magic) { Debug.LogWarning("[MowMap] not a mow map, ignored"); return; }
int count = r.ReadInt32();
for (int i = 0; i < count; i++)
{
int id = r.ReadInt32();
float total = r.ReadSingle(), mown = r.ReadSingle();
bool done = r.ReadBoolean();
int len = r.ReadInt32();
var packed = len > 0 ? r.ReadBytes(len) : null;
var had = Find(id);
if (had != null && had.done) continue;
var s = HexGrid.Get(id);
if (had == null)
{
had = new Mask { s = s, cell = s.half * 2f / Res };
had.area = had.cell * had.cell;
s_masks[id] = had;
}
had.keep = true;
if (done) { Finish(had); had.total = total; had.mown = total; had.paid = true; continue; }
if (had.left == null)
{
had.total = total;
had.mown = mown;
had.packed = packed;
had.rg = null; // a squeezed sector keeps its look: this one is out of date now
continue;
}
if (packed == null) continue;
var raw = Inflate(packed);
float left = 0f;
for (int k = 0; k < Res * Res; k++)
{
int theirs = raw[k * 2] | raw[k * 2 + 1] << 8;
if (theirs < had.left[k]) had.left[k] = (ushort)theirs;
left += had.left[k] / 65535f;
byte b = raw[Res * Res * 2 + k];
if (b > had.rg[k * 2]) had.rg[k * 2] = b;
}
had.mown = Mathf.Max(0f, had.total - left * had.area);
had.show = had.dirty = true;
}
}
Count();
}
/// <summary>False when the file is there but can't be read.</summary>
public static bool LoadFile(string path)
{
if (!File.Exists(path)) return true;
try { Merge(File.ReadAllBytes(path)); return true; }
catch (Exception e) when (e is IOException || e is InvalidDataException || e is IndexOutOfRangeException || e is ArgumentException)
{
Debug.LogWarning("[MowMap] can't read the save: " + e.Message);
return false;
}
}
}
}