A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(visual): colour grade (Neutral tonemapper, warm balance, teal/amber split toning, saturation, contrast) and a gentle vignette
eyalgolan9603700a5677
diff --git a/unity/Assets/Scripts/Map/CameraRig.cs b/unity/Assets/Scripts/Map/CameraRig.csindex 0376ea3fa..bdb2467a7 100644--- a/unity/Assets/Scripts/Map/CameraRig.cs+++ b/unity/Assets/Scripts/Map/CameraRig.cs@@ -42,6 +42,7 @@ namespace Statecraft.Game.Mapvar vol = new GameObject("PostFX").AddComponent<Volume>(); vol.isGlobal = true;vol.profile = ScriptableObject.CreateInstance<VolumeProfile>();Volume = vol;+ MapGrade.Apply(vol.profile);var sun = MapLighting.FindSun();TeardownActions.Add(MapLighting.Capture(sun)); // first, so it runs last (review M1)MapLighting.Apply(sun);@@ -49,6 +50,7 @@ namespace Statecraft.Game.MapTeardownActions.Add(ShadowFit.Restore);TeardownActions.Add(TiltShift.Reset);TeardownActions.Add(VisualToggles.Register("tiltshift", on => TiltShift.Enabled = on));+ TeardownActions.Add(VisualToggles.Register("grade", on => MapGrade.SetActive(vol.profile, on)));if (TiltShift.OffRequested()) TiltShift.Enabled = false;initialised = true;Apply();diff --git a/unity/Assets/Scripts/Map/MapGrade.cs b/unity/Assets/Scripts/Map/MapGrade.csnew file mode 100644index 000000000..10e925312--- /dev/null+++ b/unity/Assets/Scripts/Map/MapGrade.cs@@ -0,0 +1,45 @@+#nullable enable+using UnityEngine;+using UnityEngine.Rendering;+using UnityEngine.Rendering.Universal;++namespace Statecraft.Game.Map+{+ /// <summary>The map's colour grade (research notes §1, §2.2 "Colour grading"): a Neutral tonemapper owned by the map (the+ /// pipeline assets' template profile already applied one; without any, the graded Negev clips about 2.5% of its+ /// pixels: GradeTests.TheSunlitDesertDoesNotClip), slightly brighter, more contrast and saturation, a warm white balance, teal shadows against amber+ /// highlights (the promo's complementary sea and land), and a gentle dark-navy vignette. LDR grading on both tiers: the+ /// tonemapper and one LUT in the uber pass.</summary>+ public static class MapGrade+ {+ /// <summary>Neutral, not ACES: it only rolls off highlights, so the sea's blue and the amber land keep their hue (plan Task 4).</summary>+ public const TonemappingMode Tonemapper = TonemappingMode.Neutral;+ public const float PostExposure = 0.15f, Contrast = 14f, Saturation = 16f, Temperature = 9f, Tint = 2f;+ public const float SplitBalance = -15f, VignetteIntensity = 0.26f, VignetteSmoothness = 0.45f;+ public static readonly Color SplitShadows = new Color(0.36f, 0.52f, 0.60f);+ public static readonly Color SplitHighlights = new Color(0.96f, 0.78f, 0.55f);+ public static readonly Color VignetteColour = new Color(0.05f, 0.06f, 0.10f);++ public static void Apply(VolumeProfile profile)+ {+ var tm = profile.Add<Tonemapping>(true); tm.mode.Override(Tonemapper);+ var ca = profile.Add<ColorAdjustments>(true);+ ca.postExposure.Override(PostExposure); ca.contrast.Override(Contrast); ca.saturation.Override(Saturation);+ ca.hueShift.Override(0f); ca.colorFilter.Override(Color.white);+ var wb = profile.Add<WhiteBalance>(true); wb.temperature.Override(Temperature); wb.tint.Override(Tint);+ var st = profile.Add<SplitToning>(true);+ st.shadows.Override(SplitShadows); st.highlights.Override(SplitHighlights); st.balance.Override(SplitBalance);+ var v = profile.Add<Vignette>(true);+ v.intensity.Override(VignetteIntensity); v.smoothness.Override(VignetteSmoothness); v.color.Override(VignetteColour);+ v.center.Override(new Vector2(0.5f, 0.5f)); v.rounded.Override(false);+ }++ /// <summary>The "grade" toggle. Off falls back to the pipeline assets' own profile (Settings/SampleSceneProfile: Neutral+ /// tonemapping, bloom 0.25 above 1, a 0.2 black vignette), which every frame had before Task 4, not to a raw image.</summary>+ public static void SetActive(VolumeProfile profile, bool on)+ {+ foreach (var c in profile.components)+ if (c is Tonemapping || c is ColorAdjustments || c is WhiteBalance || c is SplitToning || c is Vignette) c.active = on;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/MapGrade.cs.meta b/unity/Assets/Scripts/Map/MapGrade.cs.metanew file mode 100644index 000000000..9ead9eca7--- /dev/null+++ b/unity/Assets/Scripts/Map/MapGrade.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f970467f68675489aba6f501a93faeaa\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/MapLighting.cs b/unity/Assets/Scripts/Map/MapLighting.csindex 9606d246a..87efe06fe 100644--- a/unity/Assets/Scripts/Map/MapLighting.cs+++ b/unity/Assets/Scripts/Map/MapLighting.cs@@ -56,7 +56,9 @@ namespace Statecraft.Game.Map}/// <summary>Points, colours and enables shadows on <paramref name="sun"/> (when there is one) and sets the trilight- /// ambient and its probe.</summary>+ /// ambient. Unity converts the three (sRGB) colours to the linear SH probe the shaders read, at once, in the editor+ /// and in the WebGL player; a probe assigned in Trilight mode is replaced by that conversion (Task 4, review M4), so+ /// the colours are the only input.</summary>public static void Apply(Light? sun){if (sun != null)@@ -69,23 +71,6 @@ namespace Statecraft.Game.Map}RenderSettings.ambientMode = AmbientMode.Trilight;RenderSettings.ambientSkyColor = AmbientSky; RenderSettings.ambientEquatorColor = AmbientEquator; RenderSettings.ambientGroundColor = AmbientGround;- RenderSettings.ambientProbe = AmbientProbe();- }-- /// <summary>The trilight ambient as spherical harmonics (set explicitly: a runtime change of the trilight colours does- /// not rebuild the probe the shaders read). Review M4: this is an approximation, and the three colours are its- /// inputs, not what it evaluates to. Each AddDirectionalLight lobe also adds constant and linear terms in every- /// direction, and the ground lobe (darker than the equator) pulls the whole probe down. Evaluated, the probe is- /// darker than the constants everywhere; LightingTests.TheAmbientFillIsCoolFromTheSkyAndDarkFromTheGround pins the- /// evaluated up/horizon/down colours. The look was judged on these evaluated values, and Track B's render thresholds- /// were derived with them, so a least-squares refit is a look change for Task 4's grade, not a bug fix here.</summary>- public static SphericalHarmonicsL2 AmbientProbe()- {- var sh = new SphericalHarmonicsL2();- sh.AddAmbientLight(AmbientEquator);- sh.AddDirectionalLight(Vector3.up, AmbientSky - AmbientEquator, 1f);- sh.AddDirectionalLight(Vector3.down, AmbientGround - AmbientEquator, 1f);- return sh;}}}diff --git a/unity/Assets/Tests/EditMode/GradeTests.cs b/unity/Assets/Tests/EditMode/GradeTests.csnew file mode 100644index 000000000..57f80bad9--- /dev/null+++ b/unity/Assets/Tests/EditMode/GradeTests.cs@@ -0,0 +1,182 @@+#nullable enable+using System.Collections;+using NUnit.Framework;+using Statecraft.Game.Map;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.Rendering;+using UnityEngine.Rendering.Universal;+using UnityEngine.TestTools;++/// <summary>Plan Task 4: the grade, the tonemapper, the vignette, and what they do to readability.</summary>+public class GradeTests+{+ [TearDown]+ public void Reset() { EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); VisualToggles.Clear(); }++ static (MapScene map, CameraRig rig, VolumeProfile profile) Open()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();+ var rig = Camera.main.GetComponent<CameraRig>();+ return (map, rig, rig.Volume.profile);+ }++ [Test]+ public void TheGradeIsWarmLandTealShadowsAndAGentleVignette()+ {+ var (_, _, profile) = Open();+ Assert.IsTrue(profile.TryGet<ColorAdjustments>(out var ca));+ Assert.AreEqual(MapGrade.Saturation, ca.saturation.value); Assert.Greater(ca.contrast.value, 0f);+ Assert.IsTrue(profile.TryGet<WhiteBalance>(out var wb)); Assert.Greater(wb.temperature.value, 0f, "warm");+ Assert.IsTrue(profile.TryGet<SplitToning>(out var st));+ Assert.Greater(st.shadows.value.b, st.shadows.value.r, "teal shadows"); Assert.Greater(st.highlights.value.r, st.highlights.value.b, "amber highlights");+ Assert.IsTrue(profile.TryGet<Vignette>(out var v)); Assert.That(v.intensity.value, Is.InRange(0.2f, 0.35f));+ Assert.IsTrue(profile.TryGet<Tonemapping>(out var tm)); Assert.AreEqual(TonemappingMode.Neutral, tm.mode.value);+ CollectionAssert.Contains(VisualToggles.Names, "grade");+ // The runtime profile is invisible to URP's build-time post-processing stripping, which keeps the tonemapper's+ // uber-shader variants only when some VolumeProfile asset under Assets has a Tonemapping component (URP 17.3+ // ShaderBuildPreprocessor.GetSupportedFeaturesFromVolumes; strip-unused-post-processing is on). The pipeline assets'+ // own profile (Settings/SampleSceneProfile) has one; without it the WebGL player would silently drop Neutral.+ bool kept = false;+ foreach (var guid in AssetDatabase.FindAssets("t:VolumeProfile", new[] { "Assets" }))+ kept |= AssetDatabase.LoadAssetAtPath<VolumeProfile>(AssetDatabase.GUIDToAssetPath(guid))?.Has<Tonemapping>() == true;+ Assert.IsTrue(kept, "a VolumeProfile asset with Tonemapping keeps _TONEMAP_NEUTRAL in builds");+ }++ static HexJson NearestLandHex(MapScene map, double lon, double lat)+ {+ HexJson? best = null;+ foreach (var h in map.Hexes.hexes)+ if (h.land && h.biome != "lake" && (best == null || (h.lon - lon) * (h.lon - lon) + (h.lat - lat) * (h.lat - lat) < (best.lon - lon) * (best.lon - lon) + (best.lat - lat) * (best.lat - lat))) best = h;+ return best!;+ }++ /// <summary>Selects the land hex nearest (lon, lat) and returns world points on the band (the middle of its second edge,+ /// read from the band's own mesh, so it holds whatever height the band rides at) and on the land 1 km inside it.</summary>+ static (Vector3 band, Vector3 land) SelectNear(MapScene map, double lon, double lat)+ {+ var hex = NearestLandHex(map, lon, lat);+ map.Select(hex.q, hex.r);+ var sel = map.Terrain.transform.Find(MapScene.SelectionName);+ var v = sel.GetComponent<MeshFilter>().sharedMesh.vertices;+ int n = MapBuilder.RingVertices, j = MapBuilder.OverlaySegmentsPerEdge + MapBuilder.OverlaySegmentsPerEdge / 2;+ var band = sel.TransformPoint((v[j] + v[n + j]) / 2f);+ var centre = map.Frame.ToWorld(hex.lon, hex.lat, 0);+ var inward = new Vector3(centre.x - band.x, 0, centre.z - band.z).normalized;+ var land = new Vector3(band.x, 0, band.z) + inward * 1000f; land.y = map.Terrain.SampleHeight(land);+ return (band, land);+ }++ /// <summary>Review I9: the selected hex still reads on graded land, at both promo poses, graded and ungraded.</summary>+ [UnityTest]+ public IEnumerator TheSelectedHexStillStandsOutOnGradedLand()+ {+ var (map, rig, _) = Open();+ yield return null;+ var cam = Camera.main;+ VisualToggles.Set("tiltshift", false); // the band is a thin line: measured sharp, as LightingTests measures detail+ foreach (var pose in PromoPose.All)+ {+ pose.Apply(rig, map.Frame); rig.TopInset = 0f; rig.Apply();+ var (band, land) = SelectNear(map, pose.Lon, pose.Lat);+ foreach (var graded in new[] { true, false })+ {+ VisualToggles.Set("grade", graded);+ var px = new Vector2[2];+ var s = RenderSample.Render(cam, 960, 540, new[] { band, land }, px);+ Color b = s.At((int)px[0].x, (int)px[0].y), l = s.Mean((int)px[1].x, (int)px[1].y, 1);+ float de = RenderSample.DeltaE(b, l);+ TestContext.WriteLine($"{pose.Name} graded={graded}: band {b}, land {l}, deltaE {de:0.0}");+ Assert.GreaterOrEqual(de, 20f, $"{pose.Name} graded={graded}");+ }+ VisualToggles.Set("grade", true);+ }+ map.Select(-9999, -9999);+ }++ /// <summary>Review I9: colour-blind players. Under simulated deuteranopia and protanopia (Machado 2009, severity 1), at+ /// the gameplay pose: sea against land, the selection against land and the selection against sea stay at deltaE76 >= 15.+ /// (Borders are not drawn in visual v1; the art track's border task adds its colours here.)</summary>+ [UnityTest]+ public IEnumerator ColourBlindPlayersStillTellCoastAndSelectionApart()+ {+ var (map, rig, _) = Open();+ yield return null;+ var cam = Camera.main;+ VisualToggles.Set("tiltshift", false); // the band is a thin line: measured sharp+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0f; rig.Apply();+ var (band, land) = SelectNear(map, 34.86, 32.00);+ var sea = map.Frame.ToWorld(34.66, 32.00, 0); sea.y = map.Terrain.SampleHeight(sea);+ var px = new Vector2[3];+ var s = RenderSample.Render(cam, 960, 540, new[] { band, land, sea }, px);+ Color b = s.At((int)px[0].x, (int)px[0].y), l = s.Mean((int)px[1].x, (int)px[1].y, 1), w = s.Mean((int)px[2].x, (int)px[2].y, 2);+ foreach (var kind in new[] { RenderSample.Cvd.Deuteranopia, RenderSample.Cvd.Protanopia })+ {+ Color B = RenderSample.SimulateCvd(b, kind), L = RenderSample.SimulateCvd(l, kind), W = RenderSample.SimulateCvd(w, kind);+ float seaLand = RenderSample.DeltaE(W, L), selLand = RenderSample.DeltaE(B, L), selSea = RenderSample.DeltaE(B, W);+ TestContext.WriteLine($"{kind}: sea-land {seaLand:0.0}, selection-land {selLand:0.0}, selection-sea {selSea:0.0}");+ Assert.GreaterOrEqual(seaLand, 15f, $"{kind}: the coast");+ Assert.GreaterOrEqual(selLand, 15f, $"{kind}: the selection on land");+ Assert.GreaterOrEqual(selSea, 15f, $"{kind}: the selection against the sea");+ }+ map.Select(-9999, -9999);+ }++ /// <summary>Review I9: with the Neutral tonemapper the sunlit desert does not clip: in the Negev (34.9 E, 30.8 N, 60 km)+ /// and at the gameplay pose, under 1% of pixels have any channel at the top 8-bit step. The control: with the grade's+ /// tonemapper set to None (which also overrides the pipeline profile's Neutral) the graded Negev does clip.</summary>+ [UnityTest]+ public IEnumerator TheSunlitDesertDoesNotClip()+ {+ var (map, rig, profile) = Open();+ yield return null;+ var cam = Camera.main;+ foreach (var (name, lon, lat, distance) in new[] { ("Negev", 34.9, 30.8, 60000f), ("gameplay03", PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, PromoPose.Gameplay03.Distance) })+ {+ rig.LookAt = map.Frame.ToWorld(lon, lat, 0); rig.Distance = distance; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();+ var s = RenderSample.Render(cam, 480, 270);+ float clipped = s.FractionClipped(0.995f);+ TestContext.WriteLine($"{name}: clipped {clipped:P2}");+ Assert.Less(clipped, 0.01f, name);+ }+ Assert.IsTrue(profile.TryGet<Tonemapping>(out var tm));+ rig.LookAt = map.Frame.ToWorld(34.9, 30.8, 0); rig.Distance = 60000f; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();+ tm.mode.Override(TonemappingMode.None);+ float control = RenderSample.Render(cam, 480, 270).FractionClipped(0.995f);+ tm.mode.Override(MapGrade.Tonemapper);+ TestContext.WriteLine($"Negev without a tonemapper (control): clipped {control:P2}");+ Assert.Greater(control, 0.01f, "without the tonemapper the graded desert clips");+ }++ /// <summary>Rendered at the gameplay pose: the grade lifts mean saturation by at least 5%.</summary>+ [UnityTest]+ public IEnumerator TheGradeLiftsSaturation()+ {+ var (map, rig, _) = Open();+ yield return null;+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0f; rig.Apply();+ var cam = Camera.main;+ VisualToggles.Set("grade", false); var flat = RenderSample.Render(cam, 480, 270);+ VisualToggles.Set("grade", true); var graded = RenderSample.Render(cam, 480, 270);+ TestContext.WriteLine($"saturation {flat.MeanSaturation():0.000} -> {graded.MeanSaturation():0.000}");+ Assert.Greater(graded.MeanSaturation(), flat.MeanSaturation() * 1.05f);+ }++ /// <summary>Rendered: the vignette darkens the corners relative to the centre.</summary>+ [UnityTest]+ public IEnumerator TheVignetteDarkensTheCorners()+ {+ var (map, rig, profile) = Open();+ yield return null;+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0f; rig.Apply();+ var cam = Camera.main;+ profile.TryGet<Vignette>(out var v);+ v.active = false; var plain = RenderSample.Render(cam, 480, 270);+ v.active = true; var vignetted = RenderSample.Render(cam, 480, 270);+ float Ratio(RenderSample s) => s.MeanLuma(0f, 0f, 0.1f, 0.1f) / s.MeanLuma(0.45f, 0.45f, 0.55f, 0.55f);+ TestContext.WriteLine($"corner/centre {Ratio(plain):0.000} -> {Ratio(vignetted):0.000}");+ Assert.Less(Ratio(vignetted), Ratio(plain) * 0.9f);+ }+}diff --git a/unity/Assets/Tests/EditMode/GradeTests.cs.meta b/unity/Assets/Tests/EditMode/GradeTests.cs.metanew file mode 100644index 000000000..5d46554c3--- /dev/null+++ b/unity/Assets/Tests/EditMode/GradeTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 7ea0a5337ab9e4e8db01ff3803f07347\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/LightingTests.cs b/unity/Assets/Tests/EditMode/LightingTests.csindex 3b6e8511e..ab446c268 100644--- a/unity/Assets/Tests/EditMode/LightingTests.cs+++ b/unity/Assets/Tests/EditMode/LightingTests.cs@@ -49,16 +49,28 @@ public class LightingTestsAssert.Greater(c[0].b, c[0].r, "sky fill is cool");Assert.Greater(c[0].grayscale, c[1].grayscale + 0.05f, "brighter from above");Assert.AreEqual(AmbientMode.Trilight, RenderSettings.ambientMode);- // Review M4: the SH lobes leak into every direction, so the trilight constants are inputs, not the evaluated- // colours (MapLighting.AmbientProbe); print the evaluated up / horizon / down so the documented values are checked.+ // Review M4, closed in Task 4: the shaders read Unity's own trilight -> SH conversion of the three colours (the+ // RenderSettings.ambientProbe getter returns it, in the editor and in the WebGL player alike), and it holds linear+ // values. The trilight constants are sRGB, so comparing the evaluated probe with them directly made it look like 40%+ // of nominal. In sRGB the horizon is the equator colour; up and down are blended towards it (an L2 probe cannot+ // hold a sharp trilight). The evaluated linear values stay pinned so a change to the colours is a visible decision.var e = new Color[3]; RenderSettings.ambientProbe.Evaluate(new[] { Vector3.up, Vector3.right, Vector3.down }, e);- TestContext.WriteLine($"ambient evaluated up {e[0]} horizon {e[1]} down {e[2]}");+ TestContext.WriteLine($"ambient evaluated (linear) up {e[0]} horizon {e[1]} down {e[2]}; horizon sRGB {e[1].gamma}");var expected = new[] { new Color(0.216f, 0.255f, 0.326f), new Color(0.184f, 0.179f, 0.171f), new Color(0.119f, 0.103f, 0.080f) };for (int i = 0; i < 3; i++){Assert.AreEqual(expected[i].r, e[i].r, 0.01f, $"direction {i} r"); Assert.AreEqual(expected[i].g, e[i].g, 0.01f, $"direction {i} g");Assert.AreEqual(expected[i].b, e[i].b, 0.01f, $"direction {i} b");}+ var horizon = e[1].gamma;+ Assert.AreEqual(MapLighting.AmbientEquator.r, horizon.r, 0.05f, "horizon r (sRGB)"); Assert.AreEqual(MapLighting.AmbientEquator.g, horizon.g, 0.05f, "horizon g (sRGB)");+ Assert.AreEqual(MapLighting.AmbientEquator.b, horizon.b, 0.05f, "horizon b (sRGB)");+ // No explicit probe: one assigned in Trilight mode is replaced by the conversion at once (measured in Task 4).+ var custom = new SphericalHarmonicsL2(); custom.AddAmbientLight(Color.white);+ RenderSettings.ambientProbe = custom;+ var after = new Color[1]; RenderSettings.ambientProbe.Evaluate(new[] { Vector3.right }, after);+ Assert.AreEqual(e[1].r, after[0].r, 1e-4f, "an explicit probe does not stick in Trilight mode");+ Assert.IsNull(typeof(MapLighting).GetMethod("AmbientProbe"), "MapLighting sets the colours only");}/// <summary>Review I1: URP fades shadows by straight-line distance from the camera, starting at (1 - cascadeBorder) ofdiff --git a/unity/Assets/Tests/EditMode/SettlementTests.cs b/unity/Assets/Tests/EditMode/SettlementTests.csindex 66afafc29..a3da7b6c0 100644--- a/unity/Assets/Tests/EditMode/SettlementTests.cs+++ b/unity/Assets/Tests/EditMode/SettlementTests.cs@@ -379,6 +379,10 @@ public class MapSceneTestsEditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);var map = Object.FindFirstObjectByType<MapScene>();map.Build();+ // Visual v1 Task 4: measured before the grade. The grade is a per-pixel colour transform (plus a vignette that is flat+ // this close to the centre), so it cannot open a seam, but it roughly doubles the sea's sub-step mismatch between the+ // two shaders (0.008 -> 0.016 here). Track B's patch-mean version of this test should keep this line at the merge.+ VisualToggles.Set("grade", false);var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();var size = map.Terrain.terrainData.size;var rt = new RenderTexture(1600, 900, 24);