A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: edit-mode render callbacks defer model rebuilds to LateUpdate (Fixes #2099; stacked on #2046) (#2194)
Eyal Golaned044cfed6e1
diff --git a/changelog.d/2099-edit-render-defer.md b/changelog.d/2099-edit-render-defer.mdnew file mode 100644index 000000000..b65bbcde6--- /dev/null+++ b/changelog.d/2099-edit-render-defer.md@@ -0,0 +1,4 @@+### Fixed+- In the Unity Editor, the special buildings, the town building models and the whole-town landmarks no longer load,+ create or destroy models while a Scene or Game view camera is rendering (#2099): the change waits for the next+ update, as it already did in play mode and as the camp tents do since #2046. Editor only; players are unaffected.diff --git a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.csindex b0f11045d..cfbb4645f 100644--- a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs+++ b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs@@ -258,12 +258,22 @@ namespace Statecraft.Game.Map.Collectionif (map != null) Statecraft.Game.Map.Units.UnitShowcase.HideTrees(map, Name, Array.Empty<(Vector2, float)>());}bool residencyDirty;- void ObserveResidency(Camera camera)+ void ObserveResidency(Camera camera, bool inRender){var before = residencyView!.Keys;residencyView.Observe(camera, Anchors(), Time.frameCount);if (!before.SetEquals(residencyView.Keys))- { if (Application.isPlaying) residencyDirty = true; else RefreshResidencyCore(false); }+ {+ if (Application.isPlaying || inRender)+ {+ residencyDirty = true;+#if UNITY_EDITOR+ // Edit mode runs LateUpdate only when something asks for a player-loop update.+ if (!Application.isPlaying) UnityEditor.EditorApplication.QueuePlayerLoopUpdate();+#endif+ }+ else RefreshResidencyCore(false);+ }}void LateUpdate(){@@ -372,16 +382,21 @@ namespace Statecraft.Game.Map.Collection/// TownModelLayer.CloseExitM.</summary>public static bool CloseAt(float distance, bool? was) =>was == true ? distance <= Statecraft.Game.Map.Kits.TownModelLayer.CloseExitM : distance <= Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM;- void OnEnable() => RenderPipelineManager.beginCameraRendering += Choose;+ void OnEnable() => RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;void OnDisable(){- RenderPipelineManager.beginCameraRendering -= Choose;+ RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;if (residencyView != null) { residencyDirty = false; residencyView.Clear(); residency?.Replace(Array.Empty<(string, CollectionDetail)>()); }}- internal void Choose(ScriptableRenderContext context, Camera cam)+ /// <summary>The render callback. A change of residency never instantiates or destroys models while a camera renders, in+ /// edit mode either (a Scene or Game view camera): it waits for LateUpdate, as in play mode.</summary>+ void OnBeginCameraRendering(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: true);+ /// <summary>A direct call (tests and editor tools, outside any render) applies a change of residency at once in edit mode.</summary>+ internal void Choose(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: false);+ internal void ChooseCore(Camera cam, bool inRender){if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;- if (residencyView != null) ObserveResidency(cam);+ if (residencyView != null) ObserveResidency(cam, inRender);int id = cam.GetInstanceID(); bool close = CloseAt(TownLandmarks.ViewDistance(cam), closeFor.TryGetValue(id, out var was) ? was : (bool?)null);closeFor[id] = close; LastClose = close; foreach (var r in renderers) if (r != null) r.forceRenderingOff = !close;}diff --git a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs b/unity/Assets/Scripts/Map/Collection/TownLandmarks.csindex f9b6e54e8..526e44aaa 100644--- a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs+++ b/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs@@ -362,8 +362,15 @@ namespace Statecraft.Game.Map.Collectiondirty = true; RefreshWanted();}+ /// <summary>Whether <see cref="RefreshWanted"/> has work: a redraw, a lease to retire, or a change of the admitted towns+ /// or of the models asked for. RefreshWanted returns at once without it, and the edit-mode render callback asks for a+ /// player-loop update only with it, so a settled layer never keeps the editor updating (#2099).</summary>+ internal bool RefreshPending => dirty || retiring.Count != 0+ || !admittedKeys.SetEquals(wants.Where(Allowed).Select(w => w.Key)) || !asked.SetEquals(wants.Where(Allowed).Select(w => w.Model));+void RefreshWanted(){+ if (!RefreshPending) return;var keep = new HashSet<string>(StringComparer.Ordinal);var keys = new HashSet<string>(StringComparer.Ordinal);foreach (var want in wants) if (Allowed(want)) { keep.Add(want.Model); keys.Add(want.Key); }@@ -563,13 +570,13 @@ namespace Statecraft.Game.Map.Collectionvoid OnEnable(){- RenderPipelineManager.beginCameraRendering += Choose;+ RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;RenderPipelineManager.endCameraRendering += EndCamera;if (wants.Count > 0) { focusPolicy = null; Show(wants, date); }}void OnDisable(){- RenderPipelineManager.beginCameraRendering -= Choose;+ RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;RenderPipelineManager.endCameraRendering -= EndCamera;StopAllCoroutines(); retirementScheduled = false;RestoreRenderers(); ReleaseOwned();@@ -646,16 +653,26 @@ namespace Statecraft.Game.Map.CollectionRefreshWanted();}- /// <summary>Show each map-wide whole-town original unless this camera has that town's detailed buildings ready.</summary>- internal void Choose(ScriptableRenderContext context, Camera cam)+ /// <summary>The render callback. Nothing is acquired, instantiated or destroyed while a camera renders, in edit mode+ /// either (a Scene or Game view camera): the change waits for LateUpdate, as in play mode.</summary>+ void OnBeginCameraRendering(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: true);+ /// <summary>Show each map-wide whole-town original unless this camera has that town's detailed buildings ready. A direct+ /// call (tests and editor tools, outside any render) applies a change at once in edit mode.</summary>+ internal void Choose(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: false);+ internal void ChooseCore(Camera cam, bool inRender){if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;RestoreRenderers();var layer = Layer(); LastHidden = false;// Do not depend on which beginCameraRendering subscriber was enabled first.- layer?.PrepareCamera(cam);- if (!Application.isPlaying) RefreshWanted();- layer?.PrepareCamera(cam); // synchronous editor/fake arrivals may have made a whole seat ready+ layer?.PrepareCameraCore(cam, inRender);+ if (!Application.isPlaying && !inRender) RefreshWanted();+#if UNITY_EDITOR+ // In a render, LateUpdate refreshes instead; edit mode runs it only when something asks for a player-loop update,+ // so ask only when RefreshWanted has work (a request every render would keep the editor updating).+ if (inRender && !Application.isPlaying && RefreshPending) UnityEditor.EditorApplication.QueuePlayerLoopUpdate();+#endif+ layer?.PrepareCameraCore(cam, inRender); // synchronous editor/fake arrivals may have made a whole seat readyforeach (var renderer in renderers){if (renderer == null) continue;diff --git a/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs b/unity/Assets/Scripts/Map/Kits/TownModelLayer.csindex ffff718a6..30ec30050 100644--- a/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs+++ b/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs@@ -412,7 +412,9 @@ namespace Statecraft.Game.Map.Kits}bool suppressMissingLog;- internal void PrepareCamera(Camera cam)+ /// <summary>A direct call (tests and editor tools, outside any render) applies a change of demand at once in edit mode.</summary>+ internal void PrepareCamera(Camera cam) => PrepareCameraCore(cam, inRender: false);+ internal void PrepareCameraCore(Camera cam, bool inRender){RestoreRenderers();bool changed = PruneCameras();@@ -454,7 +456,18 @@ namespace Statecraft.Game.Map.Kitschoice.towns.Clear(); foreach (var id in next) choice.towns.Add(id); changed = true;}changed |= AdmitInView(choice, cam);- if (changed) { if (Application.isPlaying) reconcileDirty = true; else ReconcileModels(); }+ if (changed)+ {+ if (Application.isPlaying || inRender)+ {+ reconcileDirty = true;+#if UNITY_EDITOR+ // Edit mode runs LateUpdate only when something asks for a player-loop update.+ if (!Application.isPlaying) UnityEditor.EditorApplication.QueuePlayerLoopUpdate();+#endif+ }+ else ReconcileModels();+ }villagesReady.Clear();foreach (var (kit, close) in swaps){@@ -749,10 +762,12 @@ namespace Statecraft.Game.Map.Kits}void EndCamera(ScriptableRenderContext _, Camera camera) => RestoreRenderers();+ /// <summary>The render callback. A change of demand never acquires or retires models while a camera renders, in edit+ /// mode either (a Scene or Game view camera): it waits for LateUpdate, as in play mode.</summary>void Submit(ScriptableRenderContext context, Camera cam){if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;- PrepareCamera(cam);+ PrepareCameraCore(cam, inRender: true);bool close = choices.TryGetValue(cam.GetInstanceID(), out var choice) && choice.close;LastClose = close;int drawn = 0, draws = 0; long tris = 0;diff --git a/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.cs b/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.csindex 545da2ad2..319cfb50e 100644--- a/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.cs+++ b/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.cs@@ -98,6 +98,49 @@ public class CollectionOtherLeaveTests"a late answer after teardown creates no instance");Assert.AreEqual(acquired, released);}+ /// <summary>#2099, as #2046 for the camp tents: the edit-mode render callback (the beginCameraRendering handler itself)+ /// never acquires or instantiates the special buildings mid-render. A change of residency (here the first camera after the+ /// layer was disabled and enabled again) only marks the layer, and LateUpdate applies it, as in play mode; once settled, a+ /// second camera that sees none of them and renders in turn changes nothing. A direct Choose (no render) still applies at+ /// once.</summary>+ [Test] public void AnEditModeRenderCallbackDefersTheSpecialBuildingsToLateUpdate()+ {+ Assert.IsFalse(Application.isPlaying, "the edit-mode render path");+ var layer = (SpecialBuildingModels)MapLayer(true);+ var go = new GameObject("TEST ONLY camera"); var camera = go.AddComponent<Camera>();+ go.transform.position = new Vector3(0, 10000, 0); go.transform.rotation = Quaternion.Euler(90, 0, 0);+ var far = new GameObject("TEST ONLY far camera"); var other = far.AddComponent<Camera>();+ far.transform.position = new Vector3(0, 250000, 0); far.transform.rotation = Quaternion.Euler(90, 0, 0); // beyond the view exit+ const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;+ void Render(Camera cam) => typeof(SpecialBuildingModels).GetMethod("OnBeginCameraRendering", Private)!.Invoke(layer,+ new object[] { default(UnityEngine.Rendering.ScriptableRenderContext), cam });+ bool Dirty() => (bool)typeof(SpecialBuildingModels).GetField("residencyDirty", Private)!.GetValue(layer)!;+ try+ {+ Assert.Greater(layer.transform.childCount, 0, "precondition: the map-wide originals stand");+ layer.enabled = false; layer.enabled = true;+ Assert.AreEqual(0, layer.transform.childCount, "precondition: disabling the layer retires its originals");+ int before = acquired;+ Render(camera);+ Assert.AreEqual(before, acquired, "nothing is acquired inside the render callback");+ Assert.AreEqual(0, layer.transform.childCount, "and nothing is instantiated there");+ Assert.IsTrue(Dirty(), "the render marks the change for LateUpdate");+ typeof(SpecialBuildingModels).GetMethod("LateUpdate", Private)!.Invoke(layer, null);+ Assert.Greater(acquired, before, "LateUpdate acquires the originals");+ Assert.Greater(layer.transform.childCount, 0, "and places them");++ int settled = acquired, children = layer.transform.childCount;+ Render(other); Render(camera); Render(other);+ Assert.IsFalse(Dirty(), "settled: two cameras rendering in turn mark nothing (no update request every render)");+ Assert.AreEqual(settled, acquired); Assert.AreEqual(children, layer.transform.childCount);++ layer.enabled = false; layer.enabled = true; before = acquired;+ layer.Choose(default, camera);+ Assert.Greater(acquired, before, "a direct call (no render) acquires at once");+ Assert.Greater(layer.transform.childCount, 0, "and places them at once");+ }+ finally { Object.DestroyImmediate(go); Object.DestroyImmediate(far); }+ }GameObject Piece(string name){var piece = GameObject.CreatePrimitive(PrimitiveType.Cube); piece.name = name;diff --git a/unity/Assets/Tests/EditMode/TownLandmarksTests.cs b/unity/Assets/Tests/EditMode/TownLandmarksTests.csindex a14ae6783..e08de469b 100644--- a/unity/Assets/Tests/EditMode/TownLandmarksTests.cs+++ b/unity/Assets/Tests/EditMode/TownLandmarksTests.cs@@ -524,6 +524,79 @@ public class TownLandmarksTestsCollectionAssert.Contains(t.Missing, "tel_aviv");}+ /// <summary>#2099, as #2046 for the camp tents: the edit-mode render callback (the beginCameraRendering handler itself)+ /// never acquires, instantiates or destroys the whole-town landmarks mid-render. A change (here the Towns.Enabled kill+ /// switch) waits for LateUpdate, as in play mode, and once applied the next render finds nothing pending (it asks for no+ /// further player-loop update); a direct Choose (no render) still applies a change at once.</summary>+ [Test]+ public void AnEditModeRenderCallbackDefersTheWholeTownsToLateUpdate()+ {+ Assert.IsFalse(Application.isPlaying, "the edit-mode render path");+ var map = OpenMap();+ // Made after OpenScene(Single), which destroys every object of the scene it replaces.+ var prefab = GameObject.CreatePrimitive(PrimitiveType.Cube); prefab.name = "fake original town";+ var camera = new GameObject("deferred whole-town camera").AddComponent<Camera>();+ try+ {+ TownLandmarks.Request = (id, detail, done) => { asked.Add((id, detail, done)); done(prefab); };+ var t = TownLandmarks.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), ContentLoader.Load(Statecraft.Game.Paths.Content))!;+ Assert.Greater(t.Placed.Count, 0, "precondition: the whole towns stand");+ var first = t.transform.GetChild(0).gameObject;+ camera.transform.SetPositionAndRotation(new Vector3(0f, 60000f, 0f), Quaternion.Euler(90f, 0f, 0f));+ Render(t, camera);+ Assert.IsFalse(t.RefreshPending, "precondition: settled, a render finds nothing pending");+ var enabled = typeof(ProductionResidency.TownPolicy).GetField("Enabled", ResidencyFlags)!;++ enabled.SetValue(map.Residency.Towns, false);+ Render(t, camera);+ Assert.IsTrue(first != null, "nothing is destroyed inside the render callback");+ Assert.Greater(t.Placed.Count, 0, "the whole towns still stand");+ Assert.IsTrue(t.RefreshPending, "the change waits for LateUpdate");+ ResidencyCall(t, typeof(TownLandmarks), "LateUpdate");+ Assert.IsTrue(first == null, "LateUpdate retires the whole towns");+ Assert.AreEqual(0, t.Placed.Count, "and none stands");+ Render(t, camera);+ Assert.IsFalse(t.RefreshPending, "once applied, the next render finds nothing pending");++ enabled.SetValue(map.Residency.Towns, true); int before = asked.Count;+ t.Choose(default, camera);+ Assert.Greater(asked.Count, before, "a direct call (no render) requests at once");+ Assert.Greater(t.Placed.Count, 0, "and places them at once");+ Render(t, camera);+ Assert.IsFalse(t.RefreshPending, "and leaves nothing pending");+ }+ finally { Object.DestroyImmediate(camera.gameObject); Object.DestroyImmediate(prefab); }+ }++ /// <summary>#2099: a model that does not stream (its request answers null) is still a settled state: render, LateUpdate and+ /// render again find nothing pending, so an edit-mode render never asks for a player-loop update on every frame.</summary>+ [Test]+ public void AMissingWholeTownLeavesNothingPendingAfterARender()+ {+ var map = OpenMap();+ var camera = new GameObject("missing whole-town camera").AddComponent<Camera>();+ try+ {+ TownLandmarks.Request = (id, detail, done) => { asked.Add((id, detail, done)); done(null); };+ var t = TownLandmarks.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), ContentLoader.Load(Statecraft.Game.Paths.Content))!;+ Assert.Greater(asked.Count, 0, "precondition: the models were asked for");+ Assert.AreEqual(0, t.Placed.Count, "precondition: none streamed");+ CollectionAssert.IsNotEmpty(t.Missing, "precondition: the towns are listed as not drawn");+ camera.transform.SetPositionAndRotation(new Vector3(0f, 60000f, 0f), Quaternion.Euler(90f, 0f, 0f));+ Render(t, camera);+ Assert.IsFalse(t.RefreshPending, "a render finds nothing pending");+ ResidencyCall(t, typeof(TownLandmarks), "LateUpdate");+ int count = asked.Count;+ Render(t, camera);+ Assert.IsFalse(t.RefreshPending, "nor after LateUpdate");+ Assert.AreEqual(count, asked.Count, "and nothing is asked for again");+ }+ finally { Object.DestroyImmediate(camera.gameObject); }+ }++ static void Render(TownLandmarks t, Camera camera) => ResidencyCall(t, typeof(TownLandmarks), "OnBeginCameraRendering",+ default(UnityEngine.Rendering.ScriptableRenderContext), camera);+const System.Reflection.BindingFlags ResidencyFlags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;static object? ResidencyCall(object? owner, Type type, string method, params object?[] args){diff --git a/unity/Assets/Tests/EditMode/TownModelResidencyTests.cs b/unity/Assets/Tests/EditMode/TownModelResidencyTests.csindex dca747d0a..ed86f3110 100644--- a/unity/Assets/Tests/EditMode/TownModelResidencyTests.cs+++ b/unity/Assets/Tests/EditMode/TownModelResidencyTests.cs@@ -1139,4 +1139,50 @@ public class TownModelResidencyTestsAssert.IsFalse(f.layer.AdmitsTown("p", camera), "4.5 km outside, not admitted before: beyond the 3 km admission margin");Assert.AreEqual(1, f.Requests[kind], "no new request outside the admission margin");}++ /// <summary>#2099, as #2046 for the camp tents: the edit-mode render callback (Submit, the beginCameraRendering handler+ /// itself) never acquires or retires building models mid-render. A change of demand only marks the layer, and LateUpdate+ /// reconciles it, as in play mode; once settled, the next render marks nothing. A direct PrepareCamera (no render) still+ /// reconciles at once.</summary>+ [Test]+ public void AnEditModeRenderCallbackDefersTheTownModelsToLateUpdate()+ {+ Assert.IsFalse(Application.isPlaying, "the edit-mode render path");+ const float HeightM = 10_000f, HalfM = 50f; // a straight-down 10 km view; the place is a 100 m box at the origin+ using var f = new ViewFixture(new[] { ViewFixture.Item("p", TownModel.B01WhiteCity, 0f, 0f) }, new[] { "p" },+ Array.Empty<(string, string[])>());+ string kind = TownModels.Ids[(int)TownModel.B01WhiteCity];+ var lateUpdate = typeof(TownModelLayer).GetMethod("LateUpdate", Flags)!;+ var dirty = typeof(TownModelLayer).GetField("reconcileDirty", Flags)!;+ var camera = f.Camera(new Vector3(0f, HeightM, 0f), Quaternion.LookRotation(Vector3.down, Vector3.forward));++ f.Submit(camera);+ Assert.IsTrue(f.layer.AdmitsTown("p", camera), "the close camera admits the place");+ Assert.IsFalse(f.Requests.ContainsKey(kind), "but nothing is acquired inside the render callback");+ Assert.IsTrue((bool)dirty.GetValue(f.layer)!, "the render marks the change for LateUpdate");+ lateUpdate.Invoke(f.layer, null);+ Assert.AreEqual(1, f.Requests[kind], "LateUpdate acquires the kind");+ f.Submit(camera);+ Assert.IsFalse((bool)dirty.GetValue(f.layer)!, "settled: the next render marks nothing (no update request every render)");++ // 7.5 km beyond the view's right edge: past the 6 km keep (AViewAdmittedPlaceStaysToSixKmOutsideTheViewAndNotBeyond).+ camera.transform.position = new Vector3(-HalfM - HeightM * Mathf.Tan(30f * Mathf.Deg2Rad) - 7500f, HeightM, 0f);+ f.Submit(camera); f.layer.RetireReleasedModels();+ Assert.IsFalse(f.layer.AdmitsTown("p", camera), "the camera no longer admits the place");+ Assert.IsFalse(f.Releases.ContainsKey(kind), "but nothing is released inside the render callback");+ lateUpdate.Invoke(f.layer, null); f.layer.RetireReleasedModels();+ Assert.AreEqual(1, f.Releases[kind], "LateUpdate releases the kind");++ camera.transform.position = new Vector3(0f, HeightM, 0f);+ f.layer.PrepareCamera(camera);+ Assert.AreEqual(2, f.Requests[kind], "a direct call (no render) acquires at once");+ }++ /// <summary>#2099: the deferred change is applied in LateUpdate, which edit mode runs only for an [ExecuteAlways] layer.</summary>+ [Test]+ public void TheDeferringLayersRunInEditMode()+ {+ foreach (var type in new[] { typeof(TownModelLayer), typeof(TownLandmarks), typeof(SpecialBuildingModels) })+ Assert.IsTrue(type.IsDefined(typeof(ExecuteAlways), false), type.Name + " is [ExecuteAlways]");+ }}