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.

Map: residency view and its callers stop allocating per frame (#2351)

Eyal Golan75145c20b6bd
diff --git a/changelog.d/e21-w51-residency-alloc.md b/changelog.d/e21-w51-residency-alloc.md
new file mode 100644
index 000000000..fa99b348f
--- /dev/null
+++ b/changelog.d/e21-w51-residency-alloc.md
@@ -0,0 +1,8 @@
+### Changed
+
+- Choosing which nearby map models stay loaded (people, rural scenes, aircraft and ships, special buildings, unit
+ figures and camp tents) builds fewer temporary collections each frame; camp tents build none. The choice itself is
+ unchanged.
+- The people, rural scenes, aircraft and ships, special buildings and unit figures layers no longer build new anchor
+ lists or key comparisons for that choice each frame, and people no longer build new component arrays when they
+ switch between their far and near figures; what they show is unchanged.
diff --git a/unity/Assets/Scripts/Map/Collection/CampTentModels.cs b/unity/Assets/Scripts/Map/Collection/CampTentModels.cs
index 409ae4067..689e60ca0 100644
--- a/unity/Assets/Scripts/Map/Collection/CampTentModels.cs
+++ b/unity/Assets/Scripts/Map/Collection/CampTentModels.cs
@@ -31,6 +31,8 @@ namespace Statecraft.Game.Map.Collection
readonly List<Renderer> models = new List<Renderer>();
readonly List<GameObject> instances = new List<GameObject>();
readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();
+ readonly List<int> goneCameraIds = new List<int>();
+ readonly List<(string key, Vector3 at, float radius)> anchors = new List<(string, Vector3, float)>();
IReadOnlyList<SettlementKits.KhakiTent> tents = Array.Empty<SettlementKits.KhakiTent>();
Renderer? kit;
CollectionResidencyView? view;
@@ -79,6 +81,8 @@ namespace Statecraft.Game.Map.Collection
layer.centre = new Vector3(c.x, 0f, c.y);
layer.extent = tents.Max(t => (t.C - c).magnitude + 0.5f * t.W);
}
+ // The one anchor Choose observes every frame, as before even with no tents (centre and extent then stay zero).
+ layer.anchors.Add((Key, layer.centre, layer.extent));
return layer;
}
@@ -164,7 +168,13 @@ namespace Statecraft.Game.Map.Collection
internal void AdvanceCameraFrame(int frame)
{
if (view != null && view.Prune(frame)) dirty = true;
- foreach (int id in closeFor.Keys.Where(id => !view!.Observes(id)).ToArray()) closeFor.Remove(id);
+ goneCameraIds.Clear();
+ if (view != null)
+ {
+ foreach (var pair in closeFor)
+ if (!view.Observes(pair.Key)) goneCameraIds.Add(pair.Key);
+ for (int i = 0; i < goneCameraIds.Count; i++) closeFor.Remove(goneCameraIds[i]);
+ }
if (dirty) { dirty = false; Refresh(); }
}
@@ -179,7 +189,7 @@ namespace Statecraft.Game.Map.Collection
{
if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection || view == null) return;
bool before = Demanded;
- view.Observe(cam, new[] { (Key, centre, extent) }, Time.frameCount);
+ view.Observe(cam, anchors, Time.frameCount);
if (before != Demanded)
{
if (Application.isPlaying || inRender)
diff --git a/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs b/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs
index fb4776a7e..c1de78b3d 100644
--- a/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs
+++ b/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs
@@ -393,6 +393,9 @@ namespace Statecraft.Game.Map.Collection
new Dictionary<(string, CollectionDetail), List<GameObject>>();
readonly Dictionary<string, Transform> peopleByKey = new Dictionary<string, Transform>(StringComparer.Ordinal);
readonly List<(Transform Person, bool Animate)> pairs = new List<(Transform, bool)>();
+ readonly List<Renderer> applyRenderers = new List<Renderer>();
+ readonly List<Animator> applyAnimators = new List<Animator>();
+ Action<List<(string key, Vector3 at, float radius)>>? fillResidencyAnchors;
bool lastClose;
public readonly List<PlacedFigure> Placed = new List<PlacedFigure>();
@@ -548,8 +551,10 @@ namespace Statecraft.Game.Map.Collection
if (residencyView != null)
{
var previousDemand = residencyView.Keys;
- residencyView.Observe(camera, wanted.Select(w => (w.Key, w.At, FigureClearanceM)), Time.frameCount);
- if (!previousDemand.SetEquals(residencyView.Keys)) { RefreshResidencyCore(false); SyncNearVisuals(); Apply(lastClose); }
+ residencyView.Observe(camera, fillResidencyAnchors ??= FillResidencyAnchors, Time.frameCount);
+ bool same = previousDemand.Count == residencyView.Keys.Count;
+ foreach (string key in previousDemand) if (!residencyView.Keys.Contains(key)) { same = false; break; }
+ if (!same) { RefreshResidencyCore(false); SyncNearVisuals(); Apply(lastClose); }
}
int id = camera.GetInstanceID();
bool close = CloseAt(TownLandmarks.ViewDistance(camera), closeFor.TryGetValue(id, out var previous) ? previous : (bool?)null);
@@ -558,6 +563,10 @@ namespace Statecraft.Game.Map.Collection
Apply(close);
}
+ void FillResidencyAnchors(List<(string key, Vector3 at, float radius)> anchors)
+ {
+ for (int i = 0; i < wanted.Count; i++) anchors.Add((wanted[i].Key, wanted[i].At, FigureClearanceM));
+ }
void Apply(bool close)
{
foreach (var pair in pairs)
@@ -565,11 +574,20 @@ namespace Statecraft.Game.Map.Collection
if (pair.Person == null) continue;
var far = pair.Person.Find("Far"); var nearRoot = pair.Person.Find("Near");
bool near = close && nearRoot != null;
- if (far != null) foreach (var renderer in far.GetComponentsInChildren<Renderer>(true)) if (renderer != null) renderer.forceRenderingOff = near;
+ if (far != null)
+ {
+ applyRenderers.Clear();
+ far.GetComponentsInChildren(true, applyRenderers);
+ foreach (var renderer in applyRenderers) if (renderer != null) renderer.forceRenderingOff = near;
+ }
if (nearRoot != null)
{
- foreach (var renderer in nearRoot.GetComponentsInChildren<Renderer>(true)) if (renderer != null) renderer.forceRenderingOff = !near;
- foreach (var animator in nearRoot.GetComponentsInChildren<Animator>(true)) if (animator != null) animator.enabled = near && pair.Animate;
+ applyRenderers.Clear();
+ nearRoot.GetComponentsInChildren(true, applyRenderers);
+ foreach (var renderer in applyRenderers) if (renderer != null) renderer.forceRenderingOff = !near;
+ applyAnimators.Clear();
+ nearRoot.GetComponentsInChildren(true, applyAnimators);
+ foreach (var animator in applyAnimators) if (animator != null) animator.enabled = near && pair.Animate;
}
}
}
diff --git a/unity/Assets/Scripts/Map/Collection/CollectionResidency.cs b/unity/Assets/Scripts/Map/Collection/CollectionResidency.cs
index 65318a203..66b9a933e 100644
--- a/unity/Assets/Scripts/Map/Collection/CollectionResidency.cs
+++ b/unity/Assets/Scripts/Map/Collection/CollectionResidency.cs
@@ -199,13 +199,24 @@ namespace Statecraft.Game.Map.Collection
internal int Frame;
internal bool Visible;
internal HashSet<string> Keys = new HashSet<string>(StringComparer.Ordinal);
+ internal HashSet<string> ScratchKeys = new HashSet<string>(StringComparer.Ordinal);
}
readonly CollectionResidencyPolicy policy;
readonly Dictionary<int, Choice> cameras = new Dictionary<int, Choice>();
- internal HashSet<string> Keys => new HashSet<string>(cameras.Values.SelectMany(c => c.Keys), StringComparer.Ordinal);
+ readonly List<int> goneCameraIds = new List<int>();
+ readonly List<(string key, Vector3 at, float radius)> filledAnchors = new List<(string, Vector3, float)>();
+ // Callers retain Keys across Observe to detect a demand change. These two sets take turns so that snapshot remains
+ // unchanged through the comparison without allocating a detached HashSet every frame.
+ HashSet<string> keys = new HashSet<string>(StringComparer.Ordinal);
+ HashSet<string> scratchKeys = new HashSet<string>(StringComparer.Ordinal);
+ internal HashSet<string> Keys => keys;
internal bool Observes(int cameraId) => cameras.ContainsKey(cameraId);
internal CollectionResidencyView(CollectionResidencyPolicy policy) { this.policy = policy; }
- internal void Clear() => cameras.Clear();
+ internal void Clear()
+ {
+ cameras.Clear(); goneCameraIds.Clear(); scratchKeys.Clear();
+ var old = keys; keys = scratchKeys; scratchKeys = old;
+ }
// Unproject in camera space: subtracting near/far WORLD points at hundreds of kilometres loses
// direction precision, moving a 100km ground focus kilometres off its actual footprint.
internal static bool TryGroundFocus(Camera camera, out Vector3 focus)
@@ -227,29 +238,70 @@ namespace Statecraft.Game.Map.Collection
internal bool Prune(int frame)
{
- var gone = cameras.Where(p => p.Value.Camera == null || !p.Value.Camera.isActiveAndEnabled
- || frame - p.Value.Frame > policy.CameraGraceFrames).Select(p => p.Key).ToArray();
- foreach (int id in gone) cameras.Remove(id);
- return gone.Length != 0;
+ bool changed = PruneCameras(frame);
+ if (changed) RebuildKeys();
+ return changed;
+ }
+ bool PruneCameras(int frame)
+ {
+ goneCameraIds.Clear();
+ foreach (var pair in cameras)
+ if (pair.Value.Camera == null || !pair.Value.Camera.isActiveAndEnabled
+ || frame - pair.Value.Frame > policy.CameraGraceFrames)
+ goneCameraIds.Add(pair.Key);
+ for (int i = 0; i < goneCameraIds.Count; i++) cameras.Remove(goneCameraIds[i]);
+ return goneCameraIds.Count != 0;
}
- internal void Observe(Camera camera, IEnumerable<(string key, Vector3 at, float radius)> anchors, int frame)
+ void RebuildKeys()
+ {
+ scratchKeys.Clear();
+ foreach (var choice in cameras.Values)
+ foreach (string key in choice.Keys)
+ scratchKeys.Add(key);
+ var old = keys; keys = scratchKeys; scratchKeys = old;
+ }
+ internal void Observe(Camera camera, IEnumerable<(string key, Vector3 at, float radius)> anchors, int frame) =>
+ Observe(camera, anchors, null, frame);
+ // The anchors are built only when this camera is close enough to scan them, as the old lazy enumerables were, so
+ // the far view does no per-anchor work. Pass a cached delegate: a method group converts to a new one per call.
+ internal void Observe(Camera camera, Action<List<(string key, Vector3 at, float radius)>> fillAnchors, int frame) =>
+ Observe(camera, null, fillAnchors, frame);
+ void Observe(Camera camera, IEnumerable<(string key, Vector3 at, float radius)>? anchors,
+ Action<List<(string key, Vector3 at, float radius)>>? fillAnchors, int frame)
{
if (camera.cameraType == CameraType.Preview || camera.cameraType == CameraType.Reflection) return;
- Prune(frame);
+ PruneCameras(frame);
int id = camera.GetInstanceID();
if (!cameras.TryGetValue(id, out var choice)) cameras[id] = choice = new Choice { Camera = camera };
choice.Frame = frame;
float height = Kits.TownModelLayer.ViewDistance(camera);
choice.Visible = height <= (choice.Visible ? policy.ViewExitM : policy.ViewEnterM);
- var old = choice.Keys; choice.Keys = new HashSet<string>(StringComparer.Ordinal);
- if (!choice.Visible) return;
- if (!TryGroundFocus(camera, out var focus)) return;
- foreach (var (key, at, extent) in anchors)
+ var old = choice.Keys; var next = choice.ScratchKeys; next.Clear();
+ if (choice.Visible && TryGroundFocus(camera, out var focus))
{
- float dx = focus.x - at.x, dz = focus.z - at.z;
- float radius = (old.Contains(key) ? policy.ExitM : policy.EnterM) + Mathf.Max(0, extent);
- if (dx * dx + dz * dz <= radius * radius) choice.Keys.Add(key);
+ if (fillAnchors != null) { filledAnchors.Clear(); fillAnchors(filledAnchors); anchors = filledAnchors; }
+ if (anchors is List<(string key, Vector3 at, float radius)> list)
+ {
+ for (int i = 0; i < list.Count; i++)
+ {
+ var (key, at, extent) = list[i];
+ float dx = focus.x - at.x, dz = focus.z - at.z;
+ float radius = (old.Contains(key) ? policy.ExitM : policy.EnterM) + Mathf.Max(0, extent);
+ if (dx * dx + dz * dz <= radius * radius) next.Add(key);
+ }
+ }
+ else
+ {
+ foreach (var (key, at, extent) in anchors!)
+ {
+ float dx = focus.x - at.x, dz = focus.z - at.z;
+ float radius = (old.Contains(key) ? policy.ExitM : policy.EnterM) + Mathf.Max(0, extent);
+ if (dx * dx + dz * dz <= radius * radius) next.Add(key);
+ }
+ }
}
+ choice.Keys = next; choice.ScratchKeys = old;
+ RebuildKeys();
}
}
}
diff --git a/unity/Assets/Scripts/Map/Collection/RuralLife.cs b/unity/Assets/Scripts/Map/Collection/RuralLife.cs
index 1247d74f3..54f45e3f6 100644
--- a/unity/Assets/Scripts/Map/Collection/RuralLife.cs
+++ b/unity/Assets/Scripts/Map/Collection/RuralLife.cs
@@ -75,9 +75,9 @@ namespace Statecraft.Game.Map.Collection
public readonly struct Want : IEquatable<Want>
{
- public readonly string Key, Model; public readonly Vector2 Anchor; public readonly float AnchorRadius;
+ public readonly string Key, Model, ResidencyKey; public readonly Vector2 Anchor; public readonly float AnchorRadius;
public Want(string key, string model, Vector2 anchor, float anchorRadius)
- { Key = key; Model = model; Anchor = anchor; AnchorRadius = anchorRadius; }
+ { Key = key; Model = model; ResidencyKey = key + "|" + model; Anchor = anchor; AnchorRadius = anchorRadius; }
public bool Equals(Want other) => Key == other.Key && Model == other.Model && Anchor == other.Anchor && AnchorRadius == other.AnchorRadius;
public override bool Equals(object? obj) => obj is Want other && Equals(other);
public override int GetHashCode() => (Key, Model, Anchor, AnchorRadius).GetHashCode();
@@ -192,7 +192,7 @@ namespace Statecraft.Game.Map.Collection
// but gates Near to the successfully placed v0.3.1 pairings (Scenes), never unplaced/failed/capped wants.
var far = wants.Select(w => (w.Model, CollectionDetail.Far));
var keys = residencyView?.Keys;
- var near = Scenes.Where(w => keys == null || keys.Contains(w.Key + "|" + w.Model))
+ var near = Scenes.Where(w => keys == null || keys.Contains(w.ResidencyKey))
.Select(w => (w.Model, CollectionDetail.Near));
return far.Concat(near);
}
@@ -242,7 +242,7 @@ namespace Statecraft.Game.Map.Collection
IEnumerable<Want> Admitted()
{
var keys = residencyView?.Keys;
- return keys == null ? wants : wants.Where(w => keys.Contains(w.Key + "|" + w.Model));
+ return keys == null ? wants : wants.Where(w => keys.Contains(w.ResidencyKey));
}
void ClearVisuals()
{
@@ -258,6 +258,8 @@ namespace Statecraft.Game.Map.Collection
readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();
readonly List<(Renderer Renderer, CollectionDetail Detail, string Instance)> renderers = new List<(Renderer, CollectionDetail, string)>();
readonly List<(Animator Animator, CollectionDetail Detail)> animators = new List<(Animator, CollectionDetail)>();
+ Action<List<(string key, Vector3 at, float radius)>>? fillResidencyAnchors;
+ readonly HashSet<string> nearInstances = new HashSet<string>(StringComparer.Ordinal);
readonly Dictionary<(string Model, CollectionDetail Detail), List<GameObject>> originals =
new Dictionary<(string, CollectionDetail), List<GameObject>>();
List<Want> wants = new List<Want>();
@@ -493,25 +495,41 @@ namespace Statecraft.Game.Map.Collection
void OnDisable() { RenderPipelineManager.beginCameraRendering -= Choose; ReleaseResidency(); }
void OnDestroy() { residency?.Dispose(); residency = null; }
+ void FillResidencyAnchors(List<(string key, Vector3 at, float radius)> anchors)
+ {
+ for (int i = 0; i < wants.Count; i++)
+ {
+ var w = wants[i];
+ anchors.Add((w.ResidencyKey, new Vector3(w.Anchor.x, 0, w.Anchor.y), w.AnchorRadius));
+ }
+ }
internal void Choose(ScriptableRenderContext context, Camera camera)
{
if (camera.cameraType == CameraType.Preview || camera.cameraType == CameraType.Reflection) return;
if (residencyView != null)
{
var previousDemand = residencyView.Keys;
- residencyView.Observe(camera, wants.Select(w => (w.Key + "|" + w.Model,
- new Vector3(w.Anchor.x, 0, w.Anchor.y), w.AnchorRadius)), Time.frameCount);
- if (!previousDemand.SetEquals(residencyView.Keys)) { RefreshResidencyCore(false); SyncNearVisuals(); }
+ residencyView.Observe(camera, fillResidencyAnchors ??= FillResidencyAnchors, Time.frameCount);
+ bool same = previousDemand.Count == residencyView.Keys.Count;
+ foreach (string key in previousDemand) if (!residencyView.Keys.Contains(key)) { same = false; break; }
+ if (!same) { RefreshResidencyCore(false); SyncNearVisuals(); }
}
int id = camera.GetInstanceID();
bool close = CloseAt(TownLandmarks.ViewDistance(camera), closeFor.TryGetValue(id, out var was) ? was : (bool?)null);
closeFor[id] = close; LastClose = close;
- var nearInstances = new HashSet<string>(renderers.Where(p => p.Renderer != null && p.Detail == CollectionDetail.Near)
- .Select(p => p.Instance), StringComparer.Ordinal);
- foreach (var (renderer, detail, instance) in renderers)
+ nearInstances.Clear();
+ for (int i = 0; i < renderers.Count; i++)
+ if (renderers[i].Renderer != null && renderers[i].Detail == CollectionDetail.Near) nearInstances.Add(renderers[i].Instance);
+ for (int i = 0; i < renderers.Count; i++)
+ {
+ var (renderer, detail, instance) = renderers[i];
if (renderer != null) renderer.forceRenderingOff = detail == CollectionDetail.Near ? !close : close && nearInstances.Contains(instance);
- foreach (var (animator, detail) in animators)
+ }
+ for (int i = 0; i < animators.Count; i++)
+ {
+ var (animator, detail) = animators[i];
if (animator != null) animator.enabled = detail == CollectionDetail.Near && close;
+ }
}
}
}
diff --git a/unity/Assets/Scripts/Map/Collection/SeaAirCollection.cs b/unity/Assets/Scripts/Map/Collection/SeaAirCollection.cs
index 84182b89a..d1ef5ec2c 100644
--- a/unity/Assets/Scripts/Map/Collection/SeaAirCollection.cs
+++ b/unity/Assets/Scripts/Map/Collection/SeaAirCollection.cs
@@ -267,17 +267,27 @@ namespace Statecraft.Game.Map.Collection
var keys = residencyView?.Keys;
return keys == null ? wants : wants.Where(w => keys.Contains(w.Key));
}
- IEnumerable<(string key, Vector3 at, float radius)> Anchors()
+ Action<List<(string key, Vector3 at, float radius)>>? fillResidencyAnchors;
+ void FillResidencyAnchors(List<(string key, Vector3 at, float radius)> anchors)
{
- if (map == null) yield break;
+ if (map == null) return;
var edge = EdgeSpot(map.Frame); // the Spitfire's anchor is on the ground under it; only its distance counts
- foreach (var w in wants)
+ for (int i = 0; i < wants.Count; i++)
{
- var c = SeaCraft.Coasts.FirstOrDefault(x => x.place == w.Place);
- yield return (w.Key, w.Model == C54 ? map.Frame.ToWorld(LodLon, LodLat, 0) : w.Model == Spitfire ? new Vector3(edge.x, 0, edge.y)
- : map.Frame.ToWorld(c.lon, c.lat, 0), SizeOf(w.Model));
+ var w = wants[i];
+ var c = default((string place, double lon, double lat, Vector2 seaward, int boats));
+ for (int j = 0; j < SeaCraft.Coasts.Length; j++)
+ if (SeaCraft.Coasts[j].place == w.Place) { c = SeaCraft.Coasts[j]; break; }
+ anchors.Add((w.Key, w.Model == C54 ? map.Frame.ToWorld(LodLon, LodLat, 0) : w.Model == Spitfire ? new Vector3(edge.x, 0, edge.y)
+ : map.Frame.ToWorld(c.lon, c.lat, 0), SizeOf(w.Model)));
}
}
+ static bool SameKeys(HashSet<string> before, HashSet<string> after)
+ {
+ if (before.Count != after.Count) return false;
+ foreach (string key in before) if (!after.Contains(key)) return false;
+ return true;
+ }
void RefreshResidency() => RefreshResidencyCore(true);
void RefreshResidencyCore(bool redraw)
{
@@ -329,8 +339,8 @@ namespace Statecraft.Game.Map.Collection
void ObserveResidency(Camera camera)
{
var before = residencyView!.Keys;
- residencyView.Observe(camera, Anchors(), Time.frameCount);
- if (!before.SetEquals(residencyView.Keys))
+ residencyView.Observe(camera, fillResidencyAnchors ??= FillResidencyAnchors, Time.frameCount);
+ if (!SameKeys(before, residencyView.Keys))
{ if (Application.isPlaying) residencyDirty = true; else RefreshResidencyCore(false); }
}
void LateUpdate()
diff --git a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs
index 9fe92fb5d..f810130df 100644
--- a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs
+++ b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs
@@ -173,6 +173,7 @@ namespace Statecraft.Game.Map.Collection
readonly HashSet<string> asked = new HashSet<string>(StringComparer.Ordinal);
readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();
readonly List<Renderer> renderers = new List<Renderer>();
+ Action<List<(string key, Vector3 at, float radius)>>? fillResidencyAnchors;
IReadOnlyList<Want> wants = Array.Empty<Want>();
CollectionResidency? residency;
@@ -200,10 +201,20 @@ namespace Statecraft.Game.Map.Collection
var keys = residencyView?.Keys;
return keys == null ? wants : wants.Where(w => keys.Contains(w.Key));
}
- IEnumerable<(string key, Vector3 at, float radius)> Anchors()
+ void FillResidencyAnchors(List<(string key, Vector3 at, float radius)> anchors)
{
- if (map == null) yield break;
- foreach (var w in wants) yield return (w.Key, map.Frame.ToWorld(w.Lon, w.Lat, 0), ClearanceOf(w.Model));
+ if (map == null) return;
+ for (int i = 0; i < wants.Count; i++)
+ {
+ var w = wants[i];
+ anchors.Add((w.Key, map.Frame.ToWorld(w.Lon, w.Lat, 0), ClearanceOf(w.Model)));
+ }
+ }
+ static bool SameKeys(HashSet<string> before, HashSet<string> after)
+ {
+ if (before.Count != after.Count) return false;
+ foreach (string key in before) if (!after.Contains(key)) return false;
+ return true;
}
void RefreshResidency() => RefreshResidencyCore(true);
void RefreshResidencyCore(bool redraw)
@@ -261,8 +272,8 @@ namespace Statecraft.Game.Map.Collection
void ObserveResidency(Camera camera, bool inRender)
{
var before = residencyView!.Keys;
- residencyView.Observe(camera, Anchors(), Time.frameCount);
- if (!before.SetEquals(residencyView.Keys))
+ residencyView.Observe(camera, fillResidencyAnchors ??= FillResidencyAnchors, Time.frameCount);
+ if (!SameKeys(before, residencyView.Keys))
{
if (Application.isPlaying || inRender)
{
diff --git a/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs b/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs
index 1ab34851d..7d718e15e 100644
--- a/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs
@@ -18,6 +18,7 @@ namespace Statecraft.Game.Map.Units
string id = "";
CollectionResidency? residency, retainedFarResidency, retainedNearResidency;
CollectionResidencyView? view;
+ readonly List<(string key, Vector3 at, float radius)> residencyAnchors = new List<(string, Vector3, float)>(1);
bool nearWanted, initialized, draws = true, retainFar;
Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? acquire;
internal void Initialize(string model, CollectionResidencyPolicy policy,
@@ -104,8 +105,15 @@ namespace Statecraft.Game.Map.Units
{
if (this == null || !initialized || view == null || camera.cameraType == CameraType.Preview || camera.cameraType == CameraType.Reflection) return;
bool first = !observed; observed = true; var before = view.Keys;
- view.Observe(camera, new[] { (id, transform.position, 0f) }, Time.frameCount);
- if (first || !before.SetEquals(view.Keys)) Schedule(view.Keys.Contains(id));
+ residencyAnchors.Clear(); residencyAnchors.Add((id, transform.position, 0f));
+ view.Observe(camera, residencyAnchors, Time.frameCount);
+ bool changed = first;
+ if (!changed)
+ {
+ changed = before.Count != view.Keys.Count;
+ if (!changed) foreach (string key in before) if (!view.Keys.Contains(key)) { changed = true; break; }
+ }
+ if (changed) Schedule(view.Keys.Contains(id));
}
void LateUpdate()
{
diff --git a/unity/Assets/Tests/EditMode/CollectionResidencyViewAllocationTests.cs b/unity/Assets/Tests/EditMode/CollectionResidencyViewAllocationTests.cs
new file mode 100644
index 000000000..2d51ff675
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CollectionResidencyViewAllocationTests.cs
@@ -0,0 +1,103 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+using Statecraft.Game.Map.Collection;
+using UnityEngine;
+using UnityEngine.TestTools.Constraints;
+using Object = UnityEngine.Object;
+using Is = UnityEngine.TestTools.Constraints.Is;
+
+public sealed class CollectionResidencyViewAllocationTests
+{
+ [Test]
+ public void RepeatedObservationAndPruningAllocateNoManagedMemory()
+ {
+ var cameraObject = new GameObject("collection residency allocation camera", typeof(Camera));
+ try
+ {
+ var camera = cameraObject.GetComponent<Camera>();
+ camera.transform.SetPositionAndRotation(new Vector3(0f, 10f, 0f), Quaternion.Euler(90f, 0f, 0f));
+ var view = new CollectionResidencyView(new CollectionResidencyPolicy(
+ 100f, 110f, 100f, 110f, 2, "TEST ONLY"));
+ var anchors = new List<(string key, Vector3 at, float radius)>
+ {
+ ("fixed", Vector3.zero, 0f),
+ };
+
+ for (int frame = 0; frame < 5; frame++)
+ {
+ view.Observe(camera, anchors, frame);
+ Assert.AreEqual(1, view.Keys.Count);
+ Assert.IsFalse(view.Prune(frame));
+ }
+
+ // Prove the recorder catches the kind of managed allocation this regression guards against.
+ Assert.That(() => { var allocated = new int[1]; GC.KeepAlive(allocated); }, new AllocatingGCMemoryConstraint());
+ int nextFrame = 5; bool demandStayedFixed = true, nothingWasPruned = true;
+ TestDelegate hundredFrames = () =>
+ {
+ for (int i = 0; i < 100; i++)
+ {
+ var before = view.Keys;
+ view.Observe(camera, anchors, nextFrame++);
+ // Explicit membership, not SetEquals: Unity's Mono HashSet.SetEquals may box an enumerator, and this
+ // guards the view's own allocations, not the class library's.
+ demandStayedFixed &= before.Count == 1 && before.Contains("fixed")
+ && view.Keys.Count == 1 && view.Keys.Contains("fixed");
+ nothingWasPruned &= !view.Prune(nextFrame - 1);
+ }
+ };
+ // Run the exact measured delegate once before measuring it. Mono JIT-compiles this lambda on its first call,
+ // and compiling each "fixed" literal allocates a temporary string (2 GC.Alloc samples on the first call, 0 on
+ // later calls, measured in Unity 6000.3.25f1 on he_IL and en_US, PR 2351). That one-time cost belongs to the
+ // test, not to the view; the measured call below still runs all 100 frames, so any per-frame allocation in
+ // Observe or Prune still fails it.
+ hundredFrames();
+ Assert.That(hundredFrames, Is.Not.AllocatingGCMemory());
+ Assert.IsTrue(demandStayedFixed, "the fixed camera keeps the same resident key");
+ Assert.IsTrue(nothingWasPruned, "the observed camera remains live");
+ }
+ finally
+ {
+ Object.DestroyImmediate(cameraObject);
+ }
+ }
+
+ [Test]
+ public void TheFillDelegateRunsOnlyWhenTheCameraIsCloseEnoughToScanAndAllocatesNothing()
+ {
+ var cameraObject = new GameObject("collection residency fill camera", typeof(Camera));
+ try
+ {
+ var camera = cameraObject.GetComponent<Camera>();
+ var view = new CollectionResidencyView(new CollectionResidencyPolicy(
+ 100f, 110f, 100f, 110f, 2, "TEST ONLY"));
+ int fills = 0;
+ Action<List<(string key, Vector3 at, float radius)>> fill = anchors => { fills++; anchors.Add(("fixed", Vector3.zero, 0f)); };
+
+ // Too high to scan (1 km over a 100 m view enter height): the anchors are never built, as with the old lazy sources.
+ camera.transform.SetPositionAndRotation(new Vector3(0f, 1000f, 0f), Quaternion.Euler(90f, 0f, 0f));
+ for (int frame = 0; frame < 3; frame++) view.Observe(camera, fill, frame);
+ Assert.AreEqual(0, fills, "a camera above the view height builds no anchors");
+ Assert.AreEqual(0, view.Keys.Count);
+
+ camera.transform.SetPositionAndRotation(new Vector3(0f, 10f, 0f), Quaternion.Euler(90f, 0f, 0f));
+ for (int frame = 3; frame < 8; frame++) view.Observe(camera, fill, frame);
+ Assert.AreEqual(5, fills, "a close camera builds the anchors once per observation");
+ CollectionAssert.AreEquivalent(new[] { "fixed" }, view.Keys);
+
+ int nextFrame = 8;
+ Assert.That(() =>
+ {
+ for (int i = 0; i < 100; i++) { view.Observe(camera, fill, nextFrame); view.Prune(nextFrame); nextFrame++; }
+ }, Is.Not.AllocatingGCMemory());
+ Assert.AreEqual(105, fills);
+ Assert.IsTrue(view.Keys.Count == 1 && view.Keys.Contains("fixed"));
+ }
+ finally
+ {
+ Object.DestroyImmediate(cameraObject);
+ }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/CollectionResidencyViewAllocationTests.cs.meta b/unity/Assets/Tests/EditMode/CollectionResidencyViewAllocationTests.cs.meta
new file mode 100644
index 000000000..45ac99162
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CollectionResidencyViewAllocationTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1ec1d77f606e46dda35fb028fa892d6a