Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

feat(diag): ?turnlog End turn probe and first WebGL split (Refs #2905) (#2957)

Eyal Golanc6979e79e2d0
diff --git a/changelog.d/2905-turnlog.md b/changelog.d/2905-turnlog.md
new file mode 100644
index 000000000..60cac15a5
--- /dev/null
+++ b/changelog.d/2905-turnlog.md
@@ -0,0 +1,4 @@
+- A diagnostic End turn probe, off unless asked for: `?turnlog` in the WebGL page address (or `-turnlog` on desktop)
+ writes one `TURNLOG` console line per End turn with the sim step's time, each event handler's time and the map
+ layers' times, so the freeze at End turn can be measured in a real browser (Refs #2905). It changes nothing in the
+ game.
diff --git a/docs/dev-setup.md b/docs/dev-setup.md
index f6329d54b..6ed451581 100644
--- a/docs/dev-setup.md
+++ b/docs/dev-setup.md
@@ -60,10 +60,12 @@ Not possible without Unity and not in CI: the Unity EditMode tests, player build
on this Mac; `npx playwright install chromium` puts it there). `find_chrome()` looks nowhere else, so on any other
platform set `CHROME_PATH` to a Chrome for Testing executable (`tools/web_check.py`).
- Page flags: `?golden` (golden check), `?smoke=N` (play N turns through the UI; bare `?smoke` = 5, `?smoke=0` = off),
- `?profile` (terrain profile), `?camlog` (log the camera distance), `?bootlog` (each boot phase's timing) and `?navlog`
- (every UI pointer and submit event, screen toggle and map click, with its frame), `?vprofile` (the visual frame-time
- profile per feature), `?shot` (screenshots at the promo poses as `SHOT` console lines) and `?kitscale=N`, `?housescale=N`, `?treescale=N` (the settlement kits' symbolic scale for city blocks, houses and trees, clamped to 5–200; defaults 60, 100, 100), `?noarmisticelines` (turns off the 1949 armistice lines drawn as true polylines over the hex bands, which are on by default, #237 and #196; a release build draws and ships only the signed-off features). In the editor, `MapCapture.Kits` takes `-kitScale`, `-houseScale` and `-treeScale`. Desktop players take `-golden`,
- `-smoke N`, `-profile`, `-camlog`, `-bootlog`, `-navlog`, `-vprofile`, `-shot` and `-noarmisticelines`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.
+ `?profile` (terrain profile), `?camlog` (log the camera distance), `?bootlog` (each boot phase's timing), `?navlog`
+ (every UI pointer and submit event, screen toggle and map click, with its frame), `?turnlog` (one line per End turn,
+ `TURNLOG v=1 turn=N date=yyyy-MM-dd total_ms=X step_ms=X handlers=N Event/Handler=X ... @Section=X ...`: the sim
+ step's milliseconds, each handler's of `Changed`, `CombatResolved` and `TurnEnded`, timed only during End turn, and
+ each map layer's section; `TurnProbe`, #2905), `?vprofile` (the visual frame-time profile per feature), `?shot` (screenshots at the promo poses as `SHOT` console lines) and `?kitscale=N`, `?housescale=N`, `?treescale=N` (the settlement kits' symbolic scale for city blocks, houses and trees, clamped to 5–200; defaults 60, 100, 100), `?noarmisticelines` (turns off the 1949 armistice lines drawn as true polylines over the hex bands, which are on by default, #237 and #196; a release build draws and ships only the signed-off features). In the editor, `MapCapture.Kits` takes `-kitScale`, `-houseScale` and `-treeScale`. Desktop players take `-golden`,
+ `-smoke N`, `-profile`, `-camlog`, `-bootlog`, `-navlog`, `-turnlog`, `-vprofile`, `-shot` and `-noarmisticelines`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.
- First card in normal mode (#909): `?firstcard` keeps the start screen and decision video on, presses New Game at once
and logs `FIRST CARD OK event=<id> media=<photo|portrait fallback> wait=<ms> ms budget=<ms> ms`, or `FIRST CARD FAIL`
after the budget (10 s, proposed). Run it with `uv run tools/machine_lock.py --shared -- uv run tools/web_check.py <build>
diff --git a/unity/Assets/Scripts/Boot/DiagLog.cs b/unity/Assets/Scripts/Boot/DiagLog.cs
index 3b3721ea0..c670e79e6 100644
--- a/unity/Assets/Scripts/Boot/DiagLog.cs
+++ b/unity/Assets/Scripts/Boot/DiagLog.cs
@@ -8,7 +8,8 @@ namespace Statecraft.Game.Boot
/// <summary>Diagnostic console lines, off unless asked for: "?bootlog" (WebGL page URL) or -bootlog (desktop) logs each
/// boot phase with its time since the player started and since the previous phase ("BOOT phase=… at=… ms dt=… ms");
/// "?navlog" / -navlog logs every UI pointer and submit event, every screen toggle and every map click with the frame
- /// it happened in ("NAV f=… …"). Playtest 2, P2-1 and P2-4.</summary>
+ /// it happened in ("NAV f=… …"). Playtest 2, P2-1 and P2-4. "?turnlog" / -turnlog times each End turn's sim step and
+ /// handlers, one "TURNLOG …" line a turn (TurnProbe, #2905).</summary>
public static class DiagLog
{
public static bool Boot { get; set; }
@@ -19,13 +20,14 @@ namespace Statecraft.Game.Boot
public static bool Requested(string flag, string? url, string[] args, bool webgl) =>
webgl ? UrlFlags.Has(url, flag) : args.Contains("-" + flag);
- /// <summary>Reads both flags from this player's URL or command line.</summary>
+ /// <summary>Reads the flags from this player's URL or command line.</summary>
public static void Init()
{
var webgl = Application.platform == RuntimePlatform.WebGLPlayer;
var url = Application.absoluteURL; var args = Environment.GetCommandLineArgs();
Boot = Requested("bootlog", url, args, webgl);
Nav = Requested("navlog", url, args, webgl);
+ TurnProbe.On = Requested(TurnProbe.Flag, url, args, webgl);
}
static double last = -1;
diff --git a/unity/Assets/Scripts/Boot/TurnProbe.cs b/unity/Assets/Scripts/Boot/TurnProbe.cs
new file mode 100644
index 000000000..fa02df991
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/TurnProbe.cs
@@ -0,0 +1,142 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Statecraft.Game.Boot
+{
+ /// <summary>Issue #2905: where an End turn's main-thread time goes, off unless asked for: "?turnlog" (WebGL page URL) or
+ /// -turnlog (desktop), read by <see cref="DiagLog.Init"/>. While on, SimBridge.EndTurn opens a turn (<see cref="BeginTurn"/>),
+ /// times the sim step, every handler of its Changed, CombatResolved and TurnEnded events (<see cref="Handler"/>) and the
+ /// sections the map layers mark (<see cref="Lap"/>), then writes one console line (<see cref="EndTurn"/>):
+ /// <code>TURNLOG v=1 turn=N date=yyyy-MM-dd total_ms=X step_ms=X handlers=N Event/Name=X ... @Section=X ...</code>
+ /// Every field after "TURNLOG" is key=value with no spaces; times are milliseconds with two decimals (invariant culture).
+ /// A handler key is its event and <see cref="HandlerName"/> (a second handler of the same name gets "#2", and so on), in
+ /// the order the handlers ran; a section key is "@" and its name, its time summed over the turn, in the order first seen.
+ /// Presentation only: it never changes what runs or in what order, and with the flag off every hook is one static bool
+ /// read (no Stopwatch read, no allocation).</summary>
+ public static class TurnProbe
+ {
+ public const string Flag = "turnlog", Prefix = "TURNLOG", Version = "1";
+
+ /// <summary>Asked for (?turnlog / -turnlog). Set by DiagLog.Init, or by a test.</summary>
+ public static bool On { get; set; }
+
+ /// <summary>Between <see cref="BeginTurn"/> and <see cref="EndTurn"/> of a probed turn: only then is anything timed.</summary>
+ public static bool Active { get; private set; }
+
+ /// <summary>The last line written (null before the first probed turn).</summary>
+ public static string? Last { get; private set; }
+
+ static List<(string key, double ms)>? handlers;
+ static List<(string key, double ms)>? sections;
+ static long turnStart;
+ static double stepMs;
+ static int turn;
+ static DateTime date;
+
+ /// <summary>Opens a probed turn when <see cref="On"/>; otherwise does nothing.</summary>
+ public static void BeginTurn(int turnNumber, DateTime turnDate)
+ {
+ if (!On) return;
+ handlers ??= new List<(string, double)>(); sections ??= new List<(string, double)>();
+ handlers.Clear(); sections.Clear();
+ turn = turnNumber; date = turnDate; stepMs = 0;
+ Active = true;
+ turnStart = Stopwatch.GetTimestamp();
+ }
+
+ /// <summary>A timestamp to time from, or 0 when no turn is probed (no clock read).</summary>
+ public static long Start() => Active ? Stopwatch.GetTimestamp() : 0;
+
+ /// <summary>Adds the time since <paramref name="from"/> to section <paramref name="name"/> and returns now, the start of
+ /// the next lap. Returns 0 at once when no turn is probed.</summary>
+ public static long Lap(string name, long from)
+ {
+ if (!Active) return 0;
+ var now = Stopwatch.GetTimestamp();
+ var ms = Ms(from, now);
+ for (int i = 0; i < sections!.Count; i++)
+ if (sections[i].key == name) { sections[i] = (name, sections[i].ms + ms); return now; }
+ sections.Add((name, ms));
+ return now;
+ }
+
+ /// <summary>The sim step's time (SimBridge.EndTurn's step call).</summary>
+ public static void Step(long from)
+ {
+ if (!Active) return;
+ stepMs += Ms(from, Stopwatch.GetTimestamp());
+ }
+
+ /// <summary>One handler of <paramref name="evt"/> ran from <paramref name="from"/> until now.</summary>
+ public static void Handler(string evt, Delegate handler, long from)
+ {
+ if (!Active) return;
+ var ms = Ms(from, Stopwatch.GetTimestamp());
+ var key = evt + "/" + HandlerName(handler);
+ int same = 1;
+ foreach (var (k, _) in handlers!) if (k == key || k.StartsWith(key + "#", StringComparison.Ordinal)) same++;
+ handlers.Add((same == 1 ? key : key + "#" + same.ToString(CultureInfo.InvariantCulture), ms));
+ }
+
+ /// <summary>Closes the probed turn and writes its line through <paramref name="log"/> (the console in the game).
+ /// Returns the line, or null when no turn was probed.</summary>
+ public static string? EndTurn(Action<string> log)
+ {
+ if (!Active) return null;
+ var total = Ms(turnStart, Stopwatch.GetTimestamp());
+ Active = false;
+ Last = Line(turn, date, total, stepMs, handlers!, sections!);
+ log(Last);
+ return Last;
+ }
+
+ /// <summary>The line's format (see the class summary).</summary>
+ public static string Line(int turnNumber, DateTime turnDate, double totalMs, double simMs,
+ IReadOnlyList<(string key, double ms)> handlerTimes, IReadOnlyList<(string key, double ms)> sectionTimes)
+ {
+ var b = new StringBuilder(Prefix);
+ b.Append(" v=").Append(Version);
+ b.Append(" turn=").Append(turnNumber.ToString(CultureInfo.InvariantCulture));
+ b.Append(" date=").Append(turnDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
+ b.Append(" total_ms=").Append(F(totalMs));
+ b.Append(" step_ms=").Append(F(simMs));
+ b.Append(" handlers=").Append(handlerTimes.Count.ToString(CultureInfo.InvariantCulture));
+ foreach (var (k, ms) in handlerTimes) b.Append(' ').Append(Key(k)).Append('=').Append(F(ms));
+ foreach (var (k, ms) in sectionTimes) b.Append(" @").Append(Key(k)).Append('=').Append(F(ms));
+ return b.ToString();
+ }
+
+ /// <summary>Made on the first probed handler only, so the flag off allocates nothing, not even at start-up.</summary>
+ static class Names
+ {
+ internal static readonly Regex LocalFunction = new Regex(@"^<([^>]*)>g__([^|]+)\|", RegexOptions.CultureInvariant);
+ internal static readonly Regex Lambda = new Regex(@"^<([^>]*)>b__", RegexOptions.CultureInvariant);
+ }
+
+ /// <summary>A handler's readable name: its class (the outermost class a compiler-made one sits in) and its method; a
+ /// lambda is "Class.Method.lambda" after the method that made it, a local function "Class.Method.Local". The
+ /// compiler's numbering is dropped, so the name stays the same when the code around it changes.</summary>
+ public static string HandlerName(Delegate handler)
+ {
+ var m = handler.Method;
+ var type = m.DeclaringType;
+ while (type != null && type.DeclaringType != null && type.Name.StartsWith("<", StringComparison.Ordinal)) type = type.DeclaringType;
+ var owner = type?.Name ?? "?";
+ var name = m.Name;
+ var local = Names.LocalFunction.Match(name);
+ if (local.Success) return owner + "." + local.Groups[1].Value + "." + local.Groups[2].Value;
+ var lambda = Names.Lambda.Match(name);
+ if (lambda.Success) return owner + "." + lambda.Groups[1].Value + ".lambda";
+ return owner + "." + name;
+ }
+
+ static string Key(string k) => k.Replace(' ', '_').Replace('=', '_');
+ static string F(double ms) => ms.ToString("0.00", CultureInfo.InvariantCulture);
+ static double Ms(long from, long to) => (to - from) * 1000.0 / Stopwatch.Frequency;
+ }
+}
diff --git a/unity/Assets/Scripts/Boot/TurnProbe.cs.meta b/unity/Assets/Scripts/Boot/TurnProbe.cs.meta
new file mode 100644
index 000000000..7b91b1ab1
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/TurnProbe.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 05b03cc7f15541fa8053dd20dc51d847
diff --git a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs
index d8fed1baf..87b3940bd 100644
--- a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs
+++ b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs
@@ -610,8 +610,10 @@ namespace Statecraft.Game.Map.Collection
void Show(IReadOnlyList<Want> wants)
{
this.wants = wants;
+ var probe = Boot.TurnProbe.Start(); // ?turnlog (#2905): the replan and the residency apart
Replan(log: true);
- if (residencyView != null) { RefreshResidency(); return; }
+ probe = Boot.TurnProbe.Lap("SpecialBuildingModels.Replan", probe);
+ if (residencyView != null) { RefreshResidency(); Boot.TurnProbe.Lap("SpecialBuildingModels.Residency", probe); return; }
foreach (var w in wants)
if (asked.Add(w.Model)) { string model = w.Model; Request(model, CollectionDetail.Near, p => { if (this == null) return; prefabs[model] = p; if (p == null) { FailedOpen = true; Debug.LogWarning($"BUILDINGS: {model} did not stream; it stays off the map."); } Rebuild(); }); }
Rebuild();
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
index ee6db9cf5..c9a6eb857 100644
--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
@@ -437,7 +437,9 @@ namespace Statecraft.Game.Map.Units
roster = now;
PlaceMoved(now);
placed = UnitPlacer.Place(now, drawSpots ?? DisplaySpots);
+ var probe = Boot.TurnProbe.Start(); // ?turnlog (#2905): the token rebuild alone
Rebuild(slide);
+ Boot.TurnProbe.Lap("UnitLayer.Rebuild", probe);
ScheduleSatisfiedPrefetchRetirement();
if (Selected != null && !placed.Any(p => p.Token.Unit.Id == Selected)) Select(null); else Select(Selected);
seenAvailability = UnitFigures.AvailabilityVersion;
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 9161c7225..dd9783827 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -454,6 +454,7 @@ namespace Statecraft.Game.UI
var layerLabel = root.Q<Label>("map-layer");
Action onDate = () =>
{
+ var probe = TurnProbe.Start(); // ?turnlog (#2905)
var live = bridge.State.Settlements.OrderBy(kv => kv.Key, StringComparer.Ordinal)
.Join(bridge.Content.SettlementHexes, kv => kv.Key, h => h.Id,
(kv, h) => (h.Q, h.R, player: SettlementControlView.PlayerHolds(kv.Value)))
@@ -462,6 +463,7 @@ namespace Statecraft.Game.UI
layerLabel.text = regions.ControlLabel(bridge.State.Date, k => text[k])
?? regions.Label(bridge.State.Date, text.Format, text["ui.lang"] == UiLanguage.Hebrew);
ShowLayerLabel();
+ TurnProbe.Lap("GameRoot.regions", probe);
};
// The caption names the borders while they are drawn: by date, and not while the minimap's button hides them.
void ShowLayerLabel() => layerLabel.style.display = regions.Shown && minimap?.BordersShown != false ? DisplayStyle.Flex : DisplayStyle.None;
@@ -491,12 +493,15 @@ namespace Statecraft.Game.UI
Action showUnits = () =>
{
// New Game replaces the session, and its sim ids are the old game's: its tokens are drawn where they stand.
+ var probe = TurnProbe.Start(); // ?turnlog (#2905)
unitLayer.Show(bridge.Content, bridge.State, slide: ReferenceEquals(shownSession, bridge.Session));
+ probe = TurnProbe.Lap("UnitLayer.Show", probe);
shownSession = bridge.Session;
unitLayer.Dim(unitLayer.Tokens.Where(t => t.Token.Unit.Side == Statecraft.Game.Map.Units.UnitData.Israel)
.Where(t => UnitCard.SimUnit(bridge.Content, bridge.State, t.Token) is int id
&& Movement.ActionsLeft(bridge.Content, bridge.State, id, bridge.Spent) == 0)
.Select(t => t.Token.Unit.Id).ToList());
+ TurnProbe.Lap("GameRoot.unitsDim", probe);
};
bridge.Changed += showUnits;
owned.Add(new Undo(() => bridge.Changed -= showUnits));
@@ -1168,46 +1173,61 @@ namespace Statecraft.Game.UI
void RenderPlacementsIfChanged()
{
if (Bridge == null) return;
+ // ?turnlog (#2905): each layer's time during End turn, as one "@Layer" section each; otherwise no clock is read.
+ var probe = TurnProbe.Start();
// Dated routes (the Burma Road from June 1948); in the GDD loop the corridors by their built segments (#792).
Statecraft.Game.Map.Routes.RouteLayer.ShowAt(map, Bridge.State.Date,
Bridge.Content.IsGdd ? Statecraft.Game.Map.Routes.RouteLayer.BuiltSegments(Bridge.Content, Bridge.State) : null);
+ probe = TurnProbe.Lap("RouteLayer", probe);
// The true armistice lines (#237; on unless "noarmisticelines" turns them off, #196), each from its own date.
ArmisticeLines.ShowAt(map, Bridge.State.Date);
+ probe = TurnProbe.Lap("ArmisticeLines", probe);
// Tal Heuberger's whole-town models on their towns far off (#663, "Whole model far, buildings near"), streamed after the first frame; the ma'abara from its date.
// The camps and housing built as city projects bring theirs too, as the placement layer draws them (#1275).
Statecraft.Game.Map.Collection.TownLandmarks.ShowAt(map, Bridge.State.Date,
PlacementLayer.Drawn(Bridge.State.Placements, Bridge.State.CityProjects.Values), Bridge.Content);
+ probe = TurnProbe.Lap("TownLandmarks", probe);
// Tal Heuberger's ibex and striped hyena, sparse in their sourced terrain zones and visible only at close zoom (#670).
Statecraft.Game.Map.Collection.WildlifeLayer.Show(map);
+ probe = TurnProbe.Lap("WildlifeLayer", probe);
// Tal Heuberger's papyrus at the Hula swamp's sourced site, close up only, streamed on the first close view, gone
// once the swamp is drained (#2082; owner, 2 November 2026: "Hula + Arava, map and boards").
Statecraft.Game.Map.Collection.HulaPapyrusLayer.ShowAt(map, Bridge.Content,
Statecraft.Game.Map.Collection.HulaPapyrusLayer.Drained(Bridge.State));
+ probe = TurnProbe.Lap("HulaPapyrusLayer", probe);
// A plowed field's or drained swamp's ground on its hex (#2877): from the sites, so a loaded save shows its own.
SiteGroundLayer.ShowAt(map, Bridge.Content, Bridge.State.Sites.Values);
+ probe = TurnProbe.Lap("SiteGroundLayer", probe);
// Tal Heuberger's civilian figures at towns, villages, transit camps and building sites, ambience only and streamed
// after the first frame (#666, #708, #886): the residents follow the settlement state, the builders the projects.
Statecraft.Game.Map.Collection.CivilianPeople.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content,
Bridge.State.Settlements, Bridge.State.CityProjects.Values);
+ probe = TurnProbe.Lap("CivilianPeople", probe);
// Tal Heuberger's period-generic farm and village scenery, streamed after the first frame (#667); never game units.
Statecraft.Game.Map.Collection.RuralLife.Show(map);
+ probe = TurnProbe.Lap("RuralLife", probe);
// Tal Heuberger's Tegart fort, barracks and factory at their sourced places and dates, close up only, streamed (#707);
// under gdd-0.3 their artisan workshop (b21) on each built arms workshop's hex (#1701 slice F).
var workshops = Statecraft.Game.Map.Collection.SpecialBuildingModels.ArmsWorkshops(Bridge.Content, Bridge.State.CityProjects.Values);
special = Statecraft.Game.Map.Collection.SpecialBuildingModels.ShowAt(map, Bridge.State.Date, workshops);
+ probe = TurnProbe.Lap("SpecialBuildingModels", probe);
// Tal Heuberger's hex-tile props (owner, 27 October 2026: "2+3"; 2 November 2026: "Every zoom" for the landmarks): their
// minarets, belfries and Jaffa's clock tower in place of the kit's at every zoom, so the bundle streams after the first
// frame; the stations, camp tents, village hedges and hill scatter close up only, built at the first close camera.
// After the layers they keep clear of (the built arms workshops' b21 too, #1701 slice F).
Statecraft.Game.Map.Collection.HexPropModels.ShowAt(map, Bridge.State.Date, workshops);
+ probe = TurnProbe.Lap("HexPropModels", probe);
// Tal Heuberger's ships off Haifa, Jaffa, Acre and (on the Altalena's turn) Tel Aviv, and the C-54 at Lod, streamed after the first frame (#669).
seaAir = Statecraft.Game.Map.Collection.SeaAirCollection.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content);
+ probe = TurnProbe.Lap("SeaAirCollection", probe);
RenderSitesIfChanged();
+ probe = TurnProbe.Lap("Sites", probe);
var shown = PlacementLayer.Drawn(Bridge.State.Placements, Bridge.State.CityProjects.Values);
var now = shown.Select(p => (p.Action, p.Q, p.R, p.Date)).ToList();
- if (drawn != null && drawn.SequenceEqual(now)) return;
+ if (drawn != null && drawn.SequenceEqual(now)) { TurnProbe.Lap("Placements", probe); return; }
drawn = now;
placements.Render(shown, Bridge.Content, map);
+ TurnProbe.Lap("Placements", probe);
}
/// <summary>Draws the designated sites (#381) only when a site's state differs from what was drawn: being built, or
diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.cs
index 33ec690be..c9314448f 100644
--- a/unity/Assets/Scripts/UI/SimBridge.cs
+++ b/unity/Assets/Scripts/UI/SimBridge.cs
@@ -83,8 +83,8 @@ namespace Statecraft.Game.UI
public void SeeEndingCard(string id)
{
if (!State.PendingEvents.Contains(id) || !IsEndingCard(id) || !endingCardsSeen.Add(id)) return;
- Notify(Changed);
- if (!EndingCardWaiting) Notify(EndingCardsSeen);
+ Notify(Changed, nameof(Changed));
+ if (!EndingCardWaiting) Notify(EndingCardsSeen, nameof(EndingCardsSeen));
}
readonly UiText text;
@@ -171,7 +171,7 @@ namespace Statecraft.Game.UI
};
/// <summary>Skips the unit for this turn: not an order, not saved, nothing in the game changes (spec 7.2).</summary>
- public void Skip(int unit) { if (skipped.Add(unit)) Notify(Changed); }
+ public void Skip(int unit) { if (skipped.Add(unit)) Notify(Changed, nameof(Changed)); }
public bool IsSkipped(int unit) => skipped.Contains(unit);
/// <summary>Null if the id is known, else the player-facing reason. The player sees only the kind of thing (#622: a
@@ -449,20 +449,29 @@ namespace Statecraft.Game.UI
static IReadOnlyList<Cause> Engagements(IEnumerable<Cause> why) => why.Where(x => x.Key == WhyKeys.Engagement || x.Key == WhyKeys.Destroyed).ToList();
- static void Notify(Action? handlers)
+ // Under ?turnlog, during End turn, each handler is timed (TurnProbe, #2905); otherwise Start is 0 and Handler returns.
+ static void Notify(Action? handlers, string evt)
{
if (handlers == null) return;
foreach (Action handler in handlers.GetInvocationList())
+ {
+ var t = Boot.TurnProbe.Start();
try { handler(); }
catch (Exception e) { UnityEngine.Debug.LogException(e); }
+ Boot.TurnProbe.Handler(evt, handler, t);
+ }
}
- static void Notify<T>(Action<T>? handlers, T value)
+ static void Notify<T>(Action<T>? handlers, T value, string evt)
{
if (handlers == null) return;
foreach (Action<T> handler in handlers.GetInvocationList())
+ {
+ var t = Boot.TurnProbe.Start();
try { handler(value); }
catch (Exception e) { UnityEngine.Debug.LogException(e); }
+ Boot.TurnProbe.Handler(evt, handler, t);
+ }
}
/// <summary>Queues an order (replacing one with the same key). Returns null, or why it was refused here: an id
@@ -481,16 +490,16 @@ namespace Statecraft.Game.UI
var refused = Session.Commit(c);
if (refused != null) return Refuse(refused);
WithdrawUnmetOperations();
- Notify(Changed);
+ Notify(Changed, nameof(Changed));
var added = Session.Now.Why.Skip(before).ToList();
- Notify(Committed, added);
- Notify(CombatResolved, Engagements(added));
+ Notify(Committed, added, nameof(Committed));
+ Notify(CombatResolved, Engagements(added), nameof(CombatResolved));
return null;
}
if (c is AllocateBudget ab) c = new AllocateBudget(new Dictionary<string, double>(ab.Shares)); // a snapshot: later edits to the caller's dictionary must not change the order
if (Content.UsesAttention && !CanPay(c))
{
- Notify(RefusedForAttention); // presentation only: a failing listener never changes the refusal
+ Notify(RefusedForAttention, nameof(RefusedForAttention)); // presentation only: a failing listener never changes the refusal
return Refuse(text.Format("order.no_attention", Price(c)!.Value, LeftFor(c)));
}
// Send home takes the unit's place in the queue: an order queued for it earlier (a reinforcement) is withdrawn, and
@@ -499,7 +508,7 @@ namespace Statecraft.Game.UI
if (IsSendHome(c)) deferred.RemoveAll(x => UnitOf(x) == UnitOf(c) && Key(x) != Key(c));
var old = QueuedLike(c);
if (old != null) deferred[deferred.IndexOf(old)] = c; else deferred.Add(c);
- Notify(Changed);
+ Notify(Changed, nameof(Changed));
return null;
}
@@ -519,7 +528,7 @@ namespace Statecraft.Game.UI
public void Withdraw(Command c)
{
- if (deferred.Remove(c)) Notify(Changed);
+ if (deferred.Remove(c)) Notify(Changed, nameof(Changed));
}
/// <summary>Runs the turn with the committed then deferred orders, clears the deferred queue, and notifies. If the
@@ -533,6 +542,8 @@ namespace Statecraft.Game.UI
int replayed = Session.Now.Why.Count;
var batch = Session.Committed.Concat(deferred).ToList();
var date = TurnStart.Date;
+ Boot.TurnProbe.BeginTurn(TurnStart.Turn, date); // ?turnlog (#2905): this call's sim step and handlers, one line
+ var stepFrom = Boot.TurnProbe.Start();
try { r = step(Session, deferred.ToList()); } // a snapshot: the queue is cleared below
catch (Exception e) // any exception (M3 final review M7): never leave a queue that fails on every End Turn
{
@@ -543,16 +554,19 @@ namespace Statecraft.Game.UI
LastBatch = Array.Empty<Command>(); LastBatchDate = default(DateTime);
var reason = text["order.failed"]; // the message stays in the log above, not on screen (#622)
var failed = new StepResult(State, new Cause[0], batch.Select(x => new Rejection(x, reason)).ToList());
- Notify(Changed);
- Notify(TurnEnded, failed.Rejected);
+ Notify(Changed, nameof(Changed));
+ Notify(TurnEnded, failed.Rejected, nameof(TurnEnded));
+ Boot.TurnProbe.EndTurn(UnityEngine.Debug.Log);
return failed;
}
+ Boot.TurnProbe.Step(stepFrom);
LastBatch = batch; LastBatchDate = date;
deferred.Clear(); skipped.Clear();
- Notify(Stepped, r);
- Notify(Changed);
- Notify(CombatResolved, Engagements(r.Why.Skip(replayed)));
- Notify(TurnEnded, r.Rejected);
+ Notify(Stepped, r, nameof(Stepped));
+ Notify(Changed, nameof(Changed));
+ Notify(CombatResolved, Engagements(r.Why.Skip(replayed)), nameof(CombatResolved));
+ Notify(TurnEnded, r.Rejected, nameof(TurnEnded));
+ Boot.TurnProbe.EndTurn(UnityEngine.Debug.Log);
return r;
}
@@ -562,7 +576,7 @@ namespace Statecraft.Game.UI
Session = session ?? throw new ArgumentNullException(nameof(session));
LastBatch = Array.Empty<Command>(); LastBatchDate = default(DateTime);
deferred.Clear(); skipped.Clear(); endingCardsSeen.Clear();
- Notify(Changed);
+ Notify(Changed, nameof(Changed));
}
}
}
diff --git a/unity/Assets/Tests/EditMode/TurnProbeTests.cs b/unity/Assets/Tests/EditMode/TurnProbeTests.cs
new file mode 100644
index 000000000..50def2bdf
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TurnProbeTests.cs
@@ -0,0 +1,223 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Text.RegularExpressions;
+using System.Threading;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Game.Map;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.TestTools.Constraints;
+using Is = UnityEngine.TestTools.Constraints.Is;
+using Object = UnityEngine.Object;
+
+/// <summary>#2905's End turn probe (?turnlog, TurnProbe): off, it records and writes nothing and allocates nothing; on, every
+/// handler of SimBridge.EndTurn's events gets a time on one line of a fixed format, and the game runs as it does off.</summary>
+public class TurnProbeTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static SimBridge NewBridge() => new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
+
+ // The whole line: TURNLOG v=1 turn=N date=yyyy-MM-dd total_ms=X step_ms=X handlers=N, then key=X fields.
+ static readonly Regex LineFormat = new Regex(
+ @"^TURNLOG v=1 turn=\d+ date=\d{4}-\d{2}-\d{2} total_ms=\d+\.\d{2} step_ms=\d+\.\d{2} handlers=\d+( @?[^\s=]+=\d+\.\d{2})*$");
+
+ readonly List<string> logged = new List<string>();
+ void Capture(string message, string stack, LogType type) { if (message.StartsWith(TurnProbe.Prefix, StringComparison.Ordinal)) logged.Add(message); }
+ bool wasOn;
+
+ // TurnProbe is static: each test starts and ends with no open turn, so one failed test (an assert between BeginTurn
+ // and EndTurn) cannot leave Active set and fail the next ones. Closing it through EndTurn with a no-op log logs nothing.
+ static void CloseOpenTurn() => TurnProbe.EndTurn(_ => { });
+
+ [SetUp] public void Listen() { wasOn = TurnProbe.On; CloseOpenTurn(); logged.Clear(); Application.logMessageReceived += Capture; }
+ [TearDown] public void Stop() { Application.logMessageReceived -= Capture; CloseOpenTurn(); TurnProbe.On = wasOn; }
+
+ static Dictionary<string, string> Fields(string line) =>
+ line.Split(' ').Skip(1).Select(f => f.Split('=')).ToDictionary(kv => kv[0], kv => kv[1]);
+
+ void Named() { }
+
+ [Test]
+ public void Off_it_records_and_writes_nothing()
+ {
+ TurnProbe.On = false;
+ var bridge = NewBridge();
+ int ran = 0;
+ bridge.Changed += () => ran++;
+ bridge.TurnEnded += _ => ran++;
+ var before = TurnProbe.Last;
+ bridge.EndTurn();
+ Assert.AreEqual(2, ran, "the handlers ran");
+ Assert.IsEmpty(logged, "no TURNLOG line");
+ Assert.AreSame(before, TurnProbe.Last, "no line made");
+ Assert.IsFalse(TurnProbe.Active);
+ Assert.AreEqual(0, TurnProbe.Start(), "no clock read");
+ Assert.AreEqual(0, TurnProbe.Lap("x", 123), "no lap");
+ }
+
+ [Test]
+ public void Off_the_hooks_allocate_nothing()
+ {
+ TurnProbe.On = false;
+ Action handler = Named;
+ void Hooks()
+ {
+ for (int i = 0; i < 200; i++)
+ {
+ var t = TurnProbe.Start();
+ t = TurnProbe.Lap("UnitLayer.Rebuild", t);
+ TurnProbe.Handler("Changed", handler, t);
+ TurnProbe.Step(t);
+ }
+ }
+ Hooks(); // warm up outside the recorder: the first call of each hook (and of Hooks) JIT-compiles and allocates
+ // Unity's GC.Alloc recorder, as MenuMusicTests uses: GC.GetAllocatedBytesForCurrentThread read 0 even for the
+ // probed turn's handler keys in the Editor, so it could not show an allocation either way.
+ Assert.That(Hooks, Is.Not.AllocatingGCMemory(), "off: no allocation in the hooks");
+
+ // The control: the same hooks in a probed turn allocate (the handler keys), so the check above can see allocation.
+ TurnProbe.On = true;
+ TurnProbe.BeginTurn(1, new DateTime(1948, 6, 15));
+ Assert.That(Hooks, Is.AllocatingGCMemory(), "on: the recorder sees the handler keys");
+ TurnProbe.EndTurn(_ => { });
+ }
+
+ [Test]
+ public void On_every_handler_gets_a_time_in_the_order_it_ran()
+ {
+ TurnProbe.On = true;
+ var bridge = NewBridge();
+ bridge.Changed += Named;
+ bridge.Changed += () => TurnProbe.Lap("Inner", TurnProbe.Start());
+ bridge.Changed += () => { };
+ bridge.CombatResolved += _ => { };
+ bridge.TurnEnded += _ => { };
+ var turn = bridge.TurnStart.Turn; var date = bridge.TurnStart.Date;
+ bridge.EndTurn();
+ Assert.AreEqual(1, logged.Count, "one line a turn");
+ var line = logged[0];
+ Assert.AreEqual(line, TurnProbe.Last);
+ StringAssert.IsMatch(LineFormat.ToString(), line);
+ var f = Fields(line);
+ Assert.AreEqual(turn.ToString(CultureInfo.InvariantCulture), f["turn"]);
+ Assert.AreEqual(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), f["date"]);
+ Assert.AreEqual("5", f["handlers"]);
+ var keys = line.Split(' ').Skip(7).Select(x => x.Split('=')[0]).ToList();
+ CollectionAssert.AreEqual(new[]
+ {
+ "Changed/TurnProbeTests.Named",
+ "Changed/TurnProbeTests.On_every_handler_gets_a_time_in_the_order_it_ran.lambda",
+ "Changed/TurnProbeTests.On_every_handler_gets_a_time_in_the_order_it_ran.lambda#2",
+ "CombatResolved/TurnProbeTests.On_every_handler_gets_a_time_in_the_order_it_ran.lambda",
+ "TurnEnded/TurnProbeTests.On_every_handler_gets_a_time_in_the_order_it_ran.lambda",
+ "@Inner",
+ }, keys);
+ Assert.IsFalse(TurnProbe.Active, "the turn is closed");
+
+ // Only End turn is probed: an order's Changed outside it writes nothing.
+ logged.Clear();
+ bridge.Skip(bridge.TurnStart.Units.Keys.First());
+ Assert.IsEmpty(logged);
+ }
+
+ [Test]
+ public void On_the_game_runs_as_it_does_off()
+ {
+ var hashes = new List<string>();
+ foreach (var on in new[] { false, true })
+ {
+ TurnProbe.On = on;
+ var bridge = NewBridge();
+ for (int t = 0; t < 3; t++) bridge.EndTurn();
+ hashes.Add(bridge.TurnStart.Hash());
+ }
+ Assert.AreEqual(hashes[0], hashes[1], "the probe never changes the sim");
+ Assert.AreEqual(3, logged.Count, "one line for each probed turn");
+ }
+
+ [Test]
+ public void The_line_format_is_fixed_and_culture_invariant()
+ {
+ var culture = Thread.CurrentThread.CurrentCulture;
+ try
+ {
+ Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE"); // a decimal comma: the line must not use it
+ var line = TurnProbe.Line(3, new DateTime(1948, 8, 15), 1234.567, 7.5,
+ new[] { ("Changed/GameRoot.RenderPlacementsIfChanged", 12.345), ("TurnEnded/A b=c", 0.004) },
+ new[] { ("UnitLayer.Rebuild", 45.0) });
+ Assert.AreEqual("TURNLOG v=1 turn=3 date=1948-08-15 total_ms=1234.57 step_ms=7.50 handlers=2 "
+ + "Changed/GameRoot.RenderPlacementsIfChanged=12.35 TurnEnded/A_b_c=0.00 @UnitLayer.Rebuild=45.00", line);
+ StringAssert.IsMatch(LineFormat.ToString(), line);
+ }
+ finally { Thread.CurrentThread.CurrentCulture = culture; }
+ }
+
+ [Test]
+ public void Handler_names_drop_the_compilers_numbering()
+ {
+ Action group = Named;
+ Action lambda = () => { };
+ void Local() { }
+ Action local = Local;
+ Assert.AreEqual("TurnProbeTests.Named", TurnProbe.HandlerName(group));
+ Assert.AreEqual("TurnProbeTests.Handler_names_drop_the_compilers_numbering.lambda", TurnProbe.HandlerName(lambda));
+ Assert.AreEqual("TurnProbeTests.Handler_names_drop_the_compilers_numbering.Local", TurnProbe.HandlerName(local));
+ }
+
+ /// <summary>The game as a player boots it: the line times every subscriber of the four events, and the map layers'
+ /// sections #2905 measured (the unit tokens, the special buildings, the other scenery layers).</summary>
+ [Test]
+ public void In_the_booted_game_every_subscriber_and_the_map_layers_are_timed()
+ {
+ var saveDir = Path.Combine(Path.GetTempPath(), "statecraft-turnprobe-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var inputs = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+ Object.FindFirstObjectByType<MapScene>().Build(inputs.Map);
+ var root = Object.FindFirstObjectByType<GameRoot>();
+ root.Store = new SaveStore(saveDir);
+ root.Begin(inputs, 0);
+ var bridge = root.Bridge!;
+ int Subscribers(string evt) =>
+ (typeof(SimBridge).GetField(evt, BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(bridge) as Delegate)?.GetInvocationList().Length ?? 0;
+ int expected = Subscribers(nameof(SimBridge.Stepped)) + Subscribers(nameof(SimBridge.Changed)) + Subscribers(nameof(SimBridge.CombatResolved))
+ + Subscribers(nameof(SimBridge.TurnEnded));
+ Assert.Greater(expected, 10, "the game's presenters listen");
+
+ TurnProbe.On = true;
+ bridge.EndTurn();
+ Assert.AreEqual(1, logged.Count);
+ var line = logged[0];
+ StringAssert.IsMatch(LineFormat.ToString(), line);
+ var f = Fields(line);
+ Assert.AreEqual(expected.ToString(CultureInfo.InvariantCulture), f["handlers"], line);
+ Assert.AreEqual(expected, f.Keys.Count(k => k.Contains("/")), line);
+ foreach (var key in new[]
+ {
+ "Stepped/EnemyTurnPlayback.Stepped", "Changed/GameRoot.RenderPlacementsIfChanged", "TurnEnded/GameStart.Autosave.Save",
+ "@GameRoot.regions", "@UnitLayer.Show", "@GameRoot.unitsDim",
+ "@RouteLayer", "@ArmisticeLines", "@TownLandmarks", "@WildlifeLayer", "@HulaPapyrusLayer", "@SiteGroundLayer",
+ "@CivilianPeople", "@RuralLife", "@SpecialBuildingModels", "@HexPropModels", "@SeaAirCollection", "@Sites", "@Placements",
+ })
+ Assert.IsTrue(f.ContainsKey(key), key + " in " + line);
+ Assert.Greater(double.Parse(f["step_ms"], CultureInfo.InvariantCulture), 0, "the sim step is timed");
+ }
+ finally
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);
+ }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/TurnProbeTests.cs.meta b/unity/Assets/Tests/EditMode/TurnProbeTests.cs.meta
new file mode 100644
index 000000000..39facc044
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TurnProbeTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: b86c436a50f843eda2fbb5ac0c18a36d