Fix Sky Mower tumbling and the hitches on a big farm
- Mowbot keeps its heading apart from the drawn pose: a flyer's lean and sway were fed back each frame and rolled it over. - Drone pads looked through every loose bundle, testing every belt end, for each idle drone every frame (43 ms on a 1500-bundle farm): distance first, and a 1.5 s pause after finding nothing. - Saves are written, laid out and compressed off the main thread; backups go in the same queue (an autosave froze the game ~50 ms every 30 s). - Robots tick on staggered frames. - -demoperf N profiles save slot N; -demobots logs the Sky Mower's tilt. On the player's save: frames over 25 ms went from 144 to 0 in 40 s, worst frame 74 ms -> 22 ms. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -46,7 +46,7 @@ namespace GrassCutter
|
||||
yield return new WaitForSeconds(15f);
|
||||
Log($"t+{k * 15} s at {Mowbot.Haste:0}x: earned {Ts.Money.Value - money:0}, closed {Ts.Closed.Value}");
|
||||
Log($" robot: {robot.Prompt}");
|
||||
Log($" sky: {sky.Prompt} alt {Planet.Altitude(sky.ShownBody.position) - Planet.Altitude(sky.Shown):0.0} m");
|
||||
Log($" sky: {sky.Prompt} alt {Planet.Altitude(sky.ShownBody.position) - Planet.Altitude(sky.Shown):0.0} m, tilt {Vector3.Angle(sky.ShownBody.up, Planet.Up(sky.Shown)):0} deg");
|
||||
Log($" pad: {pad.Prompt}, delivered {pad.Delivered}");
|
||||
}
|
||||
skyUp = Planet.Up(sky.Shown);
|
||||
|
||||
97
Assets/Scripts/Core/DemoBot.Perf.cs
Normal file
97
Assets/Scripts/Core/DemoBot.Perf.cs
Normal file
@ -0,0 +1,97 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Unity.Profiling;
|
||||
using Unity.Profiling.LowLevel.Unsafe;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public partial class DemoBot
|
||||
{
|
||||
/// <summary>
|
||||
/// -demoperf N: load save slot N, stand at the base and record where the main thread's time goes for a while:
|
||||
/// every profiler marker (a development build has one per script Update), the slow frames and what was busy in them.
|
||||
/// Writes perf.txt beside the shots. Needs a development build for the per-script markers.
|
||||
/// </summary>
|
||||
IEnumerator Perf(int slot)
|
||||
{
|
||||
SaveSlots.Current = slot - 1;
|
||||
yield return new WaitForSeconds(2f);
|
||||
NetSession.Instance.HostLocal();
|
||||
while (!Me || !Ts) yield return null;
|
||||
yield return new WaitForSeconds(6f);
|
||||
var outp = new StringBuilder();
|
||||
outp.AppendLine($"loaded: {BuildPiece.All.Count} pieces, {Cargo.All.Count} cargo, {Mowbot.All.Count} bots, {Vehicle.All.Count} vehicles, planet r {Planet.Radius:0} m, sectors started {MowMap.Started}, finished {MowMap.Finished}");
|
||||
int bodies = 0, awake = 0;
|
||||
foreach (var rb in FindObjectsByType<Rigidbody>(FindObjectsSortMode.None)) { bodies++; if (!rb.isKinematic && !rb.IsSleeping()) awake++; }
|
||||
outp.AppendLine($"rigidbodies {bodies}, awake {awake}, renderers {FindObjectsByType<Renderer>(FindObjectsSortMode.None).Length}");
|
||||
|
||||
var home = Planet.FromBase(0f, -12f);
|
||||
Me.Teleport(Planet.OnSurface(home) + home * 0.2f);
|
||||
yield return new WaitForSeconds(1f);
|
||||
Me.LookAt(Planet.OnSurface(Planet.FromBase(0f, 0f)));
|
||||
yield return new WaitForSeconds(1f);
|
||||
|
||||
// every marker there is, recorded at once
|
||||
var handles = new List<ProfilerRecorderHandle>();
|
||||
ProfilerRecorderHandle.GetAvailable(handles);
|
||||
var recs = new List<(string name, ProfilerRecorder rec)>();
|
||||
foreach (var h in handles)
|
||||
{
|
||||
var d = ProfilerRecorderHandle.GetDescription(h);
|
||||
if (d.UnitType != ProfilerMarkerDataUnit.TimeNanoseconds) continue;
|
||||
recs.Add((d.Name, ProfilerRecorder.StartNew(d.Category, d.Name, 1)));
|
||||
}
|
||||
var loop = recs.FirstOrDefault(r => r.name == "PlayerLoop").rec;
|
||||
outp.AppendLine($"recording {recs.Count} markers, PlayerLoop {(loop.Valid ? "ok" : "MISSING")}");
|
||||
|
||||
var total = new Dictionary<string, double>();
|
||||
var spikes = new List<(int frame, double ms, string top)>();
|
||||
var frames = new List<double>();
|
||||
float until = Time.realtimeSinceStartup + 40f;
|
||||
int f = 0;
|
||||
// walk around a little, as a player would
|
||||
Ctl.BotMove = new Vector2(0.3f, 1f);
|
||||
while (Time.realtimeSinceStartup < until)
|
||||
{
|
||||
yield return null;
|
||||
f++;
|
||||
if (f % 120 == 0) Ctl.BotMove = new Vector2(-Ctl.BotMove.x, Ctl.BotMove.y);
|
||||
double frameMs = loop.Valid ? loop.LastValue / 1e6 : Time.unscaledDeltaTime * 1000.0;
|
||||
frames.Add(frameMs);
|
||||
var busy = new List<(string, double)>();
|
||||
foreach (var (name, rec) in recs)
|
||||
{
|
||||
if (!rec.Valid) continue;
|
||||
double ms = rec.LastValue / 1e6;
|
||||
if (ms <= 0 || ms > 1000) continue;
|
||||
total[name] = (total.TryGetValue(name, out var t) ? t : 0) + ms;
|
||||
if (frameMs > 25 && ms > 1 && ms < 1000 && (name.StartsWith("GC:") || name.StartsWith("Physics.Simulate") || name.StartsWith("Semaphore") || name.StartsWith("GC.") || name.StartsWith("Gfx."))) busy.Add((name, ms));
|
||||
}
|
||||
if (frameMs > 25)
|
||||
spikes.Add((f, frameMs, string.Join(", ", busy.OrderByDescending(b => b.Item2).Take(10).Select(b => $"{b.Item1} {b.Item2:0.0}"))));
|
||||
}
|
||||
Ctl.BotMove = Vector2.zero;
|
||||
foreach (var (_, rec) in recs) rec.Dispose();
|
||||
|
||||
frames.Sort();
|
||||
double Pct(double p) => frames.Count == 0 ? 0 : frames[Mathf.Clamp((int)(frames.Count * p), 0, frames.Count - 1)];
|
||||
outp.AppendLine($"{f} frames: mean {frames.Average():0.0} ms, median {Pct(0.5):0.0}, p95 {Pct(0.95):0.0}, p99 {Pct(0.99):0.0}, max {frames.LastOrDefault():0.0}; {spikes.Count} over 25 ms");
|
||||
outp.AppendLine("— mean ms a frame, top markers —");
|
||||
foreach (var kv in total.OrderByDescending(kv => kv.Value).Take(70))
|
||||
outp.AppendLine($"{kv.Value / f,8:0.000} {kv.Key}");
|
||||
outp.AppendLine("— slow frames —");
|
||||
foreach (var s in spikes.OrderByDescending(s => s.ms).Take(25))
|
||||
outp.AppendLine($"#{s.frame} {s.ms:0.0} ms: {s.top}");
|
||||
float render = 0f;
|
||||
yield return BotCapture.FrameCost(40, v => render = v);
|
||||
outp.AppendLine($"render (camera at the base, GPU waited for): {render:0.0} ms");
|
||||
File.WriteAllText(Path.Combine(folder, "perf.txt"), outp.ToString());
|
||||
Log("perf done");
|
||||
Application.Quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/DemoBot.Perf.cs.meta
Normal file
2
Assets/Scripts/Core/DemoBot.Perf.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 688dd65c0fcdde24ab5d52f06b08ff75
|
||||
@ -3003,6 +3003,11 @@ namespace GrassCutter
|
||||
yield return Sizes();
|
||||
yield break;
|
||||
}
|
||||
if (CommandLine.Get("-demoperf") is string perfSlot)
|
||||
{
|
||||
yield return Perf(int.Parse(perfSlot));
|
||||
yield break;
|
||||
}
|
||||
if (CommandLine.Has("-demobots"))
|
||||
{
|
||||
yield return Bots();
|
||||
|
||||
@ -99,14 +99,41 @@ namespace GrassCutter
|
||||
|
||||
// ───────────────────────── writing ─────────────────────────
|
||||
|
||||
public static void Write(string json, byte[] map)
|
||||
// the disk work of a save runs off the main thread, one write after another: a big farm's mow map is over ten
|
||||
// megabytes, and writing it in the frame froze the game every half minute
|
||||
static System.Threading.Tasks.Task s_io = System.Threading.Tasks.Task.CompletedTask;
|
||||
static readonly object s_ioGate = new object();
|
||||
|
||||
public static void Write(string json, byte[] map) => Write(() => json, () => map);
|
||||
|
||||
/// <summary>The save, its text and its map put together off the main thread (JsonUtility works on any thread).</summary>
|
||||
public static void Write(Func<string> json, Func<byte[]> map)
|
||||
{
|
||||
var dir = Folder(Current);
|
||||
Directory.CreateDirectory(dir);
|
||||
Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json));
|
||||
Put(Path.Combine(dir, MapFile), map);
|
||||
lock (s_ioGate)
|
||||
s_io = s_io.ContinueWith(_ =>
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json()));
|
||||
Put(Path.Combine(dir, MapFile), map());
|
||||
}
|
||||
catch (Exception e) { Debug.LogWarning("[Save] couldn't write " + dir + ": " + e.Message); }
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Waits for a save still being written: before anything reads, copies or deletes the files, and on quitting.</summary>
|
||||
public static void Flush()
|
||||
{
|
||||
System.Threading.Tasks.Task t;
|
||||
lock (s_ioGate) t = s_io;
|
||||
try { t.Wait(); } catch (AggregateException e) { Debug.LogWarning("[Save] " + e.InnerException?.Message); }
|
||||
}
|
||||
|
||||
[RuntimeInitializeOnLoadMethod]
|
||||
static void FlushOnQuit() => Application.quitting += Flush;
|
||||
|
||||
/// <summary>Written whole or not at all: a crash halfway leaves the last save as it was.</summary>
|
||||
static void Put(string path, byte[] data)
|
||||
{
|
||||
@ -119,18 +146,31 @@ namespace GrassCutter
|
||||
/// <summary>The current save goes over the oldest of its backups.</summary>
|
||||
public static void Backup()
|
||||
{
|
||||
// in the same queue as the writes, after the save just asked for: the copy is of that save, and nothing waits
|
||||
var dir = Folder(Current);
|
||||
var copies = new string[Backups];
|
||||
for (int n = 0; n < Backups; n++) copies[n] = Copy(Current, n);
|
||||
lock (s_ioGate)
|
||||
s_io = s_io.ContinueWith(_ =>
|
||||
{
|
||||
try { CopyToBackup(dir, copies); }
|
||||
catch (Exception e) { Debug.LogWarning("[Save] couldn't back up " + dir + ": " + e.Message); }
|
||||
});
|
||||
}
|
||||
|
||||
static void CopyToBackup(string dir, string[] copies)
|
||||
{
|
||||
var game = Path.Combine(dir, GameFile);
|
||||
if (!File.Exists(game)) return;
|
||||
int pick = 0;
|
||||
var oldest = DateTime.MaxValue;
|
||||
for (int n = 0; n < Backups; n++)
|
||||
for (int n = 0; n < copies.Length; n++)
|
||||
{
|
||||
var path = Path.Combine(Copy(Current, n), GameFile);
|
||||
var path = Path.Combine(copies[n], GameFile);
|
||||
var when = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
|
||||
if (when < oldest) { oldest = when; pick = n; }
|
||||
}
|
||||
var to = Copy(Current, pick);
|
||||
var to = copies[pick];
|
||||
Directory.CreateDirectory(to);
|
||||
File.Copy(game, Path.Combine(to, GameFile), true);
|
||||
File.SetLastWriteTimeUtc(Path.Combine(to, GameFile), DateTime.UtcNow);
|
||||
@ -170,6 +210,7 @@ namespace GrassCutter
|
||||
/// <summary>The save to load, or null for a new game. A bad one is replaced from its backups first.</summary>
|
||||
public static string Read()
|
||||
{
|
||||
Flush();
|
||||
Migrate();
|
||||
var dir = Folder(Current);
|
||||
var json = Text(Path.Combine(dir, GameFile));
|
||||
@ -194,6 +235,7 @@ namespace GrassCutter
|
||||
|
||||
public static SlotInfo Info(int slot)
|
||||
{
|
||||
Flush();
|
||||
var path = Path.Combine(Folder(slot), GameFile);
|
||||
var h = Parse(Text(path));
|
||||
if (h == null) return new SlotInfo { used = File.Exists(path) };
|
||||
@ -202,6 +244,7 @@ namespace GrassCutter
|
||||
|
||||
public static void Delete(int slot)
|
||||
{
|
||||
Flush();
|
||||
if (Directory.Exists(Folder(slot))) Directory.Delete(Folder(slot), true);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user