Smoother drives across the meadow: no more hitches opening sectors

- Sector maps are put away on a worker thread, and trimmed in batches
- A far sector's texture only needs its look; at most four new ones a frame
- Fresh maps fill rows between their borders instead of testing every cell
- Rocks are marked with plain numbers; marks come back on unpacked maps
- Worked-overlay sort uses float keys; idle belts look on staggered steps
- Chase camera cast no longer allocates; perf demo drives and runs too

Drive phase on a late save: p99 33 -> 16 ms, frames over 20 ms 242 -> 7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-11-10 12:59:16 +06:00
parent 29485df9e1
commit 172c3b978d
6 changed files with 271 additions and 76 deletions

View File

@ -20,6 +20,8 @@ namespace GrassCutter
// the last few scraps (behind rocks, along the seams) go by themselves: no hunting for the final percent
const float DoneAt = 0.93f;
const int MaxStampsPerCut = 28, MaxOpen = 300;
/// <summary>Trim waits for this many more open maps than it keeps, so it runs now and then, not at every sector.</summary>
const int TrimSlack = 80;
/// <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;
@ -32,6 +34,8 @@ namespace GrassCutter
public ushort[] left; // 65535 = untouched, null while packed
public byte[] rg; // r, g per cell
public byte[] packed;
/// <summary>Its bytes, unsqueezed, while a worker packs them (null otherwise).</summary>
public byte[] raw;
public float total, mown; // square metres
public bool done;
public bool paid; // the host has paid out for it
@ -127,7 +131,9 @@ namespace GrassCutter
}
}
static void Apply(Mask m, Bare b)
/// <param name="fresh">The map was just made: a cell is the sector's exactly when it still has grass.</param>
/// <param name="look">Only the look: the counts came from a packed copy that already has the rock in it.</param>
static void Apply(Mask m, Bare b, bool fresh = false, bool look = false)
{
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
@ -136,24 +142,41 @@ namespace GrassCutter
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));
// plain numbers, not vectors: a big rock covers thousands of cells, and a fresh sector may have a dozen of them
float rr = Planet.Radius * Planet.Radius, r2 = b.radius * b.radius;
var c = s.c * Planet.Radius;
var e1 = s.e1;
var e2 = s.e2;
var pc = Planet.Center;
for (int z = z0; z <= z1; z++)
{
float v = Cell(m, z);
float rx = c.x + e2.x * v, ry = c.y + e2.y * v, rz = c.z + e2.z * v;
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;
float u = Cell(m, x);
float fx = rx + e1.x * u, fy = ry + e1.y * u, fz = rz + e1.z * u;
bool hit;
if (b.round)
{
// a rock is measured along the ground: the frame is flat, the soil isn't
float inv = 1f / Mathf.Sqrt(fx * fx + fy * fy + fz * fz);
float dx = fx * inv - b.dir.x, dy = fy * inv - b.dir.y, dz = fz * inv - b.dir.z;
hit = (dx * dx + dy * dy + dz * dz) * rr < r2;
}
else hit = Mathf.Abs(pc.x + fx - b.center.x) < b.half.x && Mathf.Abs(pc.z + fz - b.center.z) < b.half.y;
if (!hit) continue;
m.rg[i * 2 + 1] = 255;
m.show = true;
if (look) continue;
// 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);
if (fresh ? m.left[i] != 0 : 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;
@ -191,9 +214,36 @@ namespace GrassCutter
m.left = new ushort[Res * Res];
m.rg = new byte[Res * Res * 2];
int owned = 0;
var s = m.s;
var c = s.c * Planet.Radius;
// the sector is a convex patch of the flat frame, so each row of it is one run of cells: the borders give its
// ends, and only the cells at the ends are tested one by one (testing all 16k of them stalled the frame)
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++; }
{
var row = c + s.e2 * Cell(m, z);
float lo = float.NegativeInfinity, hi = float.PositiveInfinity;
bool none = false;
foreach (var b in s.borders)
{
float a = Vector3.Dot(row, b), k = Vector3.Dot(s.e1, b);
if (Mathf.Abs(k) < 1e-6f) { if (a > 0f) none = true; continue; }
if (k > 0f) hi = Mathf.Min(hi, -a / k);
else lo = Mathf.Max(lo, -a / k);
}
if (none) continue;
int xa = Mathf.CeilToInt(Mathf.Clamp((lo + s.half) / m.cell - 0.5f, -1f, Res));
int xb = Mathf.FloorToInt(Mathf.Clamp((hi + s.half) / m.cell - 0.5f, -1f, Res));
xa = Mathf.Clamp(xa, 0, Res - 1);
xb = Mathf.Clamp(xb, 0, Res - 1);
if (xa > xb) continue;
while (xa <= xb && !Owned(s, xa, z, m)) xa++;
while (xb >= xa && !Owned(s, xb, z, m)) xb--;
if (xa > xb) continue;
while (xa > 0 && Owned(s, xa - 1, z, m)) xa--;
while (xb < Res - 1 && Owned(s, xb + 1, z, m)) xb++;
for (int x = xa; x <= xb; x++) m.left[z * Res + x] = 65535;
owned += xb - xa + 1;
}
float total = owned * m.area;
if (m.total <= 0f) m.total = total;
m.show = true;
@ -201,19 +251,44 @@ namespace GrassCutter
{
float kept = m.total;
m.total = total;
foreach (var b in list) Apply(m, b);
foreach (var b in list) Apply(m, b, true);
if (m.packed != null) m.total = kept;
}
}
static void Unpack(Mask m)
/// <summary>Just the look of a packed sector, for its texture: the grass counts stay packed.</summary>
static void Look(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);
var raw = m.raw;
if (raw == null && m.packed != null) raw = Inflate(m.packed, s_inflate);
if (raw == null) { Unpack(m); return; }
m.rg = new byte[Res * Res * 2];
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = raw[Res * Res * 2 + i];
m.show = true;
MarkBare(m);
}
/// <summary>The packed copy keeps the grass, not where nothing grows: the blocks mark that again on a new look.</summary>
static void MarkBare(Mask m)
{
if (!s_blocks.TryGetValue(m.s.id, out var list)) return;
foreach (var b in list) Apply(m, b, false, true);
}
static void Unpack(Mask m)
{
// bytes being squeezed right now, or squeezed ones: no fresh start needed, they say everything
var raw = m.raw;
if (raw == null && m.packed != null) raw = Inflate(m.packed, s_inflate);
if (raw == null) { Fresh(m); return; }
m.left = new ushort[Res * Res];
bool had = m.rg != null && m.tex;
bool fresh = m.rg == null;
if (fresh) m.rg = new byte[Res * Res * 2];
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];
if (fresh) MarkBare(m);
if (!had) m.show = true;
}
static void Pack(Mask m)
@ -247,11 +322,42 @@ namespace GrassCutter
{
while (s_packed.TryDequeue(out var p))
if (p.m.packed == null && !p.m.dirty && p.m.left != null) p.m.packed = p.packed;
while (s_squeezed.TryDequeue(out var q))
{
// the bytes it squeezed are still the sector's: they become its packed copy
if (!ReferenceEquals(q.m.raw, q.raw)) continue;
q.m.raw = null;
if (q.m.packed == null && !q.m.dirty) q.m.packed = q.packed;
}
}
static byte[] Inflate(byte[] packed)
sealed class Squeeze { public Mask m; public byte[] raw, packed; }
static readonly System.Collections.Concurrent.ConcurrentQueue<Squeeze> s_squeezed = new System.Collections.Concurrent.ConcurrentQueue<Squeeze>();
/// <summary>Puts a sector's map away: its bytes go to a worker to be squeezed, the mask lets go of its grass counts.</summary>
static void PutAway(Mask m)
{
var raw = new byte[Res * Res * 3];
if (m.dirty || (m.keep && m.packed == null && m.raw == null))
{
var job = new Squeeze { m = m, raw = Raw(m) };
m.raw = job.raw;
m.packed = null;
m.dirty = false;
System.Threading.Tasks.Task.Run(() =>
{
job.packed = Deflate(job.raw);
s_squeezed.Enqueue(job);
});
}
m.left = null;
}
/// <summary>The main thread's inflate buffer: what it holds is copied out at once.</summary>
static readonly byte[] s_inflate = new byte[Res * Res * 3];
static byte[] Inflate(byte[] packed, byte[] into = null)
{
var raw = into ?? new byte[Res * Res * 3];
using (var z = new DeflateStream(new MemoryStream(packed), CompressionMode.Decompress))
{
int at = 0, n;
@ -260,24 +366,22 @@ namespace GrassCutter
return raw;
}
static readonly List<Mask> s_trim = new List<Mask>();
/// <summary>Too many maps in memory: squeeze the ones furthest from here.</summary>
public static void Trim(Vector3 dir)
{
TakePacked();
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;
}
if (open <= MaxOpen + TrimSlack) return;
s_trim.Clear();
foreach (var m in s_masks.Values) if (m.left != null) s_trim.Add(m);
s_trim.Sort((a, b) => (b.s.c - dir).sqrMagnitude.CompareTo((a.s.c - dir).sqrMagnitude));
// 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
for (int i = 0; i < open - MaxOpen; i++) PutAway(s_trim[i]);
s_trim.Clear();
}
// ───────────────────────── cutting ─────────────────────────
@ -536,6 +640,7 @@ namespace GrassCutter
m.mown = m.total;
m.left = null;
m.packed = null;
m.raw = null;
if (s_blocks.ContainsKey(m.s.id) && m.rg != null)
{
// the rock keeps its bare patch
@ -612,6 +717,28 @@ namespace GrassCutter
}
/// <summary>The map as the shaders read it (the blank one for an untouched sector with nothing in the way).</summary>
static int s_texFrame, s_texMade;
/// <summary>
/// The map as the shaders read it. A sector coming into view far off may wait a frame or two for its texture
/// (null), so that a drive across fresh meadow doesn't unpack and upload dozens in one frame; urgent ones (near the
/// eye) always get theirs.
/// </summary>
public static Texture2D TextureFor(HexGrid.Sector s, bool urgent)
{
if (!urgent)
{
var had = Find(s.id);
if (had != null && !had.tex && !(had.done && had.rg == null))
{
if (s_texFrame != Time.frameCount) { s_texFrame = Time.frameCount; s_texMade = 0; }
if (s_texMade >= 4) return null;
s_texMade++;
}
}
return TextureFor(s);
}
public static Texture2D TextureFor(HexGrid.Sector s)
{
if (!s_none) s_none = Single(new Color32(0, 0, 0, 255));
@ -630,7 +757,8 @@ namespace GrassCutter
m.left = null;
m.show = true;
}
if (m.rg == null) Unpack(m);
// the eye only needs the look: the grass counts stay packed (an open map counts against the ones kept open)
if (m.rg == null) Look(m);
if (!m.tex)
{
// the mips are the soft edge of a cut: the grass beside it reads them to stand lower
@ -693,6 +821,11 @@ namespace GrassCutter
rows.Add((m.s.id, m.total, m.mown, false, null, job));
continue;
}
if (!m.done && m.packed == null && m.raw != null)
{
rows.Add((m.s.id, m.total, m.mown, false, null, new Packing { m = m, raw = m.raw }));
continue;
}
rows.Add((m.s.id, m.total, m.mown, m.done, m.done ? null : m.packed, null));
}
return () =>