A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: an opt-in construction reveal prototype (dust and bouncing stones) with a one-hex editor preview (#1212)
pixelrenderai-hashecd4acc4639c
diff --git a/.gitignore b/.gitignoreindex 4238aefaf..67124af02 100644--- a/.gitignore+++ b/.gitignore@@ -83,3 +83,11 @@ Unity_v*.alf.idea/unity/obj/unity/MemoryCaptures/++# Existing local hex art used by opt-in previews; source/licence review stays with its asset batch.+unity/Assets/Art/Settlements/Prototype/HexSandboxModels/+unity/Assets/Art/Settlements/Prototype/HexSandboxModels.meta+unity/Assets/Art/Settlements/Prototype/HexSandboxGround/+unity/Assets/Art/Settlements/Prototype/HexSandboxGround.meta+unity/Assets/Art/Settlements/Prototype/Resources/+unity/Assets/Art/Settlements/Prototype/Resources.metadiff --git a/changelog.d/construction-dust-20261020.md b/changelog.d/construction-dust-20261020.mdnew file mode 100644index 000000000..8b569f206--- /dev/null+++ b/changelog.d/construction-dust-20261020.md@@ -0,0 +1 @@+- An opt-in construction reveal prototype and isolated one-hex editor preview: soft base dust, small bouncing stone chunks, original/refined comparison on an existing designed game hex, replay and cancellation, without changing simulation timing. Its materials stay in the editor until gameplay uses it, so player builds carry no new assets.diff --git a/docs/prototypes/construction-reveal.md b/docs/prototypes/construction-reveal.mdnew file mode 100644index 000000000..889a7e33c--- /dev/null+++ b/docs/prototypes/construction-reveal.md@@ -0,0 +1,148 @@+# One-hex construction reveal prototype++Opt-in presentation prototype. No gameplay flow invokes it; simulation timing, picking and completion identity remain unchanged.++## Direction++Three lightweight directions were considered:++1. **Perimeter**: low soft dust ring, a few earth chunks, intact building rises and settles. Selected for a readable silhouette and short reveal.+2. **Staggered**: dust groups and rise start later, suggesting assembly without splitting existing art. Available as a timing preset.+3. **Cloud**: wider expanding dust, crisp reveal. Available as a restrained intensity/width preset, at the cost of more cover at the base.++The refined default retains the original dust material and radial softness. Eight small faceted stones pop out in short arcs,+make two diminishing bounces, then shrink away. A smaller completion dust pulse and gentle building settle connect the action.+The comparison selector preserves the original v1 sampling on the **same real game hex**; it does not substitute the old diagnostic polygon.++## Preview++Open this worktree's `unity/` with **Unity 6000.3.25f1**, then **Statecraft > Construction > One Hex Preview**.+No Map scene, simulation, network or full board is started. The tool builds the existing `central_israel` hex at q=1, r=13+(`moshava_village`) using `HexBoardBuilder`, `HexBoardSurface`, `HexPrototypes` and `HexBoardRenderer`.+Its existing terrain paint, main street and prop placements are retained. Immediate neighbouring ground descriptors preserve+terrain continuity; only the selected hex's props are drawn. One existing roofed `sandbox:kit_moshava_2` house receives the reveal.+The game renderer owns the generated terrain/meshes/materials. Closing the private preview disposes them without changing the active scene.++Local game hex art remains in its existing ignored folders. It is not copied into Git or relicensed by this prototype.+When a local model is unavailable, the game's existing stand-in is shown and the preview reports the missing model count.+Ground textures are read without changing importers. The preview uses the game sun, camera pitch and FOV, without the global post-processing profile.++**Play / Replay** restarts; **Stop / Final** restores the completed model. Comparison (**Original / Stones**), direction,+duration, dust intensity, visual seed, speed and scrub support iteration. **Gameplay zoom** uses the existing hex capture's+26,000 m mid distance; **Tile zoom** frames the composition; **Close zoom** inspects the selected building at 5,980 m.++Default duration is 1.8 seconds: anticipation through 0.22s, rise through about 0.92s, completion pulse and short settle,+then clear. These are local visual values, not construction rules or turn durations. Completion never gates game state.++## Integration boundary++PR [#1146](https://github.com/eyalgolan/statecraft-israel/pull/1146) owns completed-city-project presentation in+`GameRoot.RenderPlacementsIfChanged` and `PlacementLayer.Render`; hex-map PRs #1153–#1155 own their board builders.+This prototype changes none of those files. Other runtime-figure and building-LOD experiments remain separate.++Until a gameplay caller exists, the Dust and Stone materials and their shaders live under+`unity/Assets/Editor/Construction/Materials/`, so player builds carry none of them. `ConstructionReveal` asks for them+through its static `Templates` loader, which only the editor sets (`ConstructionMaterials`). Wiring the reveal in means+setting `Templates` to load them when the opt-in is on, never from a `Resources` folder, which Unity packs into every build.++After the completed-visual flow settles, diff stable placement/project IDs following authoritative state updates. On a newly+completed visual, put `ConstructionReveal` on its stationary pick root and create a direct mesh-only child pivot, then call+`Bind(pivot, conservativeWorldFootprintRadius)` and `Play()`. Preserve the existing mesh, material and final transform.+Set `GroundOffset` to surface height minus the placed building base when the game intentionally sinks that base.+Keep at least **2.25 × radius** inside the tile's inset boundary. Do not wrap colliders, picking metadata or the whole placement layer.+Initial load, save restore, camera changes, streaming/LOD replacement and layer redraws must not replay completion effects;+keep completion identity independently of ephemeral render objects.++`Bind` restores the old target before reuse. `Cancel`, disabling, completion and destruction restore the final transform and clear particles.+Replay reuses its systems and owned resources. No coroutines, delayed callbacks, persistent objects, global RNG or global settings.+No project reduced-motion setting was found. Callers can skip `Play()` or call `Cancel()` to show the completed model immediately;+no global setting was invented.++## Rendering budget++Two native CPU ParticleSystems, at most **36 soft puffs + 8 mesh stones**. The stones share one eight-triangle mesh and one opaque material;+maximum added geometry is 136 triangles (72 dust + 64 stones), with two particle renderers. The original look uses 88 billboard triangles.+No rigidbodies, collision, persistent debris, trails, lights, sub-emitters, compute shaders, VFX Graph, new packages or textures.+The two tiny materials retain their URP shaders. Dust alpha blends with depth testing and no depth writes; stones depth-write.+Particles use Ignore Raycast and no colliders. Only the visual pivot rises; scale, pick root and collider remain fixed.+Sampling uses preallocated arrays and a local visual hash; it never consumes Unity's global RNG.++No managed allocations are introduced in sampled frames after initialization, by code inspection. GC/frame timing was not profiled.+Simultaneous completions still need an integration-level visibility/concurrency cap; this is a single-effect prototype.++## Validation and current evidence++Unity 6000.3.25f1 / URP, 20 October 2026:++- Focused native EditMode suite: **10 passed, 0 failed, 0 skipped**, 47.54 seconds; 0 C# compile warnings/errors.+ Includes all three deleted-particle-root/child recovery cases, whole-timeline bounds for every style/look,+ repeatability without global RNG consumption, stationary picking, replay/cancel/disable/completion/rebind/destruction,+ real game terrain and repeated private-preview disposal with scene/ambient/render-target/resource preservation.+- After the final roofed-house selector change, the native preview tests ran again: **2 passed, 0 failed, 0 skipped**,+ 29.33 seconds; 0 C# compile warnings/errors. Runtime code is unchanged from the full 10-case run.+- Native red first: 10 cases, 5 passed / 5 failed. Three failures reproduced the material leak and destroyed child accesses.+ Two failures caught an outer-row house whose conservative effect footprint did not fit the inset boundary.+ Recovery now rebuilds missing systems and renderer configuration while releasing the old dust material; the preview+ selects an existing roofed inner house without moving/resizing placements or weakening the containment guard.+- An independent Sol 6.1 reviewer verified the red/green XML and final code. No remaining code findings.+ The logs contain existing licensing/MCP shutdown noise; this is not an assertion that the entire log is error-free.+- .NET SDK 10.0.401: sim/content **2,023 passed**; Release warnings-as-errors build **0 warnings, 0 errors**.+ Policy tests **305 passed**; repository policy, GDD lint, rule-ID checks and whitespace checks passed.+- The CI-pinned Rasterio 1.5.2 could not install here without GDAL build tools. A compatible Rasterio 1.4.3 tools run had+ 1,430 passed / 4 SDK-8-related failures / 4 skipped; all 10 packaging tests passed when rerun directly with SDK 10.+ This is not a clean validation of the exact CI dependency environment.++The final actual real-hex capture completed on the existing roofed `kit_moshava_2`: 269 PNGs at 960×720/30 fps;+36 placements, zero missing models, 44 live particles observed at peak. The matched 6.4-second video includes normal+and close views. Cleared final frames are pixel-identical between looks. An independent Sol 6.1 reviewer inspected+the rise, dust, stone arcs and final frames: no remaining blockers, with the gameplay-scale subtlety noted.+The close view is retained so the restrained stones remain assessable. This is sampled visual review, not frame-time profiling.++| Final v2 (roofed source house) | Library ID | File ID |+| --- | --- | --- |+| construction-real-hex-v2.mp4 | libfile_562d7963c2b88191a408aa6b3873e271 | file_00000000aa2881f58e0e365c99236225 |+| construction-real-hex-v2.gif | libfile_8131a21a52788191bb9e7ca8283df687 | file_00000000687c81f58b0d0828ad4de6ae |+| construction-real-hex-keyframes.png | libfile_e82df7eb21848191b7d98fd95a6864bb | file_00000000a05881f5a0f7bb666b738b49 |+| construction-normal-comparison.png | libfile_85dd719f1d448191b756fe8c62839701 | file_00000000410881f5bbf86a34afca60f4 |+| construction-close-comparison.png | libfile_bcebb3fe246c8191b7620b7e88a13b7d | file_00000000af5481f5989afcd17dcd3749 |+| construction-real-hex-final.png | libfile_1486918ee84c8191b5a1bdda868fddd8 | file_00000000281881f5a158da05b02ecb07 |+| construction-final-identity.png | libfile_a5a0a99221dc81918aafc8f1d73763f5 | file_000000004c0881f59e2b4292170685f5 |+| evidence.json | libfile_8da70ef2d5f481919dfe9ba6a6f2b4ee | file_0000000075f881f5b24d6904014ff9b6 |++The initial v2 capture below used an unroofed source shell. Review prompted the final roofed selection without moving+or resizing placements, changing runtime motion, or weakening containment. The two candidate files remain available+for traceability; use the final v2 table above for the current result.++| Initial v2 candidate (unroofed source house) | Library ID | File ID |+| --- | --- | --- |+| construction-v2-framehouse-candidate.mp4 | libfile_8b8280b9c64481918df9c6752944119b | file_00000000ce1081f5b3447c8d3f58be85 |+| construction-v2-framehouse-candidate-keyframes.png | libfile_0661e7824bc48191869e537170ae75ba | file_00000000c1dc81f5ac71f0d75dc8a8f2 |++These actual candidate captures establish the earlier motion on the real hex; they are not final evidence for the roofed-house selection.+The preserved v1 media below shows the earlier diagnostic hex.++A one-hex desktop URP editor capture is not WebGL/browser validation. No construction WebGL build or performance profile+was run. Public screenshot sharing remains subject to the existing local sandbox art's provenance status; no new asset+rights declaration or legal attestation is made here.++## Preserved v1 evidence++These files are the earlier diagnostic-hex exploration, retained unchanged. Use the refined real-hex evidence above for the current result.++Library deliverables (actual rendered footage; no generated imagery):++| File | Library ID | File ID |+| --- | --- | --- |+| construction-reveal.mp4 | libfile_538b931ebfe8819198c59e2c65cb770f | file_00000000589c820c95467dc7b8f13bdd |+| construction-reveal.gif | libfile_db774cc5cc6481919e49eda4c9ed8c2a | file_000000006d7881f9a294a8c91d55e9c9 |+| construction-keyframes.png | libfile_03051b07c4488191a82030cbb636f0f0 | file_00000000432881f58375610a7f041649 |+| construction-original-final.png | libfile_e1f7fbc7943881919166e7c92b1daef4 | file_00000000076c81fda047dee9eb7a5c78 |+| construction-directions.png | libfile_45515109bbd8819199f57bf8479f46e1 | file_000000005e8c823081d699fdd375cebc |+++Capture entry point: `Statecraft.Editor.Construction.ConstructionPreview.Capture`, argument `-constructionCapture ABSOLUTE_DIRECTORY`.+Before Unity, inspect processes, atomically acquire `/tmp/statecraft-unity-validation.lock`, and wrap it in+`uv run tools/machine_lock.py --shared --wait-unity -- ...`. Do not launch competing Unity jobs.++AI assistance: Codex Sol 6.1 implemented the prototype, tests and notes; an independent Sol 6.1 agent verified the code,+native red/green XML and sampled final roofed-house capture sequence.diff --git a/unity/Assets/Editor/Construction.meta b/unity/Assets/Editor/Construction.metanew file mode 100644index 000000000..47758eeaf--- /dev/null+++ b/unity/Assets/Editor/Construction.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 01d8edf17bae443fa3fbba773b820694+folderAsset: yes+DefaultImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/ConstructionMaterials.cs b/unity/Assets/Editor/Construction/ConstructionMaterials.csnew file mode 100644index 000000000..af5a37f4e--- /dev/null+++ b/unity/Assets/Editor/Construction/ConstructionMaterials.cs@@ -0,0 +1,17 @@+#nullable enable+using Statecraft.Game.Map.Construction;+using UnityEditor;+using UnityEngine;++namespace Statecraft.Editor.Construction+{+ /// <summary>Gives the construction reveal its Dust and Stone template materials in the editor. They live under+ /// Assets/Editor, so player builds carry none of them until a gameplay caller loads them behind the opt-in.</summary>+ [InitializeOnLoad]+ static class ConstructionMaterials+ {+ public const string Folder = "Assets/Editor/Construction/Materials/";+ static ConstructionMaterials() =>+ ConstructionReveal.Templates = name => AssetDatabase.LoadAssetAtPath<Material>(Folder + name + ".mat");+ }+}diff --git a/unity/Assets/Editor/Construction/ConstructionMaterials.cs.meta b/unity/Assets/Editor/Construction/ConstructionMaterials.cs.metanew file mode 100644index 000000000..df0f31325--- /dev/null+++ b/unity/Assets/Editor/Construction/ConstructionMaterials.cs.meta@@ -0,0 +1,11 @@+fileFormatVersion: 2+guid: 63e1714816534c0c8d3b6122e3796e01+MonoImporter:+ externalObjects: {}+ serializedVersion: 2+ defaultReferences: []+ executionOrder: 0+ icon: {instanceID: 0}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/ConstructionPreview.cs b/unity/Assets/Editor/Construction/ConstructionPreview.csnew file mode 100644index 000000000..776a00f16--- /dev/null+++ b/unity/Assets/Editor/Construction/ConstructionPreview.cs@@ -0,0 +1,235 @@+#nullable enable+using System;+using System.IO;+using System.Linq;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Construction;+using Statecraft.HexTiles;+using UnityEditor;+using UnityEngine;+using Object = UnityEngine.Object;++namespace Statecraft.Editor.Construction+{+ /// <summary>One existing game hex, built by the game renderer in a private preview scene. No game/sim startup.</summary>+ public sealed class ConstructionStage : IDisposable+ {+ public const string BoardId = "central_israel", PrototypeId = "moshava_village";+ public const int BoardQ = 1, BoardR = 13;+ public const string BuildingModelId = "sandbox:kit_moshava_2";+ readonly PreviewRenderUtility preview = new PreviewRenderUtility();+ readonly GameObject root;+ public ConstructionReveal Reveal { get; }+ public Transform Visual { get; }+ public int PlacementCount { get; }+ public int MissingModels { get; }+ public Vector3 TargetPosition { get; }+ public Vector3 TileCentre { get; }+ public float Zoom = 0.56f;+ public const float TileRadius = HexScale.HexM;+ bool disposed;++ public ConstructionStage()+ {+ root = new GameObject("Construction real-hex preview"); preview.AddSingleGO(root);+ try+ {+ preview.camera.fieldOfView = 35f; preview.camera.nearClipPlane = 25f; preview.camera.farClipPlane = 100000f;+ preview.camera.clearFlags = CameraClearFlags.SolidColor;+ preview.camera.backgroundColor = new Color(0.13f, 0.20f, 0.18f);+ preview.ambientColor = MapLighting.AmbientEquator * 1.15f;+ preview.lights[0].transform.rotation = Quaternion.Euler(MapLighting.SunElevation, MapLighting.SunAzimuth - 180f, 0f);+ preview.lights[0].color = Color.Lerp(MapLighting.SunColour, new Color(1f, 0.88f, 0.70f), 0.35f);+ preview.lights[0].intensity = MapLighting.SunIntensity * HexLook.SunBoost;+ preview.lights[0].shadows = LightShadows.Soft;+ preview.lights[1].transform.rotation = Quaternion.Euler(65f, 145f, 0f);+ preview.lights[1].color = MapLighting.AmbientSky; preview.lights[1].intensity = 0.6f;++ // Preserve the actual board coordinates, so the prototype's seeded arrangement is unchanged.+ var original = HexBoard.Load(BoardId);+ var h = original.Hexes[(BoardQ, BoardR)];+ if (h.prototype != PrototypeId) throw new InvalidOperationException("The construction preview hex no longer has its expected prototype.");+ // Keep the real immediate ground neighbours; missing context would turn this into an island.+ var context = original.Hexes.Values.Where(x => HexGeometry.Distance(h.q, h.r, x.q, x.r) <= 1)+ .Select(x => x == h ? h : new BoardHex { q = x.q, r = x.r, terrain = x.terrain, ground = x.ground }).ToArray();+ var board = new HexBoard(new HexBoardFile { id = "construction-one-hex", hexes = context });+ var surface = new HexBoardSurface(board);+ var centre = HexGeometry.Centre(h.q, h.r, HexScale.HexM);+ var (boardRoot, _) = HexBoardBuilder.Build(board, Ground, seed: 1948,+ options: new HexBoardBuilder.Options { Parent = root.transform, Origin = -centre, OwnSea = false, HolesOutsideLand = true });+ var assets = boardRoot.GetComponent<HexBoardAssets>();+ TileCentre = new Vector3(0f, surface.Height(centre), 0f);+ var ctx = new HexTileContext(h.q, h.r, surface, seed: 1948);+ HexPrototypes.Create(h.prototype).Build(ctx);+ PlacementCount = ctx.Placements.Count;+ MissingModels = ctx.Placements.Count(p => p.Model != "" && HexModels.Prefab(HexModels.Resolve(p.Model, p.Position)) == null);+ // Use an existing roofed inner house: edge houses leave too little room for the dust footprint.+ var chosen = ctx.Placements.Where(p => p.Model == BuildingModelId)+ .OrderBy(p => (p.Position - centre).sqrMagnitude).ThenBy(p => p.Position.x).First();++ // Only split this preview's combined render objects; their meshes remain owned by HexBoardAssets.+ Object.DestroyImmediate(boardRoot.transform.Find("HexBoardPieces").gameObject);+ HexBoardRenderer.Emit(boardRoot.transform, ctx.Placements.Where(p => !p.Equals(chosen)), assets);+ var host = new GameObject("Building pick root"); host.transform.SetParent(boardRoot.transform, false);+ host.transform.localPosition = chosen.Position;+ Visual = new GameObject("Mesh-only visual pivot").transform; Visual.SetParent(host.transform, false);+ var rebased = new HexPlacement(chosen.Model, chosen.StandIn, chosen.Fit, chosen.Tint,+ Matrix4x4.Translate(-chosen.Position) * chosen.Matrix, chosen.Q, chosen.R);+ HexBoardRenderer.Emit(Visual, new[] { rebased }, assets);+ var bounds = HexModels.Bounds(Visual.gameObject);+ float radius = new Vector2(bounds.size.x, bounds.size.z).magnitude * 0.5f;+ if (!HexGeometry.InHex(chosen.Position, centre, HexScale.HexM, HexScale.HexM * HexScale.InsetShare + radius * 2.25f))+ throw new InvalidOperationException($"The chosen building has insufficient inset ground: offset={chosen.Position - centre}, radius={radius}, bounds={bounds.size}.");+ var pick = host.AddComponent<BoxCollider>(); pick.center = host.transform.InverseTransformPoint(bounds.center); pick.size = bounds.size;+ Reveal = host.AddComponent<ConstructionReveal>(); Reveal.Bind(Visual, radius);+ Reveal.GroundOffset = Mathf.Max(0f, surface.Height(chosen.Position) - chosen.Position.y);+ TargetPosition = host.transform.position;+ }+ catch { preview.Cleanup(); throw; }+ }++ static (Texture2D?, Texture2D?) Ground(string name)+ {+ const string folder = "Assets/Art/Settlements/Prototype/HexSandboxGround/";+ return (AssetDatabase.LoadAssetAtPath<Texture2D>(folder + name + "_diff_2k.jpg"),+ AssetDatabase.LoadAssetAtPath<Texture2D>(folder + name + "_nor_gl_2k.jpg"));+ }+ void PositionCamera()+ {+ var cam = preview.camera; cam.transform.rotation = Quaternion.Euler(50f, 22f, 0f);+ var at = Zoom < 0.4f ? TargetPosition + Vector3.up * Reveal.FootprintRadius * 0.35f : TileCentre;+ cam.transform.position = at - cam.transform.forward * (26000f * Zoom);+ }+ public void Draw(Rect rect)+ {+ PositionCamera(); preview.BeginPreview(rect, GUIStyle.none); preview.Render(true);+ GUI.DrawTexture(rect, preview.EndPreview(), ScaleMode.ScaleToFit);+ }+ public Texture2D Frame(int width, int height)+ {+ PositionCamera(); preview.BeginStaticPreview(new Rect(0, 0, width, height)); preview.Render(true);+ return preview.EndStaticPreview();+ }+ public void Dispose()+ {+ if (disposed) return; disposed = true;+ if (Reveal != null) Reveal.Cancel(); preview.Cleanup();+ }+ }+ public sealed class ConstructionPreview : EditorWindow+ {+ ConstructionStage? stage; bool playing; float time; double last;+ [MenuItem("Statecraft/Construction/One Hex Preview")]+ public static void Open() => GetWindow<ConstructionPreview>("Construction reveal");+ void OnEnable() { stage = new ConstructionStage(); last = EditorApplication.timeSinceStartup; EditorApplication.update += Tick; }+ void OnDisable() { EditorApplication.update -= Tick; stage?.Dispose(); stage = null; }+ void Tick()+ {+ double now = EditorApplication.timeSinceStartup;+ if (playing && stage != null)+ {+ time += (float)Math.Min(now - last, 0.1) * stage.Reveal.Speed;+ stage.Reveal.Sample(time); if (time >= stage.Reveal.Duration) playing = false; Repaint();+ }+ last = now;+ }+ void OnGUI()+ {+ if (stage == null) return;+ var fx = stage.Reveal;+ EditorGUILayout.LabelField("ONE HEX / CONSTRUCTION", EditorStyles.boldLabel);+ EditorGUILayout.LabelField("Actual moshava_village hex · game terrain and placements · no simulation", EditorStyles.miniLabel);+ using (new EditorGUILayout.HorizontalScope())+ {+ if (GUILayout.Button("Play / Replay")) { fx.Play(); time = 0f; playing = true; }+ if (GUILayout.Button("Stop / Final")) { fx.Cancel(); time = fx.Duration; playing = false; }+ if (GUILayout.Button("Close zoom")) stage.Zoom = 0.23f;+ if (GUILayout.Button("Tile zoom")) stage.Zoom = 0.56f;+ if (GUILayout.Button("Gameplay zoom")) stage.Zoom = 1f;+ }+ EditorGUI.BeginChangeCheck();+ fx.Look = (ConstructionLook)EditorGUILayout.EnumPopup("Comparison", fx.Look);+ fx.Style = (RevealStyle)EditorGUILayout.EnumPopup("Direction", fx.Style);+ fx.Duration = EditorGUILayout.Slider("Duration (seconds)", fx.Duration, 0.6f, 4f);+ fx.Intensity = EditorGUILayout.Slider("Dust intensity", fx.Intensity, 0f, 1.5f);+ fx.Speed = EditorGUILayout.Slider("Playback speed", fx.Speed, 0.1f, 3f);+ fx.Seed = EditorGUILayout.IntField("Visual seed", fx.Seed);+ time = EditorGUILayout.Slider("Scrub", time, 0f, fx.Duration);+ if (EditorGUI.EndChangeCheck()) fx.Sample(time);+ if (stage.MissingModels > 0) EditorGUILayout.HelpBox($"{stage.MissingModels} local game models are unavailable; existing game stand-ins are shown.", MessageType.Info);+ var rect = GUILayoutUtility.GetRect(100, 10000, 100, 10000, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));+ if (Event.current.type == EventType.Repaint && rect.width > 0 && rect.height > 0)+ {+ stage.Draw(rect);+ }+ }++ // Unity -batchmode ... -executeMethod Statecraft.Editor.Construction.ConstructionPreview.Capture+ static string PendingCapture => Path.GetFullPath(Path.Combine(Application.dataPath, "../Library/ConstructionCapture.pending.txt"));+ static double readySince;++ // The worktree-local marker survives MCP-triggered assembly reloads before the renderer is ready.+ // Capture itself is synchronous: Unity cannot reload halfway through its frame loop.+ [InitializeOnLoadMethod]+ static void ResumePendingCapture()+ {+ if (!File.Exists(PendingCapture)) return;+ readySince = 0;+ EditorApplication.update -= WaitForCapture;+ EditorApplication.update += WaitForCapture;+ }+ static void WaitForCapture()+ {+ if (EditorApplication.isCompiling || EditorApplication.isUpdating) { readySince = 0; return; }+ double now = EditorApplication.timeSinceStartup;+ if (readySince == 0) { readySince = now; return; }+ if (now - readySince < 1.5) return;+ EditorApplication.update -= WaitForCapture;+ CaptureNow(File.ReadAllText(PendingCapture));+ }+ public static void Capture()+ {+ string output = Path.GetFullPath(Path.Combine(Application.dataPath, "../../asset-staging/ui-local/construction"));+ var args = Environment.GetCommandLineArgs();+ for (int i = 0; i < args.Length - 1; i++) if (args[i] == "-constructionCapture") output = Path.GetFullPath(args[i + 1]);+ Directory.CreateDirectory(Path.GetDirectoryName(PendingCapture)!);+ File.WriteAllText(PendingCapture, output);+ ResumePendingCapture();+ }+ static void CaptureNow(string output)+ {+ try+ {+ Directory.CreateDirectory(output);+ using var stage = new ConstructionStage();+ void Save(string file) { var image = stage.Frame(960, 720); File.WriteAllBytes(Path.Combine(output, file), image.EncodeToPNG()); Object.DestroyImmediate(image); }+ int peak = 0;+ foreach (var view in new[] { "normal", "close" })+ {+ stage.Zoom = view == "normal" ? 1f : 0.23f;+ foreach (ConstructionLook look in Enum.GetValues(typeof(ConstructionLook)))+ {+ stage.Reveal.Look = look; stage.Reveal.Play();+ for (int i = 0; i <= 66; i++)+ {+ stage.Reveal.Sample(i / 30f); Save($"{view}-{look.ToString().ToLowerInvariant()}-{i:0000}.png");+ int live = 0; foreach (var ps in stage.Reveal.GetComponentsInChildren<ParticleSystem>()) live += ps.particleCount;+ peak = Math.Max(peak, live);+ }+ }+ }+ stage.Zoom = 0.56f; stage.Reveal.Cancel(); Save("real-tile-final.png");+ File.WriteAllText(Path.Combine(output, "capture-info.txt"),+ $"Actual Unity 6000.3.25f1 URP editor rendering. 960x720, 30fps.\n" ++ $"Existing board={ConstructionStage.BoardId}, prototype={ConstructionStage.PrototypeId}, q={ConstructionStage.BoardQ}, r={ConstructionStage.BoardR}, model={ConstructionStage.BuildingModelId}, seed=1948, placements={stage.PlacementCount}, missing models={stage.MissingModels}.\n" ++ $"Original v1 vs Stones on same tile/camera. Normal distance=26000m; close=5980m.\n" ++ $"Two systems, 36 soft puffs + 8 faceted mesh stones maximum; peak={peak}. Duration=1.8 seconds.\n" ++ "No simulation loaded. No WebGL build run. Preview uses game sun constants and camera pitch/FOV, without the global post-processing profile.\n");+ stage.Dispose();+ File.Delete(PendingCapture);+ Debug.Log("CONSTRUCTION CAPTURE OK " + output); if (Application.isBatchMode) EditorApplication.Exit(0);+ }+ catch (Exception e) { File.Delete(PendingCapture); Debug.LogException(e); if (Application.isBatchMode) EditorApplication.Exit(1); else throw; }+ }+ }+}diff --git a/unity/Assets/Editor/Construction/ConstructionPreview.cs.meta b/unity/Assets/Editor/Construction/ConstructionPreview.cs.metanew file mode 100644index 000000000..e307cf893--- /dev/null+++ b/unity/Assets/Editor/Construction/ConstructionPreview.cs.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: 5c5c9e542031483ea714300e44589744+MonoImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Materials.meta b/unity/Assets/Editor/Construction/Materials.metanew file mode 100644index 000000000..0d0ea5d97--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 6f98103b7379488eae28d7ff06e4173d+folderAsset: yes+DefaultImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Materials/Dust.mat b/unity/Assets/Editor/Construction/Materials/Dust.matnew file mode 100644index 000000000..0f15f6a9e--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Dust.mat@@ -0,0 +1,22 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!21 &2100000+Material:+ serializedVersion: 8+ m_ObjectHideFlags: 0+ m_Name: Dust+ m_Shader: {fileID: 4800000, guid: 2758547def4841eb9d174efc2741cb4d, type: 3}+ m_ValidKeywords: []+ m_InvalidKeywords: []+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 0+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: -1+ stringTagMap: {}+ disabledShaderPasses: []+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs: []+ m_Ints: []+ m_Floats: []+ m_Colors: []diff --git a/unity/Assets/Editor/Construction/Materials/Dust.mat.meta b/unity/Assets/Editor/Construction/Materials/Dust.mat.metanew file mode 100644index 000000000..4e033eaa8--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Dust.mat.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: 00ce1d4103984aafb84a35097b67fdd2+NativeFormatImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Materials/Dust.shader b/unity/Assets/Editor/Construction/Materials/Dust.shadernew file mode 100644index 000000000..5b4d9fdcc--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Dust.shader@@ -0,0 +1,31 @@+Shader "Statecraft/ConstructionDust"+{+ SubShader+ {+ Tags { "RenderPipeline"="UniversalPipeline" "Queue"="Transparent" "RenderType"="Transparent" }+ Pass+ {+ Blend SrcAlpha OneMinusSrcAlpha+ ZWrite Off+ Cull Off+ HLSLPROGRAM+ #pragma vertex vert+ #pragma fragment frag+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ struct Attributes { float4 positionOS:POSITION; half4 color:COLOR; float2 uv:TEXCOORD0; };+ struct Varyings { float4 positionCS:SV_POSITION; half4 color:COLOR; float2 uv:TEXCOORD0; };+ Varyings vert(Attributes v)+ {+ Varyings o; o.positionCS=TransformObjectToHClip(v.positionOS.xyz); o.color=v.color; o.uv=v.uv; return o;+ }+ half4 frag(Varyings i):SV_Target+ {+ float2 p=i.uv*2-1;+ float edge=saturate(1-dot(p,p));+ half alpha=edge*edge*(3-2*edge);+ return half4(i.color.rgb, i.color.a*alpha);+ }+ ENDHLSL+ }+ }+}diff --git a/unity/Assets/Editor/Construction/Materials/Dust.shader.meta b/unity/Assets/Editor/Construction/Materials/Dust.shader.metanew file mode 100644index 000000000..52e5f887d--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Dust.shader.meta@@ -0,0 +1,9 @@+fileFormatVersion: 2+guid: 2758547def4841eb9d174efc2741cb4d+ShaderImporter:+ externalObjects: {}+ defaultTextures: []+ nonModifiableTextures: []+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Materials/Stone.mat b/unity/Assets/Editor/Construction/Materials/Stone.matnew file mode 100644index 000000000..888316a64--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Stone.mat@@ -0,0 +1,22 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!21 &2100000+Material:+ serializedVersion: 8+ m_ObjectHideFlags: 0+ m_Name: Stone+ m_Shader: {fileID: 4800000, guid: 1e78098667ad4ca89939aaca3d6d1b80, type: 3}+ m_ValidKeywords: []+ m_InvalidKeywords: []+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 0+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: -1+ stringTagMap: {}+ disabledShaderPasses: []+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs: []+ m_Ints: []+ m_Floats: []+ m_Colors: []diff --git a/unity/Assets/Editor/Construction/Materials/Stone.mat.meta b/unity/Assets/Editor/Construction/Materials/Stone.mat.metanew file mode 100644index 000000000..fe6732e4c--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Stone.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 0a0d78cdc1904734802396165ad072ba+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Materials/Stone.shader b/unity/Assets/Editor/Construction/Materials/Stone.shadernew file mode 100644index 000000000..b2ee590af--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Stone.shader@@ -0,0 +1,30 @@+Shader "Statecraft/ConstructionStone"+{+ SubShader+ {+ Tags { "RenderPipeline"="UniversalPipeline" "RenderType"="Opaque" "Queue"="Geometry" }+ Pass+ {+ Tags { "LightMode"="UniversalForward" }+ HLSLPROGRAM+ #pragma vertex vert+ #pragma fragment frag+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"+ struct Attributes { float4 positionOS:POSITION; float3 normalOS:NORMAL; half4 color:COLOR; };+ struct Varyings { float4 positionCS:SV_POSITION; half3 normalWS:TEXCOORD0; half4 color:COLOR; };+ Varyings vert(Attributes v)+ {+ Varyings o; o.positionCS=TransformObjectToHClip(v.positionOS.xyz);+ o.normalWS=TransformObjectToWorldNormal(v.normalOS); o.color=v.color; return o;+ }+ half4 frag(Varyings i):SV_Target+ {+ Light sun=GetMainLight();+ half diffuse=saturate(dot(normalize(i.normalWS),sun.direction));+ return half4(i.color.rgb * (half3(0.36,0.34,0.30) + sun.color * diffuse * 0.72),1);+ }+ ENDHLSL+ }+ }+}diff --git a/unity/Assets/Editor/Construction/Materials/Stone.shader.meta b/unity/Assets/Editor/Construction/Materials/Stone.shader.metanew file mode 100644index 000000000..873ca1bfc--- /dev/null+++ b/unity/Assets/Editor/Construction/Materials/Stone.shader.meta@@ -0,0 +1,9 @@+fileFormatVersion: 2+guid: 1e78098667ad4ca89939aaca3d6d1b80+ShaderImporter:+ externalObjects: {}+ defaultTextures: []+ nonModifiableTextures: []+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Statecraft.Construction.Editor.asmdef b/unity/Assets/Editor/Construction/Statecraft.Construction.Editor.asmdefnew file mode 100644index 000000000..be3ecf3d3--- /dev/null+++ b/unity/Assets/Editor/Construction/Statecraft.Construction.Editor.asmdef@@ -0,0 +1,7 @@+{+ "name": "Statecraft.Construction.Editor",+ "rootNamespace": "Statecraft.Editor.Construction",+ "references": ["Statecraft.Game"],+ "includePlatforms": ["Editor"],+ "autoReferenced": true+}diff --git a/unity/Assets/Editor/Construction/Statecraft.Construction.Editor.asmdef.meta b/unity/Assets/Editor/Construction/Statecraft.Construction.Editor.asmdef.metanew file mode 100644index 000000000..54dbdf002--- /dev/null+++ b/unity/Assets/Editor/Construction/Statecraft.Construction.Editor.asmdef.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: 032c291a2d9e4936882f04ec2a56a37c+AssemblyDefinitionImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Tests.meta b/unity/Assets/Editor/Construction/Tests.metanew file mode 100644index 000000000..c3f12cb6a--- /dev/null+++ b/unity/Assets/Editor/Construction/Tests.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 928134efc2c643e48645c7ce1b60944e+folderAsset: yes+DefaultImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Tests/ConstructionPreviewTests.cs b/unity/Assets/Editor/Construction/Tests/ConstructionPreviewTests.csnew file mode 100644index 000000000..44fa48ce3--- /dev/null+++ b/unity/Assets/Editor/Construction/Tests/ConstructionPreviewTests.cs@@ -0,0 +1,50 @@+#nullable enable+using System.Linq;+using NUnit.Framework;+using Statecraft.Editor.Construction;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.SceneManagement;+using Object = UnityEngine.Object;++public class ConstructionPreviewTests+{+ [Test]+ public void PreviewUsesTheGamesHexTerrainInsteadOfADiagnosticPolygon()+ {+ using var stage = new ConstructionStage();+ Assert.That(Resources.FindObjectsOfTypeAll<Terrain>().Any(t => t.name == "HexBoardTerrain" && t.gameObject.scene == stage.Reveal.gameObject.scene), Is.True,+ "one real hex must use HexBoardBuilder terrain");+ }++ [Test]+ public void PreviewReplayAndDisposalLeaveTheCurrentSceneAndResourcesUnchanged()+ {+ var active = SceneManager.GetActiveScene(); bool dirty = active.isDirty;+ int previews = EditorSceneManager.previewSceneCount;+ var mode = RenderSettings.ambientMode; var sky = RenderSettings.ambientSkyColor; var sun = RenderSettings.sun;+ var target = RenderTexture.active;+ int Materials() => Resources.FindObjectsOfTypeAll<Material>().Count(m => m.name == "Construction dust (owned)" || m.name == "Construction stones (owned)");+ int owned = Materials();+ int Stones() => Resources.FindObjectsOfTypeAll<Mesh>().Count(m => m.name == "Construction stone (owned)");+ int stones = Stones();+ for (int i = 0; i < 3; i++)+ {+ using var stage = new ConstructionStage();+ stage.Reveal.Play(); stage.Reveal.Sample(0.65f);+ var image = stage.Frame(240, 180);+ try { Assert.That(image.width, Is.EqualTo(240)); }+ finally { Object.DestroyImmediate(image); }+ stage.Dispose(); stage.Dispose();+ Assert.That(EditorSceneManager.previewSceneCount, Is.EqualTo(previews));+ Assert.That(Materials(), Is.EqualTo(owned));+ Assert.That(Stones(), Is.EqualTo(stones));+ }+ Assert.That(SceneManager.GetActiveScene(), Is.EqualTo(active));+ Assert.That(active.isDirty, Is.EqualTo(dirty));+ Assert.That(RenderSettings.ambientMode, Is.EqualTo(mode));+ Assert.That(RenderSettings.ambientSkyColor, Is.EqualTo(sky));+ Assert.That(RenderSettings.sun, Is.EqualTo(sun));+ Assert.That(RenderTexture.active, Is.EqualTo(target));+ }+}diff --git a/unity/Assets/Editor/Construction/Tests/ConstructionPreviewTests.cs.meta b/unity/Assets/Editor/Construction/Tests/ConstructionPreviewTests.cs.metanew file mode 100644index 000000000..69f28bdcc--- /dev/null+++ b/unity/Assets/Editor/Construction/Tests/ConstructionPreviewTests.cs.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: 3e17b0b8e6ba4ad99b36c01c7668baf1+MonoImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Editor/Construction/Tests/Statecraft.Construction.Tests.asmdef b/unity/Assets/Editor/Construction/Tests/Statecraft.Construction.Tests.asmdefnew file mode 100644index 000000000..8b099fb7f--- /dev/null+++ b/unity/Assets/Editor/Construction/Tests/Statecraft.Construction.Tests.asmdef@@ -0,0 +1,8 @@+{+ "name": "Statecraft.Construction.Tests",+ "references": ["Statecraft.Construction.Editor", "Statecraft.Game", "UnityEngine.TestRunner", "UnityEditor.TestRunner"],+ "includePlatforms": ["Editor"],+ "overrideReferences": true,+ "precompiledReferences": ["nunit.framework.dll"],+ "defineConstraints": ["UNITY_INCLUDE_TESTS"]+}diff --git a/unity/Assets/Editor/Construction/Tests/Statecraft.Construction.Tests.asmdef.meta b/unity/Assets/Editor/Construction/Tests/Statecraft.Construction.Tests.asmdef.metanew file mode 100644index 000000000..ee7bd8686--- /dev/null+++ b/unity/Assets/Editor/Construction/Tests/Statecraft.Construction.Tests.asmdef.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: 8d3ae8b075b641c0ae3d75c664519def+AssemblyDefinitionImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/Construction.meta b/unity/Assets/Scripts/Map/Construction.metanew file mode 100644index 000000000..ba7a82b85--- /dev/null+++ b/unity/Assets/Scripts/Map/Construction.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 85c785761da54ad08fc0c71c7d3eb999+folderAsset: yes+DefaultImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/Construction/ConstructionReveal.cs b/unity/Assets/Scripts/Map/Construction/ConstructionReveal.csnew file mode 100644index 000000000..8d2a24f85--- /dev/null+++ b/unity/Assets/Scripts/Map/Construction/ConstructionReveal.cs@@ -0,0 +1,261 @@+#nullable enable+using System;+using UnityEngine;+using UnityEngine.Rendering;+using Object = UnityEngine.Object;++namespace Statecraft.Game.Map.Construction+{+ public enum RevealStyle { Perimeter, Staggered, Cloud }+ public enum ConstructionLook { Original, Stones }++ /// <summary>Opt-in presentation only. Bind a mesh-only visual child, never the authoritative pick root.+ /// No callbacks into simulation, global random state, coroutines or per-frame allocations.+ /// Its Dust and Stone materials come from <see cref="Templates"/>, which nothing in the player sets, so builds carry+ /// no construction assets until a gameplay caller loads them behind the opt-in.</summary>+ [ExecuteAlways, DisallowMultipleComponent]+ public sealed class ConstructionReveal : MonoBehaviour+ {+ [Range(0.6f, 4f)] public float Duration = 1.8f;+ [Range(0f, 1.5f)] public float Intensity = 1f;+ [Range(0.1f, 3f)] public float Speed = 1f;+ public int Seed = 1948;+ public RevealStyle Style;+ public ConstructionLook Look = ConstructionLook.Stones;+ [Min(0f)] public float GroundOffset;+ public const int DustBudget = 36, DebrisBudget = 8;+ /// <summary>The template material by name ("Dust", "Stone"). The editor preview sets it+ /// (Assets/Editor/Construction/Materials); never a Resources folder, which Unity packs into every build.</summary>+ public static Func<string, Material?>? Templates;+ public bool IsPlaying { get; private set; }+ public float Elapsed { get; private set; }+ public float FootprintRadius { get; private set; }+ Transform? visual;+ Vector3 originalPosition, originalScale, localRise;+ GameObject? particles;+ ParticleSystem? dust, debris;+ Material? material, stoneMaterial;+ Mesh? stoneMesh;+ ParticleSystemRenderer? debrisRenderer;+ ConstructionLook configuredLook;+ bool lookConfigured;+ readonly ParticleSystem.Particle[] puffs = new ParticleSystem.Particle[DustBudget];+ readonly ParticleSystem.Particle[] flecks = new ParticleSystem.Particle[DebrisBudget];+ bool bound;++ /// <summary>radius is a conservative circle about the visual base, in world units. Keep at least+ /// 2.25 radius inside the tile. Call before Play; rebinding first restores the old visual.</summary>+ public void Bind(Transform target, float radius)+ {+ if (target == null) throw new ArgumentNullException(nameof(target));+ if (target == transform || target.parent != transform) throw new ArgumentException("Bind a direct visual child of the reveal host.", nameof(target));+ if (!float.IsFinite(radius) || radius <= 0f) throw new ArgumentOutOfRangeException(nameof(radius));+ Cancel(); visual = target; originalPosition = target.localPosition; originalScale = target.localScale;+ FootprintRadius = radius; bound = true;+ float height = radius * 1.3f;+ var renderers = target.GetComponentsInChildren<Renderer>();+ if (renderers.Length > 0)+ {+ var bounds = renderers[0].bounds;+ foreach (var renderer in renderers) bounds.Encapsulate(renderer.bounds);+ height = Mathf.Max(bounds.size.y, radius * 0.1f);+ }+ localRise = transform.InverseTransformVector(Vector3.up * height);+ }++ public void Play()+ {+ if (!isActiveAndEnabled || !bound || visual == null) return;+ Cancel(); EnsureParticles(); IsPlaying = true; Elapsed = 0f; Sample(0f);+ }++ void Update()+ {+ if (Application.isPlaying && IsPlaying) Sample(Elapsed + Time.deltaTime * Mathf.Clamp(Speed, 0.1f, 3f));+ }++ /// <summary>Absolute visual time, for scrubbing and reproducible captures. Does not advance simulation.</summary>+ public void Sample(float seconds)+ {+ if (!isActiveAndEnabled || !bound || visual == null) { Cancel(); return; }+ Elapsed = float.IsFinite(seconds) ? Mathf.Max(0f, seconds) : 0f;+ float duration = float.IsFinite(Duration) ? Mathf.Clamp(Duration, 0.6f, 4f) : 1.8f;+ float t = Mathf.Clamp01(Elapsed / duration);+ if (t >= 1f) { Cancel(); Elapsed = duration; return; }+ EnsureParticles();+ // Anticipation: the intact building starts below the ground. Dust precedes its rise.+ float rise = Smooth(0.12f, Style == RevealStyle.Staggered ? 0.67f : 0.51f, t);+ float settle = Mathf.Sin(Mathf.InverseLerp(0.51f, 0.78f, t) * Mathf.PI) * (t < 0.78f ? 0.012f : 0f);+ if (Look == ConstructionLook.Stones)+ {+ // One restrained overshoot and a smaller return, never a squash of the original model.+ float u = Mathf.InverseLerp(0.51f, 0.82f, t);+ settle = t < 0.82f ? Mathf.Sin(u * Mathf.PI * 2f) * (1f - u) * 0.02f : 0f;+ }+ visual.localScale = originalScale;+ visual.localPosition = originalPosition + localRise * (rise - 1f + settle);+ particles!.transform.position = transform.TransformPoint(originalPosition) + Vector3.up * (Look == ConstructionLook.Stones && float.IsFinite(GroundOffset) ? Mathf.Max(0f, GroundOffset) : 0f);+ ConfigureLook(); DrawDust(t);+ if (Look == ConstructionLook.Original) DrawDebris(t); else DrawStones(t);+ }++ public void Cancel()+ {+ IsPlaying = false;+ if (bound && visual != null) { visual.localPosition = originalPosition; visual.localScale = originalScale; }+ if (dust != null) dust.Clear(); if (debris != null) debris.Clear();+ }++ void OnDisable() => Cancel();+ void OnDestroy()+ {+ Cancel(); Dispose(particles); Dispose(material); Dispose(stoneMaterial); Dispose(stoneMesh);+ particles = null; material = null; stoneMaterial = null; stoneMesh = null; lookConfigured = false;+ }++ void EnsureParticles()+ {+ if (particles != null && dust != null && debris != null) return;+ // A caller may remove a visual-only child while retaining the host for reuse.+ // Release the surviving partial system/material and configure the replacement renderer again.+ if (dust != null) dust.Clear(); if (debris != null) debris.Clear();+ Dispose(particles); Dispose(material);+ particles = null; dust = null; debris = null; material = null;+ debrisRenderer = null; lookConfigured = false;+ var template = Template("Dust");+ material = new Material(template) { name = "Construction dust (owned)", hideFlags = HideFlags.DontSave };+ particles = new GameObject("Construction particles (owned)") { hideFlags = HideFlags.DontSave, layer = 2 };+ particles.transform.SetParent(transform, false);+ // World space keeps the dust at the ground while only the visual child rises.+ dust = MakeSystem("Base puffs", DustBudget); debris = MakeSystem("Earth flecks", DebrisBudget);+ }++ ParticleSystem MakeSystem(string name, int budget)+ {+ var go = new GameObject(name) { layer = 2 }; go.transform.SetParent(particles!.transform, false);+ var ps = go.AddComponent<ParticleSystem>(); ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);+ ps.useAutoRandomSeed = false; ps.randomSeed = 1u;+ var main = ps.main; main.simulationSpeed = 0f; main.startSpeed = 0f; main.playOnAwake = false; main.loop = false; main.maxParticles = budget;+ main.simulationSpace = ParticleSystemSimulationSpace.World; main.cullingMode = ParticleSystemCullingMode.AlwaysSimulate;+ var emission = ps.emission; emission.enabled = false; var shape = ps.shape; shape.enabled = false;+ var renderer = go.GetComponent<ParticleSystemRenderer>(); renderer.sharedMaterial = material;+ renderer.shadowCastingMode = ShadowCastingMode.Off; renderer.receiveShadows = false;+ ps.Play(); ps.Pause();+ renderer.renderMode = ParticleSystemRenderMode.Billboard; renderer.sortMode = ParticleSystemSortMode.Distance;+ return ps;+ }++ void DrawDust(float t)+ {+ int count = 0;+ float intensity = float.IsFinite(Intensity) ? Mathf.Clamp(Intensity, 0f, 1.5f) : 1f;+ int wanted = Mathf.RoundToInt(DustBudget * Mathf.Min(intensity, 1f));+ Vector3 centre = particles!.transform.position;+ float radius = FootprintRadius;+ for (int i = 0; i < wanted; i++)+ {+ float h = Hash(i, 1), h2 = Hash(i, 2), h3 = Hash(i, 3);+ bool completion = Look == ConstructionLook.Stones && i % 3 == 2;+ float start = completion ? 0.49f + h * 0.045f : 0.06f + h * 0.09f + (Style == RevealStyle.Staggered ? (i % 3) * 0.055f : 0f);+ float age = (t - start) / (completion ? 0.32f : 0.48f + h2 * 0.29f);+ if (age <= 0f || age >= 1f) continue;+ float angle = i * 2.399963f + h2 * 0.3f;+ float cloud = Style == RevealStyle.Cloud ? 1.16f : 1f;+ float ring = radius * (0.82f + h2 * 0.19f + age * 0.42f) * cloud;+ float size = radius * (0.35f + h3 * 0.22f) * (0.6f + age * 1.1f) * cloud;+ float opacity = Mathf.Sin(Mathf.PI * age) * (1f - Smooth(0.60f, 1f, age)) * 0.76f * Mathf.Min(intensity, 1.3f);+ var colour = Color.Lerp(new Color(0.57f, 0.41f, 0.26f), new Color(0.88f, 0.76f, 0.51f), h3);+ colour.a = opacity * (completion ? 0.62f : 1f);+ if (completion) size *= 0.68f;+ puffs[count++] = Particle(centre + new Vector3(Mathf.Cos(angle) * ring, radius * (0.07f + age * 0.19f + h3 * 0.06f), Mathf.Sin(angle) * ring), size, colour, h * 360f);+ }+ dust!.SetParticles(puffs, count);+ }++ void DrawDebris(float t)+ {+ int count = 0;+ if (Intensity > 0f)+ for (int i = 0; i < DebrisBudget; i++)+ {+ float age = (t - 0.14f - Hash(i, 4) * 0.08f) / 0.28f;+ if (age <= 0f || age >= 1f) continue;+ float angle = i * 2.399963f, r = FootprintRadius * (0.65f + age * 0.63f);+ var at = particles!.transform.position + new Vector3(Mathf.Cos(angle) * r, FootprintRadius * (0.025f + Mathf.Sin(age * Mathf.PI) * 0.24f), Mathf.Sin(angle) * r);+ flecks[count++] = Particle(at, FootprintRadius * (0.025f + Hash(i, 6) * 0.018f), new Color(0.48f, 0.34f, 0.19f, 1f - Smooth(0.6f, 1f, age)), age * 180f);+ }+ debris!.SetParticles(flecks, count);+ }++ void ConfigureLook()+ {+ if (lookConfigured && configuredLook == Look) return;+ debrisRenderer ??= debris!.GetComponent<ParticleSystemRenderer>();+ var main = debris!.main; main.startRotation3D = Look == ConstructionLook.Stones;+ if (Look == ConstructionLook.Stones)+ {+ if (stoneMaterial == null)+ {+ var template = Template("Stone");+ stoneMaterial = new Material(template) { name = "Construction stones (owned)", hideFlags = HideFlags.DontSave };+ stoneMesh = MakeStone();+ }+ debrisRenderer.renderMode = ParticleSystemRenderMode.Mesh; debrisRenderer.mesh = stoneMesh;+ debrisRenderer.sharedMaterial = stoneMaterial;+ }+ else { debrisRenderer.renderMode = ParticleSystemRenderMode.Billboard; debrisRenderer.sharedMaterial = material; }+ configuredLook = Look; lookConfigured = true;+ }++ void DrawStones(float t)+ {+ int count = 0;+ if (Intensity > 0f)+ for (int i = 0; i < DebrisBudget; i++)+ {+ float age = (t - 0.10f - (i % 3) * 0.022f - Hash(i, 4) * 0.025f) / (0.55f + Hash(i, 8) * 0.08f);+ if (age <= 0f || age >= 1f) continue;+ float angle = i * 2.399963f + Hash(i, 9) * 0.5f;+ float travel = 1f - (1f - age) * (1f - age);+ float radius = FootprintRadius * (0.76f + travel * 0.77f);+ float height;+ if (age < 0.55f) { float u = age / 0.55f; height = 4f * u * (1f - u) * (0.32f + Hash(i, 10) * 0.1f); }+ else if (age < 0.80f) { float u = (age - 0.55f) / 0.25f; height = 4f * u * (1f - u) * 0.10f; }+ else if (age < 0.94f) { float u = (age - 0.80f) / 0.14f; height = 4f * u * (1f - u) * 0.025f; }+ else height = 0f;+ float size = FootprintRadius * (0.085f + Hash(i, 6) * 0.035f) * (1f - Smooth(0.82f, 1f, age));+ var at = particles!.transform.position + new Vector3(Mathf.Cos(angle) * radius, FootprintRadius * (height + 0.065f), Mathf.Sin(angle) * radius);+ var colour = Color.Lerp(new Color(0.43f, 0.32f, 0.20f), new Color(0.69f, 0.56f, 0.36f), Hash(i, 7));+ var stone = Particle(at, size, colour, 0f);+ stone.rotation3D = new Vector3(Hash(i, 11) * 180f + travel * 210f, Hash(i, 12) * 360f, travel * 140f);+ flecks[count++] = stone;+ }+ debris!.SetParticles(flecks, count);+ }++ static Material Template(string name) => Templates?.Invoke(name)+ ?? throw new InvalidOperationException($"Construction {name} material is missing: set ConstructionReveal.Templates.");++ static Mesh MakeStone()+ {+ var points = new[] { new Vector3(0.1f, 0.55f, -0.07f), new Vector3(-0.12f, -0.4f, 0.06f),+ new Vector3(-0.52f, 0.05f, 0.04f), new Vector3(0.46f, -0.03f, 0.08f),+ new Vector3(0.02f, 0.03f, -0.43f), new Vector3(0.03f, 0.02f, 0.39f) };+ int[] faces = { 0, 4, 2, 0, 3, 4, 0, 5, 3, 0, 2, 5, 1, 2, 4, 1, 4, 3, 1, 3, 5, 1, 5, 2 };+ var vertices = new Vector3[faces.Length]; var indices = new int[faces.Length];+ for (int i = 0; i < faces.Length; i++) { vertices[i] = points[faces[i]]; indices[i] = i; }+ var mesh = new Mesh { name = "Construction stone (owned)", hideFlags = HideFlags.DontSave, vertices = vertices, triangles = indices };+ mesh.RecalculateNormals(); mesh.RecalculateBounds(); return mesh;+ }++ static ParticleSystem.Particle Particle(Vector3 position, float size, Color colour, float rotation) =>+ new ParticleSystem.Particle { position = position, startSize = size, startColor = colour, rotation = rotation, startLifetime = 10f, remainingLifetime = 10f };+ float Hash(int i, int salt)+ {+ uint h = unchecked((uint)(Seed ^ (i + 1) * 73856093 ^ salt * 19349663));+ h ^= h << 13; h ^= h >> 17; h ^= h << 5; return (h & 0xffff) / 65535f;+ }+ static float Smooth(float from, float to, float t) => Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(from, to, t));+ static void Dispose(Object? value) { if (value == null) return; if (Application.isPlaying) Destroy(value); else DestroyImmediate(value); }+ }+}diff --git a/unity/Assets/Scripts/Map/Construction/ConstructionReveal.cs.meta b/unity/Assets/Scripts/Map/Construction/ConstructionReveal.cs.metanew file mode 100644index 000000000..8cb692242--- /dev/null+++ b/unity/Assets/Scripts/Map/Construction/ConstructionReveal.cs.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: 5de17d97b4174eb2bee82695d3390eae+MonoImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/ConstructionRevealTests.cs b/unity/Assets/Tests/EditMode/ConstructionRevealTests.csnew file mode 100644index 000000000..f08ca38e8--- /dev/null+++ b/unity/Assets/Tests/EditMode/ConstructionRevealTests.cs@@ -0,0 +1,192 @@+#nullable enable+using System;+using NUnit.Framework;+using UnityEngine;+using Object = UnityEngine.Object;++public class ConstructionRevealTests+{+ // Reflection keeps the red test executable before the opt-in component exists.+ static Type RevealType => typeof(Statecraft.Game.Map.PlacementLayer).Assembly.GetType("Statecraft.Game.Map.Construction.ConstructionReveal")!;++ [Test]+ public void RevealIsAvailableWithoutLoadingTheGame()+ {+ Assert.That(RevealType, Is.Not.Null, "a standalone construction reveal must exist");+ }++ [Test]+ public void TheRevealsMaterialsShipInNoPlayerBuild()+ {+ // Nothing in gameplay calls the reveal yet, so the default player build must carry none of its assets.+ Assert.That(Resources.LoadAll<Object>("Construction"), Is.Empty, "Resources folders ship in every build");+ Assert.That(UnityEditor.AssetDatabase.FindAssets("t:Material", new[] { "Assets/Editor/Construction/Materials" }), Has.Length.EqualTo(2),+ "the Dust and Stone templates stay editor-only");+ }++ [Test]+ public void SeededParticlesAreRepeatableBoundedAndDoNotConsumeGlobalRandom()+ {+ Assert.That(RevealType, Is.Not.Null, "a standalone construction reveal must exist");+ var root = new GameObject("test root"); var visual = new GameObject("visual");+ try+ {+ visual.transform.SetParent(root.transform, false); root.transform.position = new Vector3(30, 4, 20);+ var fx = root.AddComponent(RevealType);+ void Call(string name, params object[] args) => RevealType.GetMethod(name)!.Invoke(fx, args);+ Call("Bind", visual.transform, 2f);+ var random = UnityEngine.Random.state;+ Call("Play"); Call("Sample", 0.65f);+ Assert.That(UnityEngine.Random.state, Is.EqualTo(random), "visual seed never consumes the sim/global RNG");+ var systems = root.GetComponentsInChildren<ParticleSystem>(); Assert.That(systems.Length, Is.EqualTo(2));+ var before = new ParticleSystem.Particle[44]; int count = systems[0].GetParticles(before);+ Assert.That(count, Is.InRange(1, 36));+ foreach (var ps in systems)+ {+ var particles = new ParticleSystem.Particle[44]; int n = ps.GetParticles(particles);+ Assert.That(n, Is.LessThanOrEqualTo(ps.main.maxParticles));+ for (int i = 0; i < n; i++)+ {+ var d = particles[i].position - root.transform.position;+ Assert.That(new Vector2(d.x, d.z).magnitude + particles[i].startSize * 0.5f, Is.LessThan(4.5f));+ Assert.That(d.y, Is.InRange(0f, 1f), "dust remains near ground");+ }+ }+ Call("Play"); Call("Sample", 0.65f);+ var after = new ParticleSystem.Particle[44]; Assert.That(systems[0].GetParticles(after), Is.EqualTo(count));+ for (int i = 0; i < count; i++) Assert.That(after[i].position, Is.EqualTo(before[i].position));+ }+ finally { Object.DestroyImmediate(root); }+ }++ [Test]+ public void OriginalAndStoneLooksStayBoundedAcrossTheWholeTimeline()+ {+ var look = RevealType.GetField("Look");+ Assert.That(look, Is.Not.Null, "the original and refined looks must remain comparable");+ var root = new GameObject("bounds root"); var visual = new GameObject("visual");+ visual.transform.SetParent(root.transform, false);+ try+ {+ var fx = root.AddComponent(RevealType);+ void Call(string name, params object[] args) => RevealType.GetMethod(name)!.Invoke(fx, args);+ Call("Bind", visual.transform, 2f);+ var buffer = new ParticleSystem.Particle[44];+ foreach (var mode in new[] { "Original", "Stones" })+ {+ look!.SetValue(fx, Enum.Parse(look.FieldType, mode));+ foreach (var style in Enum.GetValues(RevealType.GetField("Style")!.FieldType))+ {+ RevealType.GetField("Style")!.SetValue(fx, style); Call("Play");+ var systems = root.GetComponentsInChildren<ParticleSystem>();+ for (int step = 0; step <= 30; step++)+ {+ Call("Sample", step * 0.06f);+ foreach (var ps in systems)+ {+ int n = ps.GetParticles(buffer); Assert.That(n, Is.LessThanOrEqualTo(ps.main.maxParticles));+ for (int i = 0; i < n; i++)+ {+ var p = buffer[i].position;+ var size = buffer[i].startSize3D;+ Assert.That(new Vector2(p.x, p.z).magnitude + Mathf.Max(size.x, size.y) * 0.5f, Is.LessThan(4.5f));+ Assert.That(p.y, Is.InRange(0f, 1f));+ }+ }+ }+ }+ }+ }+ finally { Object.DestroyImmediate(root); }+ }++ [TestCase(0)]+ [TestCase(1)]+ [TestCase(2)]+ public void DestroyedParticleChildrenCanBeRecreatedWithoutLeakingOrLosingMeshMode(int child)+ {+ var root = new GameObject("reuse root"); var visual = new GameObject("visual");+ visual.transform.SetParent(root.transform, false);+ try+ {+ var fx = root.AddComponent(RevealType);+ void Call(string name, params object[] args) => RevealType.GetMethod(name)!.Invoke(fx, args);+ Call("Bind", visual.transform, 2f); Call("Play"); Call("Sample", 0.5f);+ var systems = root.GetComponentsInChildren<ParticleSystem>();+ var oldDust = systems[0].GetComponent<ParticleSystemRenderer>().sharedMaterial;+ Object.DestroyImmediate(child == 0 ? systems[0].transform.parent.gameObject : systems[child - 1].gameObject);+ if (child == 0) Call("Play");+ Call("Sample", 0.5f);+ Assert.That(oldDust == null, Is.True, "recreation must release the old owned dust material");+ var rebuilt = root.GetComponentsInChildren<ParticleSystemRenderer>();+ Assert.That(rebuilt.Length, Is.EqualTo(2));+ Assert.That(rebuilt[1].renderMode, Is.EqualTo(ParticleSystemRenderMode.Mesh));+ Assert.That(rebuilt[1].mesh, Is.Not.Null);+ }+ finally { Object.DestroyImmediate(root); }+ }++ [Test]+ public void DestroyAndRebindRestoreTheOldTargetAndReleaseOwnedMaterial()+ {+ Assert.That(RevealType, Is.Not.Null, "a standalone construction reveal must exist");+ var root = new GameObject("root"); var a = new GameObject("a"); var b = new GameObject("b");+ a.transform.SetParent(root.transform, false); b.transform.SetParent(root.transform, false);+ try+ {+ var fx = root.AddComponent(RevealType);+ void Call(string name, params object[] args) => RevealType.GetMethod(name)!.Invoke(fx, args);+ Call("Bind", a.transform, 2f); Call("Play"); Call("Sample", 0.2f);+ var renderers = root.GetComponentsInChildren<ParticleSystemRenderer>();+ var material = renderers[0].sharedMaterial; var stones = renderers[1].sharedMaterial; var mesh = renderers[1].mesh;+ Call("Bind", b.transform, 1f); Assert.That(a.transform.localScale, Is.EqualTo(Vector3.one));+ Assert.That(a.transform.localPosition, Is.EqualTo(Vector3.zero));+ Call("Play"); Call("Sample", 0.2f); Object.DestroyImmediate(fx);+ Assert.That(b.transform.localScale, Is.EqualTo(Vector3.one));+ Assert.That(b.transform.localPosition, Is.EqualTo(Vector3.zero));+ Assert.That(material == null, Is.True, "owned material is released");+ Assert.That(stones == null, Is.True, "owned stone material is released");+ Assert.That(mesh == null, Is.True, "owned stone mesh is released");+ Assert.That(root.GetComponentsInChildren<ParticleSystem>().Length, Is.Zero);+ }+ finally { Object.DestroyImmediate(root); }+ }++ [Test]+ public void ReplayCancelAndDisableRestoreVisualAndKeepPickingStable()+ {+ Assert.That(RevealType, Is.Not.Null, "a standalone construction reveal must exist");+ var root = new GameObject("pick root");+ var visual = GameObject.CreatePrimitive(PrimitiveType.Cube);+ try+ {+ visual.transform.SetParent(root.transform, false);+ Object.DestroyImmediate(visual.GetComponent<Collider>());+ var pick = root.AddComponent<BoxCollider>();+ visual.transform.localPosition = new Vector3(2, 0, 1);+ visual.transform.localScale = new Vector3(2, 3, 2);+ var position = visual.transform.localPosition; var scale = visual.transform.localScale;+ var fx = root.AddComponent(RevealType);+ void Call(string name, params object[] args) => RevealType.GetMethod(name)!.Invoke(fx, args);+ Call("Bind", visual.transform, 4f);+ for (int i = 0; i < 12; i++)+ {+ Call("Play"); Call("Sample", 0.6f);+ Assert.That(pick.enabled, Is.True);+ Assert.That(root.transform.position, Is.EqualTo(Vector3.zero));+ Call("Cancel");+ Assert.That(visual.transform.localPosition, Is.EqualTo(position));+ Assert.That(visual.transform.localScale, Is.EqualTo(scale));+ }+ Assert.That(root.GetComponentsInChildren<ParticleSystem>(true).Length, Is.EqualTo(2), "replay reuses its two systems");+ Call("Play"); Call("Sample", 0.5f); ((Behaviour)fx).enabled = false;+ Assert.That(visual.transform.localPosition, Is.EqualTo(position));+ Assert.That(visual.transform.localScale, Is.EqualTo(scale));+ ((Behaviour)fx).enabled = true;+ Call("Play"); Call("Sample", 100f);+ Assert.That(visual.transform.localScale, Is.EqualTo(scale));+ Assert.That(root.GetComponentsInChildren<ParticleSystem>(true)[0].particleCount, Is.Zero);+ }+ finally { Object.DestroyImmediate(root); }+ }+}diff --git a/unity/Assets/Tests/EditMode/ConstructionRevealTests.cs.meta b/unity/Assets/Tests/EditMode/ConstructionRevealTests.cs.metanew file mode 100644index 000000000..005a6d01e--- /dev/null+++ b/unity/Assets/Tests/EditMode/ConstructionRevealTests.cs.meta@@ -0,0 +1,11 @@+fileFormatVersion: 2+guid: 16a04f9e7c634ddca539bbc37c9dc84b+MonoImporter:+ externalObjects: {}+ serializedVersion: 2+ defaultReferences: []+ executionOrder: 0+ icon: {instanceID: 0}+ userData:+ assetBundleName:+ assetBundleVariant: