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(visual): a two-band tilt-shift as a half-resolution render-graph pass; the far-only Gaussian DoF is retired

eyalgolanc5d313246558
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index a10b4ed53..2a480d529 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -125,8 +125,33 @@ than its constants, which are inputs, not the evaluated colours. Evaluated value
0.72), equator (0.48, 0.46, 0.42), ground (0.26, 0.22, 0.17). The images were judged on the evaluated values, and Track
B's thresholds were derived with them, so a least-squares refit would be a look change for Task 4, not a fix here.
+## Task 3: tilt-shift
+Two bands, blurred by a half-resolution render-graph pass (`TiltShiftFeature` on both renderers, `Statecraft/TiltShift`):
+a separable 9-tap Gaussian whose radius is `TiltShift.Weight(y) * MaxRadiusUv` (10/1080 of the picture height), focus at
+the middle of the map area below the top bar, weakening to 35% from 60 km to the 250 km overview. URP's far-only
+Gaussian DoF is retired. Toggle: `tiltshift`. Tests (gradient-energy ratio, shifted / sharp, at the gameplay pose, 960x540):
+Mobile top 0.22, bottom 0.31, middle 1.00 (top at 1920x1080 0.21); PC top 0.16, bottom 0.24, middle 1.00 (top at
+1920x1080 0.15); TopInset 0.3: focus band 1.00, upper band 0.19.
+
+Profile (1920x1080, DPR 1, render scale 0.80, 3 interleaved runs per configuration):
+```
+headless (web_check.py)
+PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=2.10 spread_ms=0.14 median_p95_ms=3.00
+PROFILE summary visual=-tiltshift pose=gameplay03 runs=3 median_avg_ms=2.18 spread_ms=0.55 median_p95_ms=3.00
+PROFILE summary visual=all pose=diorama02 runs=3 median_avg_ms=10.07 spread_ms=0.53 median_p95_ms=11.00
+PROFILE summary visual=-tiltshift pose=diorama02 runs=3 median_avg_ms=9.59 spread_ms=0.59 median_p95_ms=10.00
+headed (headed.py profile --dpr 1)
+PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=1.86 spread_ms=0.13 median_p95_ms=3.00
+PROFILE summary visual=-tiltshift pose=gameplay03 runs=3 median_avg_ms=1.85 spread_ms=0.01 median_p95_ms=3.00
+PROFILE summary visual=all pose=diorama02 runs=3 median_avg_ms=9.57 spread_ms=0.30 median_p95_ms=10.00
+PROFILE summary visual=-tiltshift pose=diorama02 runs=3 median_avg_ms=9.50 spread_ms=0.16 median_p95_ms=10.00
+```
+Cost `median(all) - median(-tiltshift)`: headless -0.08 ms (gameplay03) and +0.48 ms (diorama02); headed +0.01 and
++0.07 ms. All are within the 1.5 ms budget before any spread allowance.
+
## Checkpoints
| Task | Name | Images | Owner verdict |
|---|---|---|---|
| 1 | t01-before | captures/visual/t01-before/*-compare*.png | (owner) |
| 2 | t02-light | captures/visual/t02-light/*-compare*.png | (owner) Note: at the new 6 km hero zoom the view is filled by the 600-1,800 m placeholder marker cubes, so judge the zoom range, not the close-up art, until the settlement art track replaces them. |
+| 3 | t03-tiltshift | captures/visual/t03-tiltshift/*-compare*.png | (owner) Note: the map labels are still world-space text, so they blur with the map in the top and bottom bands until Task 9 moves them to UI Toolkit. |
diff --git a/unity/Assets/Editor/PostFxAssets.cs b/unity/Assets/Editor/PostFxAssets.cs
new file mode 100644
index 000000000..a6c5ed15b
--- /dev/null
+++ b/unity/Assets/Editor/PostFxAssets.cs
@@ -0,0 +1,52 @@
+#nullable enable
+using System.Linq;
+using Statecraft.Game.Map;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.Rendering.Universal;
+
+namespace Statecraft.Game.EditorTools
+{
+ /// <summary>Creates TiltShift.mat and adds one active TiltShiftFeature using it to both URP renderers (web: Mobile, desktop:
+ /// PC). Idempotent. Adding a feature needs the renderer's feature list and its local-file-id map kept in step, as URP's own
+ /// renderer inspector does. Run headless:
+ /// Unity -batchmode -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.PostFxAssets.Create</summary>
+ public static class PostFxAssets
+ {
+ public static readonly string[] Renderers = { "Assets/Settings/Mobile_Renderer.asset", "Assets/Settings/PC_Renderer.asset" };
+
+ public static void Create()
+ {
+ var shader = Shader.Find("Statecraft/TiltShift") ?? throw new System.InvalidOperationException("shader not found: Statecraft/TiltShift");
+ var mat = AssetDatabase.LoadAssetAtPath<Material>(PostFxPaths.TiltShiftMaterial);
+ if (mat == null) { mat = new Material(shader); AssetDatabase.CreateAsset(mat, PostFxPaths.TiltShiftMaterial); }
+ else mat.shader = shader;
+ EditorUtility.SetDirty(mat);
+ foreach (var path in Renderers)
+ AddFeature(AssetDatabase.LoadAssetAtPath<UniversalRendererData>(path) ?? throw new System.IO.FileNotFoundException("renderer missing", path), mat);
+ AssetDatabase.SaveAssets();
+ }
+
+ static void AddFeature(ScriptableRendererData data, Material mat)
+ {
+ var feature = data.rendererFeatures.OfType<TiltShiftFeature>().FirstOrDefault();
+ if (feature == null)
+ {
+ feature = ScriptableObject.CreateInstance<TiltShiftFeature>();
+ feature.name = "TiltShift";
+ AssetDatabase.AddObjectToAsset(feature, data);
+ AssetDatabase.SaveAssetIfDirty(data);
+ AssetDatabase.TryGetGUIDAndLocalFileIdentifier(feature, out _, out long localId);
+ var so = new SerializedObject(data);
+ var features = so.FindProperty("m_RendererFeatures");
+ var map = so.FindProperty("m_RendererFeatureMap");
+ features.arraySize++; features.GetArrayElementAtIndex(features.arraySize - 1).objectReferenceValue = feature;
+ map.arraySize++; map.GetArrayElementAtIndex(map.arraySize - 1).longValue = localId;
+ so.ApplyModifiedPropertiesWithoutUndo();
+ }
+ feature.Material = mat;
+ feature.SetActive(true);
+ EditorUtility.SetDirty(feature); EditorUtility.SetDirty(data);
+ }
+ }
+}
diff --git a/unity/Assets/Editor/PostFxAssets.cs.meta b/unity/Assets/Editor/PostFxAssets.cs.meta
new file mode 100644
index 000000000..b1ca49b16
--- /dev/null
+++ b/unity/Assets/Editor/PostFxAssets.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 43a8a2d3bfe124624a4c47e86faf5ba7
\ No newline at end of file
diff --git a/unity/Assets/Materials/TiltShift.mat b/unity/Assets/Materials/TiltShift.mat
new file mode 100644
index 000000000..bf5ae9d47
--- /dev/null
+++ b/unity/Assets/Materials/TiltShift.mat
@@ -0,0 +1,30 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: TiltShift
+ m_Shader: {fileID: 4800000, guid: a7f4caca24b5e4901a1e8c86c891828e, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap: {}
+ disabledShaderPasses: []
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs: []
+ m_Ints: []
+ m_Floats: []
+ m_Colors: []
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/unity/Assets/Materials/TiltShift.mat.meta b/unity/Assets/Materials/TiltShift.mat.meta
new file mode 100644
index 000000000..67099b285
--- /dev/null
+++ b/unity/Assets/Materials/TiltShift.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 2e55b9998c63e4b0699efdc30fcf7d4b
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Scripts/Map/CameraRig.cs b/unity/Assets/Scripts/Map/CameraRig.cs
index 28c741c26..cb5d4683f 100644
--- a/unity/Assets/Scripts/Map/CameraRig.cs
+++ b/unity/Assets/Scripts/Map/CameraRig.cs
@@ -6,9 +6,8 @@ using UnityEngine.Rendering.Universal;
namespace Statecraft.Game.Map
{
- /// <summary>Diorama camera: fixed 50-degree pitch, 35-degree FOV, Gaussian far blur beyond the look-at point (tilt-shift look).
- /// Yaw turns the view around the look-at point (0 = looking north); CameraController drives LookAt, Distance and Yaw.
- /// Gaussian, not Bokeh: physical Bokeh DoF keeps everything sharp at 100 km focus distances.</summary>
+ /// <summary>Diorama camera: fixed 50-degree pitch, 35-degree FOV, a two-band tilt-shift (TiltShiftFeature) driven from Apply.
+ /// Yaw turns the view around the look-at point (0 = looking north); CameraController drives LookAt, Distance and Yaw.</summary>
public sealed class CameraRig : MonoBehaviour
{
public const float Pitch = 50f, Fov = 35f;
@@ -19,7 +18,6 @@ namespace Statecraft.Game.Map
/// <summary>The largest inset the projection applies (TopInset is clamped to it); at this pitch and FOV the top of
/// the view still looks down, so the sky never shows (MapSceneTests.TheCameraClearsToTheSeaColour).</summary>
public const float MaxTopInset = 0.5f;
- DepthOfField _dof;
/// <summary>Undo actions for state Init changes outside the rig (the URP asset's shadow distance...). MapScene.Build hands
/// them to the map's MapRuntimeAssets right after Init, so destroying the map undoes them.</summary>
@@ -43,14 +41,14 @@ namespace Statecraft.Game.Map
cam.GetUniversalAdditionalCameraData().renderPostProcessing = true;
var vol = new GameObject("PostFX").AddComponent<Volume>(); vol.isGlobal = true;
vol.profile = ScriptableObject.CreateInstance<VolumeProfile>();
- _dof = vol.profile.Add<DepthOfField>(true); _dof.mode.Override(DepthOfFieldMode.Gaussian);
- _dof.gaussianMaxRadius.Override(1.5f);
Volume = vol;
var sun = MapLighting.FindSun();
TeardownActions.Add(MapLighting.Capture(sun)); // first, so it runs last (review M1)
MapLighting.Apply(sun);
TeardownActions.Add(VisualToggles.Register("shadows", on => { var s = MapLighting.FindSun(); if (s != null) s.shadows = on ? LightShadows.Soft : LightShadows.None; }));
TeardownActions.Add(ShadowFit.Restore);
+ TeardownActions.Add(TiltShift.Reset);
+ TeardownActions.Add(VisualToggles.Register("tiltshift", on => TiltShift.Enabled = on));
initialised = true;
Apply();
}
@@ -59,7 +57,7 @@ namespace Statecraft.Game.Map
{
transform.rotation = Quaternion.Euler(Pitch, Yaw, 0);
transform.position = LookAt - transform.forward * Distance;
- if (_dof != null) { _dof.gaussianStart.Override(Distance * 1.05f); _dof.gaussianEnd.Override(Distance * 1.8f); }
+ TiltShift.Apply(TopInset, Distance);
ApplyProjection();
if (initialised) ShadowFit.Apply(GetComponent<Camera>()); // after the projection: the fit reads the corner rays
}
diff --git a/unity/Assets/Scripts/Map/TiltShift.cs b/unity/Assets/Scripts/Map/TiltShift.cs
new file mode 100644
index 000000000..a2421d6fd
--- /dev/null
+++ b/unity/Assets/Scripts/Map/TiltShift.cs
@@ -0,0 +1,55 @@
+#nullable enable
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>The tilt-shift band (plan Task 3; promo 03 blurs about the bottom 15% and top 20%). CameraRig.Apply calls
+ /// Apply every frame with the top bar's inset and the rig distance; TiltShiftFeature draws the blur while Enabled. The
+ /// radius is a share of the picture's height, so no pixel size is needed. Weight mirrors TiltWeight in TiltShift.shader.</summary>
+ public static class TiltShift
+ {
+ public static readonly int ParamsId = Shader.PropertyToID("_ScTiltShift");
+ public const float HalfWidth = 0.17f, Feather = 0.18f;
+ /// <summary>The largest blur radius as a share of the picture's height: 10 px of a 1080-line picture.</summary>
+ public const float MaxRadiusUv = 10f / 1080f;
+ public const float FullStrengthDistanceM = 60000f, MinStrength = 0.35f;
+ public static bool Enabled = true;
+
+ /// <summary>HLSL smoothstep(p.y, p.y + p.z, |y - p.x|).</summary>
+ public static float Weight(float y, Vector4 p)
+ {
+ float t = Mathf.Clamp01((Mathf.Abs(y - p.x) - p.y) / p.z);
+ return t * t * (3f - 2f * t);
+ }
+
+ /// <summary>The middle of the map area below a top bar covering <paramref name="topInset"/> of the screen.</summary>
+ public static float FocusCentre(float topInset) => (1f - Mathf.Clamp(topInset, 0f, CameraRig.MaxTopInset)) * 0.5f;
+
+ public static float Strength(float distance) =>
+ Mathf.Lerp(1f, MinStrength, Mathf.InverseLerp(FullStrengthDistanceM, CameraController.MaxDistance, distance));
+
+ public static Vector4 Params(float topInset, float distance) =>
+ new Vector4(FocusCentre(topInset), HalfWidth, Feather, MaxRadiusUv * Strength(distance));
+
+ public static void Apply(float topInset, float distance) => Shader.SetGlobalVector(ParamsId, Params(topInset, distance));
+
+ /// <summary>No band set: TiltShiftFeature draws nothing until the next Apply (a camera no rig drives, or the map torn
+ /// down), and the toggle is back on. CameraRig.Init hands it to the map's teardown.</summary>
+ public static void Reset()
+ {
+ Enabled = true;
+ Shader.SetGlobalVector(ParamsId, Vector4.zero);
+ }
+
+ /// <summary>True when a rig has set a band with a radius. With the zero global (before the map's first Apply, or after
+ /// its teardown) smoothstep(0, 0, |y|) is about 1 everywhere, so the composite would replace the whole frame with its
+ /// half-resolution copy at full cost.</summary>
+ public static bool HasBand => Shader.GetGlobalVector(ParamsId).w > 0f;
+ }
+
+ /// <summary>Asset paths the tests share with the editor scripts (tests cannot reference Assets/Editor).</summary>
+ public static class PostFxPaths
+ {
+ public const string TiltShiftMaterial = "Assets/Materials/TiltShift.mat";
+ }
+}
diff --git a/unity/Assets/Scripts/Map/TiltShift.cs.meta b/unity/Assets/Scripts/Map/TiltShift.cs.meta
new file mode 100644
index 000000000..218a13324
--- /dev/null
+++ b/unity/Assets/Scripts/Map/TiltShift.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1c8a26b750d8440f39d7d4f39159cb8d
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/TiltShiftFeature.cs b/unity/Assets/Scripts/Map/TiltShiftFeature.cs
new file mode 100644
index 000000000..62dd63d1a
--- /dev/null
+++ b/unity/Assets/Scripts/Map/TiltShiftFeature.cs
@@ -0,0 +1,69 @@
+#nullable enable
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+using UnityEngine.Rendering.Universal;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>The tilt-shift renderer feature (on both URP renderers, PostFxAssets.Create). Before URP's own post-processing
+ /// (so the grade and vignette apply on top): blur the camera colour horizontally into a 1/Downsample target, vertically
+ /// into a second one, then composite back with the band weight as alpha. Game cameras only.</summary>
+ public sealed class TiltShiftFeature : ScriptableRendererFeature
+ {
+ [SerializeField] Material? material;
+ [SerializeField, Range(1, 4)] int downsample = 2;
+ TiltShiftPass? pass;
+
+ public Material? Material { get => material; set => material = value; }
+ public int Downsample { get => downsample; set => downsample = Mathf.Clamp(value, 1, 4); }
+
+ public override void Create() =>
+ pass = new TiltShiftPass { renderPassEvent = RenderPassEvent.BeforeRenderingPostProcessing, requiresIntermediateTexture = true };
+
+ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
+ {
+ if (material == null || pass == null || !TiltShift.Enabled || !TiltShift.HasBand) return;
+ pass.Setup(material, downsample);
+ renderer.EnqueuePass(pass);
+ }
+ }
+
+ sealed class TiltShiftPass : ScriptableRenderPass
+ {
+ Material material = null!;
+ int downsample = 2;
+
+ sealed class PassData { public TextureHandle source; public Material material = null!; public int pass; }
+
+ public void Setup(Material m, int d) { material = m; downsample = d; }
+
+ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
+ {
+ var camera = frameData.Get<UniversalCameraData>();
+ var resources = frameData.Get<UniversalResourceData>();
+ if (camera.cameraType != CameraType.Game || resources.isActiveTargetBackBuffer) return;
+ var colour = resources.activeColorTexture;
+ var desc = renderGraph.GetTextureDesc(colour);
+ desc.sizeMode = TextureSizeMode.Explicit;
+ desc.width = Mathf.Max(1, desc.width / downsample); desc.height = Mathf.Max(1, desc.height / downsample);
+ desc.msaaSamples = MSAASamples.None; desc.clearBuffer = false;
+ desc.filterMode = FilterMode.Bilinear; desc.wrapMode = TextureWrapMode.Clamp;
+ desc.name = "TiltShiftA"; var a = renderGraph.CreateTexture(desc);
+ desc.name = "TiltShiftB"; var b = renderGraph.CreateTexture(desc);
+ Blit(renderGraph, "TiltShift Horizontal", colour, a, 0, AccessFlags.Write);
+ Blit(renderGraph, "TiltShift Vertical", a, b, 1, AccessFlags.Write);
+ Blit(renderGraph, "TiltShift Composite", b, colour, 2, AccessFlags.ReadWrite); // blends over the sharp frame
+ }
+
+ void Blit(RenderGraph graph, string name, TextureHandle source, TextureHandle target, int shaderPass, AccessFlags targetAccess)
+ {
+ using var builder = graph.AddRasterRenderPass<PassData>(name, out var data);
+ data.source = source; data.material = material; data.pass = shaderPass;
+ builder.UseTexture(source, AccessFlags.Read);
+ builder.SetRenderAttachment(target, 0, targetAccess);
+ builder.SetRenderFunc((PassData d, RasterGraphContext ctx) =>
+ Blitter.BlitTexture(ctx.cmd, d.source, new Vector4(1, 1, 0, 0), d.material, d.pass));
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/TiltShiftFeature.cs.meta b/unity/Assets/Scripts/Map/TiltShiftFeature.cs.meta
new file mode 100644
index 000000000..7dbcd6996
--- /dev/null
+++ b/unity/Assets/Scripts/Map/TiltShiftFeature.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 851d1613d1b594d1b88db2f3eba74604
\ No newline at end of file
diff --git a/unity/Assets/Settings/Mobile_Renderer.asset b/unity/Assets/Settings/Mobile_Renderer.asset
index ea246b259..577ca91a2 100644
--- a/unity/Assets/Settings/Mobile_Renderer.asset
+++ b/unity/Assets/Settings/Mobile_Renderer.asset
@@ -1,5 +1,20 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-6024354078132407002
+MonoBehaviour:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: 851d1613d1b594d1b88db2f3eba74604, type: 3}
+ m_Name: TiltShift
+ m_EditorClassIdentifier: Statecraft.Game::Statecraft.Game.Map.TiltShiftFeature
+ m_Active: 1
+ material: {fileID: 2100000, guid: 2e55b9998c63e4b0699efdc30fcf7d4b, type: 2}
+ downsample: 2
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
@@ -13,11 +28,9 @@ MonoBehaviour:
m_Name: Mobile_Renderer
m_EditorClassIdentifier:
debugShaders:
- debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7,
- type: 3}
+ debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7, type: 3}
hdrDebugViewPS: {fileID: 4800000, guid: 573620ae32aec764abd4d728906d2587, type: 3}
- probeVolumeSamplingDebugComputeShader: {fileID: 7200000, guid: 53626a513ea68ce47b59dc1299fe3959,
- type: 3}
+ probeVolumeSamplingDebugComputeShader: {fileID: 7200000, guid: 53626a513ea68ce47b59dc1299fe3959, type: 3}
probeVolumeResources:
probeVolumeDebugShader: {fileID: 0}
probeVolumeFragmentationDebugShader: {fileID: 0}
@@ -26,11 +39,16 @@ MonoBehaviour:
probeSamplingDebugMesh: {fileID: 0}
probeSamplingDebugTexture: {fileID: 0}
probeVolumeBlendStatesCS: {fileID: 0}
- m_RendererFeatures: []
- m_RendererFeatureMap:
+ m_RendererFeatures:
+ - {fileID: -6024354078132407002}
+ m_RendererFeatureMap: 26f5bd63e23165ac
m_UseNativeRenderPass: 1
+ xrSystemData: {fileID: 0}
postProcessData: {fileID: 11400000, guid: 41439944d30ece34e96484bdb6645b55, type: 2}
- m_AssetVersion: 2
+ m_AssetVersion: 3
+ m_PrepassLayerMask:
+ serializedVersion: 2
+ m_Bits: 4294967295
m_OpaqueLayerMask:
serializedVersion: 2
m_Bits: 4294967295
@@ -48,5 +66,7 @@ MonoBehaviour:
m_RenderingMode: 0
m_DepthPrimingMode: 0
m_CopyDepthMode: 0
+ m_DepthAttachmentFormat: 0
+ m_DepthTextureFormat: 0
m_AccurateGbufferNormals: 0
m_IntermediateTextureMode: 0
diff --git a/unity/Assets/Settings/PC_Renderer.asset b/unity/Assets/Settings/PC_Renderer.asset
index 475b02e55..b04a84800 100644
--- a/unity/Assets/Settings/PC_Renderer.asset
+++ b/unity/Assets/Settings/PC_Renderer.asset
@@ -1,5 +1,20 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-6041217640759497533
+MonoBehaviour:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: 851d1613d1b594d1b88db2f3eba74604, type: 3}
+ m_Name: TiltShift
+ m_EditorClassIdentifier: Statecraft.Game::Statecraft.Game.Map.TiltShiftFeature
+ m_Active: 1
+ material: {fileID: 2100000, guid: 2e55b9998c63e4b0699efdc30fcf7d4b, type: 2}
+ downsample: 2
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
@@ -13,32 +28,28 @@ MonoBehaviour:
m_Name: PC_Renderer
m_EditorClassIdentifier:
debugShaders:
- debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7,
- type: 3}
+ debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7, type: 3}
hdrDebugViewPS: {fileID: 4800000, guid: 573620ae32aec764abd4d728906d2587, type: 3}
- probeVolumeSamplingDebugComputeShader: {fileID: 7200000, guid: 53626a513ea68ce47b59dc1299fe3959,
- type: 3}
+ probeVolumeSamplingDebugComputeShader: {fileID: 7200000, guid: 53626a513ea68ce47b59dc1299fe3959, type: 3}
probeVolumeResources:
- probeVolumeDebugShader: {fileID: 4800000, guid: e5c6678ed2aaa91408dd3df699057aae,
- type: 3}
- probeVolumeFragmentationDebugShader: {fileID: 4800000, guid: 03cfc4915c15d504a9ed85ecc404e607,
- type: 3}
- probeVolumeOffsetDebugShader: {fileID: 4800000, guid: 53a11f4ebaebf4049b3638ef78dc9664,
- type: 3}
- probeVolumeSamplingDebugShader: {fileID: 4800000, guid: 8f96cd657dc40064aa21efcc7e50a2e7,
- type: 3}
- probeSamplingDebugMesh: {fileID: -3555484719484374845, guid: 57d7c4c16e2765b47a4d2069b311bffe,
- type: 3}
- probeSamplingDebugTexture: {fileID: 2800000, guid: 24ec0e140fb444a44ab96ee80844e18e,
- type: 3}
- probeVolumeBlendStatesCS: {fileID: 7200000, guid: b9a23f869c4fd45f19c5ada54dd82176,
- type: 3}
+ probeVolumeDebugShader: {fileID: 4800000, guid: e5c6678ed2aaa91408dd3df699057aae, type: 3}
+ probeVolumeFragmentationDebugShader: {fileID: 4800000, guid: 03cfc4915c15d504a9ed85ecc404e607, type: 3}
+ probeVolumeOffsetDebugShader: {fileID: 4800000, guid: 53a11f4ebaebf4049b3638ef78dc9664, type: 3}
+ probeVolumeSamplingDebugShader: {fileID: 4800000, guid: 8f96cd657dc40064aa21efcc7e50a2e7, type: 3}
+ probeSamplingDebugMesh: {fileID: -3555484719484374845, guid: 57d7c4c16e2765b47a4d2069b311bffe, type: 3}
+ probeSamplingDebugTexture: {fileID: 2800000, guid: 24ec0e140fb444a44ab96ee80844e18e, type: 3}
+ probeVolumeBlendStatesCS: {fileID: 7200000, guid: b9a23f869c4fd45f19c5ada54dd82176, type: 3}
m_RendererFeatures:
- {fileID: 7833122117494664109}
- m_RendererFeatureMap: ad6b866f10d7b46c
+ - {fileID: -6041217640759497533}
+ m_RendererFeatureMap: ad6b866f10d7b46cc3ecb43f904829ac
m_UseNativeRenderPass: 1
+ xrSystemData: {fileID: 0}
postProcessData: {fileID: 11400000, guid: 41439944d30ece34e96484bdb6645b55, type: 2}
- m_AssetVersion: 2
+ m_AssetVersion: 3
+ m_PrepassLayerMask:
+ serializedVersion: 2
+ m_Bits: 4294967295
m_OpaqueLayerMask:
serializedVersion: 2
m_Bits: 4294967295
@@ -56,6 +67,8 @@ MonoBehaviour:
m_RenderingMode: 2
m_DepthPrimingMode: 0
m_CopyDepthMode: 0
+ m_DepthAttachmentFormat: 0
+ m_DepthTextureFormat: 0
m_AccurateGbufferNormals: 0
m_IntermediateTextureMode: 0
--- !u!114 &7833122117494664109
@@ -84,12 +97,3 @@ MonoBehaviour:
BlurQuality: 0
Falloff: 100
SampleCount: -1
- m_BlueNoise256Textures:
- - {fileID: 2800000, guid: 36f118343fc974119bee3d09e2111500, type: 3}
- - {fileID: 2800000, guid: 4b7b083e6b6734e8bb2838b0b50a0bc8, type: 3}
- - {fileID: 2800000, guid: c06cc21c692f94f5fb5206247191eeee, type: 3}
- - {fileID: 2800000, guid: cb76dd40fa7654f9587f6a344f125c9a, type: 3}
- - {fileID: 2800000, guid: e32226222ff144b24bf3a5a451de54bc, type: 3}
- - {fileID: 2800000, guid: 3302065f671a8450b82c9ddf07426f3a, type: 3}
- - {fileID: 2800000, guid: 56a77a3e8d64f47b6afe9e3c95cb57d5, type: 3}
- m_Shader: {fileID: 4800000, guid: 0849e84e3d62649e8882e9d6f056a017, type: 3}
diff --git a/unity/Assets/Shaders/TiltShift.shader b/unity/Assets/Shaders/TiltShift.shader
new file mode 100644
index 000000000..25d133855
--- /dev/null
+++ b/unity/Assets/Shaders/TiltShift.shader
@@ -0,0 +1,70 @@
+// Two-band tilt-shift (plan Task 3). Pass 0 blurs horizontally from the camera colour into a half-resolution target,
+// pass 1 blurs that vertically, pass 2 composites it over the camera colour with the band weight as alpha. The radius at a
+// pixel is TiltWeight(y) * _ScTiltShift.w of the picture's height, so the focus band stays sharp and the blur grows
+// smoothly towards the top and bottom. The radius is a share of the picture's height (UV units). No depth texture: it runs on
+// the web tier.
+Shader "Statecraft/TiltShift"
+{
+ SubShader
+ {
+ Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }
+ ZWrite Off ZTest Always Cull Off
+ HLSLINCLUDE
+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl"
+
+ float4 _ScTiltShift; // x focus centre (viewport y, 0 = bottom), y sharp half-width, z feather, w max radius (share of height)
+
+ float TiltWeight(float y)
+ {
+ return smoothstep(_ScTiltShift.y, _ScTiltShift.y + _ScTiltShift.z, abs(y - _ScTiltShift.x));
+ }
+
+ half3 Sample(float2 uv) { return SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_LinearClamp, uv).rgb; }
+
+ // 9-tap Gaussian (sigma = 2 taps) whose tap spacing is a quarter of the local radius.
+ half3 Blur(float2 uv, float2 dir)
+ {
+ float r = TiltWeight(uv.y) * _ScTiltShift.w;
+ // r is a share of the picture's height; the horizontal step converts it with the aspect ratio, which the render
+ // scale does not change (review I4).
+ float2 s = dir * (r * 0.25) * float2(_ScreenParams.y / _ScreenParams.x, 1.0);
+ half3 c = Sample(uv) * 0.2270270;
+ c += (Sample(uv + s) + Sample(uv - s)) * 0.1945946;
+ c += (Sample(uv + 2.0 * s) + Sample(uv - 2.0 * s)) * 0.1216216;
+ c += (Sample(uv + 3.0 * s) + Sample(uv - 3.0 * s)) * 0.0540541;
+ c += (Sample(uv + 4.0 * s) + Sample(uv - 4.0 * s)) * 0.0162162;
+ return c;
+ }
+ ENDHLSL
+
+ Pass
+ {
+ Name "TiltShiftHorizontal"
+ HLSLPROGRAM
+ #pragma vertex Vert
+ #pragma fragment Frag
+ half4 Frag(Varyings i) : SV_Target { return half4(Blur(i.texcoord, float2(1, 0)), 1); }
+ ENDHLSL
+ }
+ Pass
+ {
+ Name "TiltShiftVertical"
+ HLSLPROGRAM
+ #pragma vertex Vert
+ #pragma fragment Frag
+ half4 Frag(Varyings i) : SV_Target { return half4(Blur(i.texcoord, float2(0, 1)), 1); }
+ ENDHLSL
+ }
+ Pass
+ {
+ Name "TiltShiftComposite"
+ Blend SrcAlpha OneMinusSrcAlpha
+ HLSLPROGRAM
+ #pragma vertex Vert
+ #pragma fragment Frag
+ half4 Frag(Varyings i) : SV_Target { return half4(Sample(i.texcoord), TiltWeight(i.texcoord.y)); }
+ ENDHLSL
+ }
+ }
+}
diff --git a/unity/Assets/Shaders/TiltShift.shader.meta b/unity/Assets/Shaders/TiltShift.shader.meta
new file mode 100644
index 000000000..986d71807
--- /dev/null
+++ b/unity/Assets/Shaders/TiltShift.shader.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: a7f4caca24b5e4901a1e8c86c891828e
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Tests/EditMode/SettlementTests.cs b/unity/Assets/Tests/EditMode/SettlementTests.cs
index 470e9ed0f..e2fbc1ba2 100644
--- a/unity/Assets/Tests/EditMode/SettlementTests.cs
+++ b/unity/Assets/Tests/EditMode/SettlementTests.cs
@@ -534,12 +534,12 @@ public class MapSceneTests
}
[Test]
- public void RebuildingDoesNotLeakDepthOfFieldComponents()
+ public void RebuildingDoesNotLeakVolumeComponents()
{
var map = NewMap(); map.Build();
- int after1 = Resources.FindObjectsOfTypeAll<DepthOfField>().Length;
+ int after1 = Resources.FindObjectsOfTypeAll<VolumeComponent>().Length;
map.Build(); map.Build();
- Assert.AreEqual(after1, Resources.FindObjectsOfTypeAll<DepthOfField>().Length);
+ Assert.AreEqual(after1, Resources.FindObjectsOfTypeAll<VolumeComponent>().Length);
}
[Test]
diff --git a/unity/Assets/Tests/EditMode/TiltShiftTests.cs b/unity/Assets/Tests/EditMode/TiltShiftTests.cs
new file mode 100644
index 000000000..87baa5e0a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TiltShiftTests.cs
@@ -0,0 +1,129 @@
+#nullable enable
+using System.Collections;
+using System.Linq;
+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 3: the two-band tilt-shift.</summary>
+public class TiltShiftTests
+{
+ static readonly Vector4 P = new Vector4(0.5f, 0.17f, 0.18f, 10f / 1080f);
+
+ [TearDown]
+ public void Reset()
+ {
+ TiltShift.Enabled = true;
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ VisualToggles.Clear();
+ }
+
+ [Test]
+ public void TheMiddleBandIsSharpAndBothEdgesBlur()
+ {
+ Assert.AreEqual(0f, TiltShift.Weight(0.5f, P));
+ Assert.AreEqual(0f, TiltShift.Weight(0.34f, P), 1e-6f, "inside the sharp half-width");
+ Assert.AreEqual(1f, TiltShift.Weight(0.0f, P)); Assert.AreEqual(1f, TiltShift.Weight(1.0f, P));
+ Assert.AreEqual(TiltShift.Weight(0.2f, P), TiltShift.Weight(0.8f, P), 1e-6f, "symmetric about the focus");
+ Assert.Greater(TiltShift.Weight(0.15f, P), TiltShift.Weight(0.25f, P), "stronger towards the edge");
+ }
+
+ [Test]
+ public void TheBlurIsResolutionIndependentAndFollowsTheTopBar()
+ {
+ Assert.AreEqual(0.5f, TiltShift.FocusCentre(0f));
+ Assert.AreEqual(0.45f, TiltShift.FocusCentre(0.1f), 1e-6f, "the middle of the map area below a 10% bar");
+ Assert.AreEqual(0.25f, TiltShift.FocusCentre(5f), 1e-6f, "clamped to CameraRig.MaxTopInset");
+ Assert.AreEqual(0.45f, TiltShift.Params(0.1f, 30000f).x, 1e-6f);
+ Assert.AreEqual(10f / 1080f, TiltShift.MaxRadiusUv, 1e-7f, "10 px of a 1080-line picture, whatever the window or render scale");
+ Assert.AreEqual(TiltShift.MaxRadiusUv, TiltShift.Params(0f, 30000f).w, 1e-7f, "full strength when close");
+ Assert.AreEqual(TiltShift.MaxRadiusUv * TiltShift.MinStrength, TiltShift.Params(0f, CameraController.MaxDistance).w, 1e-7f, "weakest at the overview");
+ }
+
+ [Test]
+ public void BothTiersRunTheTiltShiftAndTheFarBlurIsGone()
+ {
+ var mat = AssetDatabase.LoadAssetAtPath<Material>(PostFxPaths.TiltShiftMaterial);
+ Assert.IsNotNull(mat); Assert.AreEqual("Statecraft/TiltShift", mat.shader.name);
+ foreach (var path in new[] { "Assets/Settings/Mobile_Renderer.asset", "Assets/Settings/PC_Renderer.asset" })
+ {
+ var data = AssetDatabase.LoadAssetAtPath<UniversalRendererData>(path);
+ var f = data.rendererFeatures.OfType<TiltShiftFeature>().SingleOrDefault();
+ Assert.IsNotNull(f, path); Assert.IsTrue(f!.isActive, path);
+ // The same asset, compared by instance id: Unity can hand out two managed wrappers for one native object
+ // (seen for the PC renderer, the active one), so AreSame on the wrappers fails for the right asset.
+ Assert.IsNotNull(f.Material, path); Assert.AreEqual(mat.GetInstanceID(), f.Material!.GetInstanceID(), path);
+ }
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ Object.FindFirstObjectByType<MapScene>().Build();
+ Assert.IsFalse(Camera.main.GetComponent<CameraRig>().Volume.profile.Has<DepthOfField>(), "the far-only Gaussian DoF is retired");
+ CollectionAssert.Contains(VisualToggles.Names, "tiltshift");
+ }
+
+ [Test]
+ public void TheTiltShiftShaderCompilesForWebGL2() =>
+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(Shader.Find("Statecraft/TiltShift")));
+
+ /// <summary>Rendered on both tiers at the gameplay pose: local contrast in the top and bottom bands falls by at least
+ /// 40%, the middle band keeps at least 95% of it. (Thresholds leave room for the terrain and grade tracks: a blur
+ /// lowers gradient energy whatever the texture.)</summary>
+ [UnityTest]
+ public IEnumerator TheTopAndBottomBlurAndTheMiddleStaysSharpOnBothTiers()
+ {
+ int saved = QualitySettings.GetQualityLevel();
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
+ yield return null;
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();
+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0f; rig.Apply();
+ try
+ {
+ foreach (var level in new[] { 0, 1 })
+ {
+ QualitySettings.SetQualityLevel(level, true);
+ TiltShift.Apply(0f, rig.Distance);
+ TiltShift.Enabled = false; var sharp = RenderSample.Render(cam, 960, 540);
+ TiltShift.Enabled = true; var shifted = RenderSample.Render(cam, 960, 540);
+ float Ratio(float y0, float y1) => shifted.GradientEnergy(y0, y1) / sharp.GradientEnergy(y0, y1);
+ float top = Ratio(0.90f, 0.98f), bottom = Ratio(0.02f, 0.10f), middle = Ratio(0.46f, 0.54f);
+ TestContext.WriteLine($"{QualitySettings.names[level]}: top {top:0.00}, bottom {bottom:0.00}, middle {middle:0.00}");
+ Assert.Less(top, 0.6f, "top band blurred"); Assert.Less(bottom, 0.6f, "bottom band blurred");
+ Assert.Greater(middle, 0.95f, "middle band sharp");
+ // Review N6: the same blur at twice the resolution (the radius is a share of the picture's height).
+ TiltShift.Enabled = false; var sharpBig = RenderSample.Render(cam, 1920, 1080);
+ TiltShift.Enabled = true; var shiftedBig = RenderSample.Render(cam, 1920, 1080);
+ float topBig = shiftedBig.GradientEnergy(0.90f, 0.98f) / sharpBig.GradientEnergy(0.90f, 0.98f);
+ TestContext.WriteLine($"{QualitySettings.names[level]}: top at 1920x1080 {topBig:0.00}");
+ Assert.AreEqual(top, topBig, 0.1f, "the top band loses the same share of its detail at 1080 lines as at 540");
+ }
+ }
+ finally { QualitySettings.SetQualityLevel(saved, true); }
+ }
+
+ /// <summary>Review I4: an asymmetric case, so a vertically flipped composite or a focus that ignores the top bar fails.
+ /// With TopInset 0.3 the focus is at 0.35: the band around 0.35 stays sharp, and 0.70-0.78 (sharp when the focus is at
+ /// 0.5) is blurred.</summary>
+ [UnityTest]
+ public IEnumerator AnOffCentreFocusFollowsTheTopBar()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
+ yield return null;
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();
+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0.3f; rig.Apply();
+ Assert.AreEqual(0.35f, Shader.GetGlobalVector(TiltShift.ParamsId).x, 1e-5f, "CameraRig.Apply passes the inset");
+ TiltShift.Enabled = false; var sharp = RenderSample.Render(cam, 960, 540);
+ TiltShift.Enabled = true; var shifted = RenderSample.Render(cam, 960, 540);
+ float Ratio(float y0, float y1) => shifted.GradientEnergy(y0, y1) / sharp.GradientEnergy(y0, y1);
+ float focus = Ratio(0.33f, 0.37f), upper = Ratio(0.70f, 0.78f);
+ TestContext.WriteLine($"focus band {focus:0.00}, upper band {upper:0.00}");
+ Assert.Greater(focus, 0.95f, "sharp at the inset's focus (0.35)");
+ Assert.Less(upper, 0.8f, "blurred above it");
+ rig.TopInset = 0f; rig.Apply();
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/TiltShiftTests.cs.meta b/unity/Assets/Tests/EditMode/TiltShiftTests.cs.meta
new file mode 100644
index 000000000..6dd69f61b
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TiltShiftTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1d10f8a5e532e481694b83445596ce6d
\ No newline at end of file