A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: round 2 of the hex-tile map (full-detail buildings, regional variants, time of day, under attack, painter palette), stacked on #1131 (refs #18) (#1153)
pixelrenderai-hashd64e91bad2fd
diff --git a/changelog.d/hex-editor-round2-1153.md b/changelog.d/hex-editor-round2-1153.mdnew file mode 100644index 000000000..13393ad55--- /dev/null+++ b/changelog.d/hex-editor-round2-1153.md@@ -0,0 +1,16 @@+- Round 2 of the opt-in hex-tile map, still presentation only and off by default.+ - **Buildings:** they draw the shipped b*-v2 town models at full detail. Our own decimated copies had lost faces, so+ grass showed through walls and windows. The tile budgets are raised to match, and a test counts see-through view+ rays.+ - **Regional variants:** two each for the north, centre and south of the wheat, citrus, olive, mixed-farm and forest+ tiles (a new `mixed_farm`).+ - **Time of day:** day, dusk and night presets (`?hex-tiles&hex-time=dusk|night`, desktop `-hex-time`). Night has+ lit windows. Everything is restored on teardown.+ - **Under attack:** a look for a hex (smoke, glow and a pulsing border) that the sim can drive later. It is not+ saved to any board.+ - **Hex Painter:** a palette of every tile, by kind and region, and every unit, with thumbnails. A brush paints+ tiles, units are placed with a facing, and day, dusk, night and under attack can be previewed.+ - **Units:** a character unit is one model × 8. The hex figures draw the Collection's whole figures in the editor;+ the grazing flock's sheep and donkey do too. Our decimated copies showed the ground through clothes, fleece and faces.+ - **Board capture:** the whole-board shot no longer cuts off the board's south edge.+ (docs/hex-tiles/README.md; refs #18)diff --git a/docs/hex-tiles/README.md b/docs/hex-tiles/README.mdindex 7dadecfc3..202132d9a 100644--- a/docs/hex-tiles/README.md+++ b/docs/hex-tiles/README.md@@ -115,6 +115,36 @@ The recipes plant, by region:A hex with no region, as on every board made before regions, gets the built-in mix: olive and carob on the flat, oakand pine on hills, limestone outcrops on hills.+### Regional variants of the farm and forest tiles++Each farm and forest type has two variants for each of the north, centre and south: 30 tiles, all `Kind` farm or+forest.++| Type | Ids | Base |+|---|---|---|+| Wheat | `wheat_fields_<region>_a` and `_b` | `WheatFields` |+| Citrus | `citrus_orchard_<region>_a` and `_b` | `CitrusOrchard` |+| Olive | `olive_terraces_<region>_a` and `_b` | `OliveTerraces` |+| Mixed farm | `mixed_farm_<region>_a` and `_b` | `MixedFarm` (`mixed_farm`) |+| Forest | `forest_<region>_a` and `_b` | `PineForest` |++- **One variant, one file.** Each variant is a short file in `Prototypes/` named by its region (`wheat_fields_north_a`+ is `WheatFieldsNorthA.cs`). It subclasses its base and overrides only the base's `protected virtual` members: grid+ turn, parcel size, crops, species, caps, yard, and `Dress`.+- **The regions differ:**+ - north is greener, with oak and pine hedgerows;+ - centre has coastal-plain citrus;+ - south is drier and sparser, with date palms and acacia. Its forest is an acacia or date-palm grove, not a pine+ wood.+- **a and b differ** in layout, parcel size, crop mix and species, so they read apart at board distance.+- **Choosing a variant.** The region recipes in `regions.yaml` pick between the variants of a hex's region with the+ stable per-hex `pick`.+- **`HexVariantTests` checks them:**+ - every variant is registered with its kind and region;+ - each variant builds differently from its pair and from its base;+ - the base tiles still build exactly as before. Their placements and paints are pinned by hash, so a base edit that+ changes what `wheat_fields` and the others build fails the test.+## Painting hexes by hand: overrides and the Hex Painter**Overrides.** Hand edits that must survive regeneration go in `Boards/<id>.overrides.json`, beside the board. The file@@ -151,21 +181,47 @@ and no hex appears twice in a list.The board in the scene is never saved: load it again after a script reload.+**The palette.** Below the selected hex, the painter lists every registered tile.++- **How it is grouped:**+ - Tiles are grouped by kind (city, town, village, farm, forest, nature, other), then by region (north, centre, south,+ any). The groups come from `[HexPrototype(Kind, Region)]`, so a new tile appears by itself.+ - Units come after the tiles, as characters (a squad of 8) and vehicles (one each).+- **Thumbnails.** Each entry shows its thumbnail, or its id where none has been made yet. **Make thumbnails** (or+ `HexPaletteThumbs.Run` in batch) renders them into `asset-staging/ui-local/hex-tiles/thumbs/`. It replaces the open+ scene after asking to save, then reopens the scene and the board.+- **Paint tiles.** Pick a tile, which switches the mode to *Paint tile*, then click or drag over hexes in the Scene+ view. Each hex is rebuilt and written to the board's overrides. The "no tile" brush clears a hex's prototype.+- **Stand units.** Pick a unit and a facing (the six neighbour directions, or any angle), then click a hex, or use+ *Stand the unit on the selected hex*. This writes `unit` and `facing`. *Clear unit* removes it, and the removal is+ recorded, so the hex stays empty after regenerating.+- **Previews.** *Day*, *Dusk*, *Night* (see "Time of day") and *Under attack* (see "Under attack") are previews only.+ - They are never written.+ - They are undone on Unload, on loading another board, on closing the window and on a script reload.+ - After a painted hex is rebuilt, its under-attack look is shown again and the time preset is applied again.+To check the painter's path from the command line, use `HexPainterCapture`. It loads the board, shoots the hex, makesone edit, and shoots it again. The edit goes to a scratch overrides file in the capture folder unless `-overrides` namesanother:```bash-Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.HexTiles.Painter.HexPainterCapture.Run -board israel -hex -3,19 -field prototype -value tel_aviv_city_mixed+Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.HexTiles.Painter.HexPainterCapture.Run -board israel -hex -3,19 -thumbs -ops "prototype=kibbutz;unit=palmach_squad@120;time=dusk;time=night;attack"```+Each operation writes `<n>-<op>/before.png` and `after.png`. The capture also writes `painter.txt` and, with+`-thumbs`, the palette's contact sheet: `palette.png` and `palette.txt`. The older `-field <f> -value <v>+[-facing <deg>]` form still works.+## Adding a prototype hex (the contributor workflow)**One prototype is one new file** (or one unit is one new file under `Units/`). **You never edit anyone else's file.**1. **Copy the reference** `unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCity.cs` to`Prototypes/<YourName>.cs`. Then:- - Give it a new `[HexPrototype("your_id")]`, in lower_snake_case and unique.+ - Give it a new `[HexPrototype("your_id", Kind = "...")]`, in lower_snake_case and unique.+ - `Kind` is its group in the painter's palette, one of `HexPrototypes.Kinds`: city, town, village, farm, forest,+ nature or other.+ - Add `Region = "north"`, `"centre"` or `"south"` for a regional variant.- Use the namespace `Statecraft.HexTiles.Prototypes`.- Write it in C# 9: no `record` types.- Keep one prototype class per file. Do not copy `WheatFields.cs`: it holds two (`wheat_fields` and `grazing_land`).@@ -282,6 +338,7 @@ Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath unThe tests require that every prototype:- has a lower_snake_case id;+- names a palette kind, and a known region if any;- builds something;- is deterministic;- keeps every piece inside its inset hexagon;@@ -353,6 +410,91 @@ Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPThe output is `asset-staging/ui-local/hex-tiles/unit-move/unit-move.mp4`, plus its frames. The MP4 is written onlywhen ffmpeg is on PATH. `-captureDir` and `-captureSize 1920x1080` are optional.+## Buildings: the shipped b*-v2 models++The building ids the tiles use (`sandbox:hq_white_city*`, `sandbox:hq_white_city_hero` and every `sandbox:kit_*`) draw+the shipped b*-v2 town models at full detail.++- **Where they come from:** `TownModelSet`, `Assets/Art/Settlements/TownModels.asset`, the set the map scene already+ loads.+- **How the ids map:** `HexModels.TownAliases` holds the mapping. No prototype file names the models.+- **Why:** our own decimated kit had lost faces, and its materials cull back faces, so the ground showed through walls+ and windows (Tal, 19 October 2026).+- **Fallbacks:** without the set, an id draws its local sandbox prefab, then its stand-in.+- **Naming a model directly:** use `town:<folder>`, for example `town:b04a-haifa-stone-balconies-v2`. The folders are+ listed in `TownModels.Ids`. These models are cleared on main, so they draw on every machine.+ - `town:<folder>@mid` draws the set's baked mid level. Most mid levels see through, so don't use it.+- **Remaps.** b11 shikun and b21 workshop are not in the set and are not pulled into a build. `kit_white_city_4` draws+ b13a; `kit_jaffa_2` and `kit_negev_3` draw b03a. `kit_haifa` draws b17, because b04a's full mesh has open wall+ triangles.+- **Cost:** a full mesh is about 6,000 triangles, so the city, village and farm budgets were raised to match. A lighter+ level is a follow-up: the LOD generator's in-between levels are whole for most models, but they smear their+ textures.+- **Checking a new building mesh:**+ - `HexModelMeshTests` counts view rays that meet a model but none of its front faces: the ground shows there.+ b02a and b13a are allowed their thin balcony slivers. The report goes to+ `asset-staging/ui-local/hex-tiles/round2/buildings/mesh-report.txt`.+ - `HexModelCapture.Run` shoots every building alias from four sides.+ - On Tripo meshes, open-edge counts are noise. Only see-through rays find holes.++## Figures: the Collection's whole characters++- **One character per unit.** A character unit is one model × 8 (`HexUnitTypes.Squad(title, model)`), never a mix.+ `palmach_squad` is 8 Palmach scouts (c12f).+- **Where the figures come from.** In the editor (captures, painter, tests), the `proto:figure-*` ids draw the cleared+ Collection figures (`HexModels.FigureAliases`, `Assets/Art/Collection/<figure>/<figure>-near|far.prefab`).+ - Our own decimated copies (`characters_to_fbx.py`) had lost faces, 2.7 to 6.5% see-through.+ - Soldiers take `near`. Townspeople take `far`, except c01, whose far level is holed.+ - The grazing flock's sheep and donkey take `far`; their decimated copies were 6 to 8% see-through.+- **In a player** the Collection streams from bundles, so the hex tiles still draw the local proto figures, then+ stand-ins. Wiring the bundles in is a follow-up.+- **No walk cycle.** The Collection's near figures have an idle clip only, so a moving squad glides.+- **Checking a figure:** `HexUnitTests` checks one model per unit, whole figures, facing, height and the fallback.++## Time of day++- **Turning it on:** add `&hex-time=dusk` or `&hex-time=night` to a `?hex-tiles` URL (desktop: `-hex-time dusk|night`).+- **What counts:**+ - Only a top-level query parameter counts.+ - A value after `#`, a bad value, or the flag alone gives day.+ - `?hex-time` without `?hex-tiles` does nothing.+- **The presets** (`Core/HexTimeOfDay.cs`, presentation only):+ - **Day** is the warm `HexLook`, unchanged.+ - **Dusk** is a low (14°) west-north-west sun: deep warm light and long shadows under a cooler sky.+ - **Night** is a dim blue-white moon, a dark-blue ambient and a lower exposure. It keeps about 55–60% of day's+ brightness, so tiles and units stay readable. City and town tiles get warm lit windows: one mesh, under the board+ root as `HexNightWindows`.+- **Teardown:** the preset's undo runs before `HexLook`'s. It puts back:+ - the grade values and override states it changed;+ - the sun's rotation, intensity, colour and shadows;+ - the ambient mode, colours and probe.+ It removes only the volume components it added, and destroys the window mesh and material.+- **Captures** take `-time day|dusk|night`. Night also darkens the background.+- **In the Hex Painter:** the window has the same switch.++## Under attack++`HexUnderAttack.Show(boardRoot, surface, q, r)` marks a hex as under attack: three grey smoke columns, a low warm glow+where each rises, and a muted red border that pulses slowly. The columns rise in the hex's north half, so they stand+behind a unit or the city's centre as the board camera sees it.++- **Presentation only:** nothing reads or writes the simulation, and it is never written to a board or its overrides.+ It is the visual state the sim can drive later; movement and combat rules are the owner's+ (`docs/gdd/military-combat.md`).+- **Removing it:** `Hide(boardRoot, q, r)` removes it and frees the 3 meshes, the 3 materials and the texture it made.+ `IsShown` tells whether a hex has it.+- **Animation:** it animates in edit mode and in play (`HexUnderAttackLook`). For a deterministic frame, in captures and+ tests, set `look.Hold = true` and call `look.Time(t)`. Smoke placement is seeded by (q, r).+- **Materials:** they ship as templates in `Resources/HexTiles/Materials` (`HexAttackSmoke`, `HexAttackGlow`,+ `HexAttackBorder`), made by **Statecraft/Hex Tiles/Make Materials**. After running that menu, revert the five older+ templates it rewrites.+- **Cost:** about 723 triangles and 3 draws.+- **Captures:**++```bash+Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.HexTiles.Capture.HexUnderAttackCapture.Run -board israel+```+## Review and hand-in- **Branch:** work on `hex/<your_id>`. The change is your one prototype file (or one `Units/<id>.cs`), plus your models@@ -366,7 +508,8 @@ when ffmpeg is on PATH. `-captureDir` and `-captureSize 1920x1080` are optional.- **Tripo models are local-only while their rights are pending:**- figures, animals, vehicles and landmarks (`proto:`);- - the decimated city kit (`sandbox:kit_*`).+ - the decimated city kit (`sandbox:kit_*`). The tiles no longer draw it while the shipped town models are found (see+ "Buildings").They are never committed, shared or built into a shareable build. On other machines they draw as stand-ins.- **Not yet in the repository:**- the EZ-Tree trees (MIT), Poly Haven rocks and ground textures (CC0) under `sandbox:`;@@ -382,18 +525,26 @@ when ffmpeg is on PATH. `-captureDir` and `-captureSize 1920x1080` are optional.|---|---|| `Core/HexTileContract.cs` | `HexTerrain`, `[HexPrototype]`, `IHexPrototype`, `HexScale`, the registry, hex geometry || `Core/HexTileContext.cs` | The API a prototype uses, and the placement record |-| `Core/HexModels.cs` | Model ids, variants, stand-ins, triangle counts |+| `Core/HexModels.cs` | Model ids, variants, stand-ins, triangle counts, the shipped town models (`TownAliases`) |+| `Core/HexTimeOfDay.cs` | Day, dusk and night presets (`?hex-time`) |+| `Core/HexUnderAttack.cs` | The under-attack look for a hex || `Core/HexBoard.cs` | Board files, the Civ-style ground (`HexBoardSurface`), ground layers || `Core/HexBoardBuilder.cs` | Terrain, sea, rendering, tile edges, per-tile reports || `Core/HexUnits.cs` | `HexUnit`, `HexUnitMember`, and `HexUnitMotion` (moving a unit along hex centres) || `Core/HexBoardOverrides.cs` | A board's hand edits (`<id>.overrides.json`) |-| `Capture/HexBoardCapture.cs` | The capture command (`-prototype <id>`, plus `-on <tile>` to try it on another tile's hex) |+| `Capture/HexBoardCapture.cs` | The capture command (`-prototype <id>`, plus `-on <tile>` to try it on another tile's hex; `-time`) |+| `Capture/HexModelCapture.cs` | Four-side shots of each building model, and the see-through check (`HexMeshCheck`) |+| `Capture/HexUnderAttackCapture.cs` | Before and after shots of the under-attack look || `Painter/HexPainterWindow.cs` | The Hex Painter window || `Painter/HexPainter.cs` | The painter's write-back and one-hex rebuild |-| `Painter/HexPainterCapture.cs` | The painter's path from the command line |+| `Painter/HexPainterCapture.cs` | The painter's path from the command line (`-ops`, `-thumbs`) |+| `Painter/HexPalette.cs` | The palette's groups, facings and brushes |+| `Painter/HexPaletteThumbs.cs` | Palette thumbnails and the contact sheet |+| `Painter/HexPainterSwitches.cs`, `HexPainterStage.cs` | The painter's time-of-day and under-attack previews, and its light and grade || `tools/hex_tiles/regions.yaml` | The region recipes || `Capture/HexUnitMoveCapture.cs` | The unit-move video || `Tests/HexPrototypeTests.cs` | The contract tests |+| `Tests/HexVariantTests.cs`, `HexModelMeshTests.cs`, `HexTimeOfDayTests.cs`, `HexUnderAttackTests.cs`, `HexBoardCaptureTests.cs` | Variants, whole buildings, time of day, under attack, whole-board framing || `Prototypes/` | One file per prototype hex (`TelAvivCity.cs` is the reference) || `Prototypes/MountainPeaks.cs` | `mountain_peaks`, the rocks on a mountain hex || `Prototypes/WheatFields.cs` | `wheat_fields` and `grazing_land` (two classes in one file: do not copy it) |diff --git a/tools/tests/test_hex_regions.py b/tools/tests/test_hex_regions.pyindex ae98f83d8..12fc49592 100644--- a/tools/tests/test_hex_regions.py+++ b/tools/tests/test_hex_regions.py@@ -16,7 +16,7 @@ COUNTRY = ["--regions", str(REGIONS), "--id", "israel", "--all", "--env-ring", "def known_prototypes():ids = set()for f in (HEX_TILES / "Prototypes").glob("*.cs"):- ids |= set(re.findall(r'\[HexPrototype\("([a-z0-9_]+)"\)\]', f.read_text(encoding="utf-8")))+ ids |= set(re.findall(r'\[HexPrototype\("([a-z0-9_]+)"[,)]', f.read_text(encoding="utf-8")))return idsdiff --git a/unity/Assets/Editor/HexTiles/Capture/HexBoardCapture.cs b/unity/Assets/Editor/HexTiles/Capture/HexBoardCapture.csindex 885c86ab5..4a069da73 100644--- a/unity/Assets/Editor/HexTiles/Capture/HexBoardCapture.cs+++ b/unity/Assets/Editor/HexTiles/Capture/HexBoardCapture.cs@@ -22,7 +22,9 @@ namespace Statecraft.HexTiles.Capture/// -prototype <id> builds and shoots only that tile (with the board's ground and mountains around it)./// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity/// -executeMethod Statecraft.HexTiles.Capture.HexBoardCapture.Run [-board tel_aviv] [-prototype <id> [-on <tile>]]- /// [-captureDir asset-staging/ui-local/hex-tiles] [-captureSize 3840x2160] [-boardOnly]+ /// [-captureDir asset-staging/ui-local/hex-tiles] [-captureSize 3840x2160] [-boardOnly] [-time day|dusk|night] [-closeM 12500]+ /// -time lays a HexTimeOfDay preset over the look once the board is built (day, the default, changes nothing); night+ /// also darkens the background./// A board too large for the standard board shot (the whole country) is framed whole instead. Each prototype and unit/// is shot once (its last hex in the board file, the one whose shots used to be kept); -boardOnly skips those shots.</summary>public static class HexBoardCapture@@ -32,7 +34,7 @@ namespace Statecraft.HexTiles.Capture/// them the board paints flat colours.</summary>const string GroundFolder = "Assets/Art/Settlements/Prototype/HexSandboxGround";/// <summary>A livelier grade than the shipped map's, for the hex-tile captures (the opt-in look's start values).</summary>- const float Pitch = 50f, Fov = 35f, BoardDistanceM = 80000f, MidDistanceM = 26000f, CloseDistanceM = 12500f;+ public const float Pitch = 50f, Fov = 35f, BoardDistanceM = 80000f, MidDistanceM = 26000f, CloseDistanceM = 12500f;[MenuItem("Statecraft/Hex Tiles/Capture Tel Aviv Board")]public static void Run()@@ -63,8 +65,12 @@ namespace Statecraft.HexTiles.Capturevar on = Arg("-on");if (only != null && on != null) foreach (var h in board.Hexes.Values) if (h.prototype == on) h.prototype = only;if (only != null && !board.Hexes.Values.Any(h => h.prototype == only)) throw new ArgumentException($"board {boardId} has no tile '{only}' (try -on <tile>)");+ var time = HexTime.Day;+ if (Arg("-time") is string timeId && !HexTimeOfDay.TryParse(timeId, out time)) throw new ArgumentException($"-time {timeId}: not one of {string.Join(", ", HexTimeOfDay.Ids)}");var cam = Stage();var (root, reports) = HexBoardBuilder.Build(board, Ground, only: only);+ // After the build, so the night's lit windows find the board's city and town tiles.+ var undoTime = ApplyTime(cam, time, root, board, only);long buildMs = clock.ElapsedMilliseconds;Directory.CreateDirectory(dir);try@@ -73,7 +79,7 @@ namespace Statecraft.HexTiles.CaptureVector3 OnGround(Vector3 p) => new Vector3(p.x, Mathf.Max(surface.Height(p), 0f), p.z);var centres = board.Hexes.Values.Select(h => HexGeometry.Centre(h.q, h.r, HexScale.HexM)).ToList();var middle = new Vector3(centres.Average(c => c.x), 0f, centres.Average(c => c.z));- float boardDistance = BoardDistance(board, cam, width / (float)height);+ float boardDistance = BoardDistance(board, OnGround(middle), width / (float)height);if (only == null) Shoot(cam, OnGround(middle), boardDistance, Path.Combine(dir, "board.png"), width, height);// A board with an environment ring: one wider shot that takes in the landscape round the play hexes.if (only == null && board.Hexes.Values.Any(h => h.env)) Shoot(cam, OnGround(middle), boardDistance * 1.6f, Path.Combine(dir, "board-wide.png"), width, height);@@ -83,11 +89,11 @@ namespace Statecraft.HexTiles.Capture{var c = OnGround(HexGeometry.Centre(t.q, t.r, HexScale.HexM));Shoot(cam, c, MidDistanceM, Path.Combine(dir, $"{t.prototype}-mid.png"), width, height);- Shoot(cam, c, CloseDistanceM, Path.Combine(dir, $"{t.prototype}-close.png"), width, height);+ Shoot(cam, c, CloseM(), Path.Combine(dir, $"{t.prototype}-close.png"), width, height);}// Units: one close shot each, at the unit's own zoom.foreach (var u in board.Hexes.Values.Where(h => tiles && h.unit != "" && (only == null || h.prototype == only)).GroupBy(h => h.unit).Select(g => g.Last()))- Shoot(cam, OnGround(HexGeometry.Centre(u.q, u.r, HexScale.HexM)), CloseDistanceM, Path.Combine(dir, $"unit-{u.unit}-close.png"), width, height);+ Shoot(cam, OnGround(HexGeometry.Centre(u.q, u.r, HexScale.HexM)), CloseM(), Path.Combine(dir, $"unit-{u.unit}-close.png"), width, height);var lines = new List<string> { $"board {boardId}: {board.Hexes.Count} hexes, built in {buildMs} ms, {width}x{height}" };lines.AddRange(reports.Select(r => " " + r));File.WriteAllLines(Path.Combine(dir, only == null ? "stats.txt" : $"{only}-stats.txt"), lines);@@ -95,6 +101,7 @@ namespace Statecraft.HexTiles.Capture}finally{+ undoTime();TiltShift.Reset();Object.DestroyImmediate(root);}@@ -117,14 +124,52 @@ namespace Statecraft.HexTiles.Capturereturn cam;}+ /// <summary>Night's sky behind the board: a dark navy instead of the day's teal.</summary>+ public static readonly Color NightBackground = new Color(0.02f, 0.06f, 0.11f);++ /// <summary>Lays <paramref name="time"/> over the look Stage() set (its volume and sun), as HexTilesLook does in the+ /// game, and darkens the camera's background for night. Returns the undo.</summary>+ public static Action ApplyTime(Camera cam, HexTime time, GameObject root, HexBoard board, string? only)+ {+ var volume = Object.FindFirstObjectByType<Volume>();+ var undo = HexTimeOfDay.Apply(time, volume != null ? volume.profile : null, MapLighting.FindSun(), root, board, only);+ if (time != HexTime.Night) return undo;+ var background = cam.backgroundColor; cam.backgroundColor = NightBackground;+ return () => { undo(); if (cam != null) cam.backgroundColor = background; };+ }+/// <summary>The board shot's distance: the standard one, unless the board would not fit at twice it (the whole- /// country), when it is framed whole: its width across the view, its depth foreshortened by the pitch.</summary>- static float BoardDistance(HexBoard board, Camera cam, float aspect)+ /// country, by the rough fit below), when it is framed whole: the shortest distance at which all four corners of+ /// the board's rect (HexBoardBuilder.Bounds, at sea level) project inside the view with a small margin, the camera+ /// still aimed at <paramref name="lookAt"/>. The rough fit alone (the depth foreshortened by sin(pitch)) left the+ /// near, southern edge out of frame: at a 50 degree pitch the perspective spreads the near side.</summary>+ public static float BoardDistance(HexBoard board, Vector3 lookAt, float aspect){var b = HexBoardBuilder.Bounds(board);- float tanV = Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad), tanH = tanV * aspect;- float fit = 1.05f * Mathf.Max(b.width * 0.5f / tanH, b.height * 0.5f * Mathf.Sin(Pitch * Mathf.Deg2Rad) / tanV);- return fit > 2f * BoardDistanceM ? fit : BoardDistanceM;+ float tanV = Mathf.Tan(Fov * 0.5f * Mathf.Deg2Rad), tanH = tanV * aspect;+ float rough = 1.05f * Mathf.Max(b.width * 0.5f / tanH, b.height * 0.5f * Mathf.Sin(Pitch * Mathf.Deg2Rad) / tanV);+ if (rough <= 2f * BoardDistanceM) return BoardDistanceM;+ var corners = new[] { new Vector3(b.xMin, 0f, b.yMin), new Vector3(b.xMax, 0f, b.yMin), new Vector3(b.xMin, 0f, b.yMax), new Vector3(b.xMax, 0f, b.yMax) };+ bool Fits(float d) => corners.All(c =>+ {+ var v = View(c, lookAt, d);+ return v.z > 0f && Mathf.Abs(v.x / v.z) <= tanH * (1f - FrameMargin) && Mathf.Abs(v.y / v.z) <= tanV * (1f - FrameMargin);+ });+ float lo = rough * 0.5f, hi = rough;+ while (!Fits(hi)) hi *= 1.5f;+ for (int i = 0; i < 40; i++) { float mid = 0.5f * (lo + hi); if (Fits(mid)) hi = mid; else lo = mid; }+ return hi;+ }++ /// <summary>The share of the half-view kept free round a board framed whole.</summary>+ public const float FrameMargin = 0.03f;++ /// <summary>A world point in view space (x right, y up, z forward) for a shot of <paramref name="lookAt"/> from+ /// <paramref name="distance"/>, the camera placed as Shoot places it.</summary>+ static Vector3 View(Vector3 p, Vector3 lookAt, float distance)+ {+ var rot = Quaternion.Euler(Pitch, 0f, 0f);+ return Quaternion.Inverse(rot) * (p - (lookAt - rot * Vector3.forward * distance));}public static void Shoot(Camera cam, Vector3 lookAt, float distance, string path, int width, int height)@@ -154,6 +199,11 @@ namespace Statecraft.HexTiles.Capturereturn (Load($"{texture}_diff_2k.jpg", false), Load($"{texture}_nor_gl_2k.jpg", true));}+ /// <summary>The close shots' camera distance: -closeM <metres> (for example 3000, a squad's figures up close), else+ /// <see cref="CloseDistanceM"/>.</summary>+ static float CloseM() =>+ float.TryParse(Arg("-closeM"), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var m) && m > 0f ? m : CloseDistanceM;+public static string? Arg(string name){var args = Environment.GetCommandLineArgs();diff --git a/unity/Assets/Editor/HexTiles/Capture/HexModelCapture.cs b/unity/Assets/Editor/HexTiles/Capture/HexModelCapture.csnew file mode 100644index 000000000..2ff4a947c--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Capture/HexModelCapture.cs@@ -0,0 +1,382 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using Debug = UnityEngine.Debug;+using Object = UnityEngine.Object;++namespace Statecraft.HexTiles.Capture+{+ /// <summary>Whether a building's mesh is whole, measured in the placement's unit frame (HexModels.Parts: y up whatever+ /// the source mesh's). The test is what the player sees: the buildings' materials cull back faces and Tripo's+ /// buildings are open underneath, so a view ray that meets the model but no front face of it (in through a missing+ /// wall face, out past the culled inside of the far wall) shows the ground through the building (SeeThrough, of the+ /// rays that meet the model at all, from eight sides at the board camera's elevations). Rays whose first face is a+ /// back face (BackFirst) are reported but do not decide: one-sided railings and awnings seen from behind count there,+ /// and the wall behind them still shows (measured on b02b, 19 October 2026). Open (boundary) edges, after welding+ /// vertices by position (UV and normal seams split them), are reported too: the shipped meshes have thousands+ /// (T-junctions and hairline cracks) that never show. Also how a sandbox prefab and the town model drawn for it line+ /// up (Facing).</summary>+ public static class HexMeshCheck+ {+ public readonly struct Result+ {+ public readonly int Triangles, Open, OpenOffBase, NonManifold, Hits, BackFirst, SeeThrough;+ public Result(int triangles, int open, int offBase, int nonManifold, int hits, int backFirst, int seeThrough)+ {+ Triangles = triangles; Open = open; OpenOffBase = offBase; NonManifold = nonManifold; Hits = hits; BackFirst = backFirst; SeeThrough = seeThrough;+ }+ /// <summary>The share of view rays on the model that see the ground through it.</summary>+ public float SeeThroughShare => Hits == 0 ? 0f : SeeThrough / (float)Hits;+ /// <summary>The share of view rays on the model whose first face is a back face.</summary>+ public float BackFirstShare => Hits == 0 ? 0f : BackFirst / (float)Hits;+ public override string ToString() =>+ $"{Triangles} tris, {SeeThroughShare:P2} see-through ({SeeThrough} of {Hits} rays), {BackFirstShare:P2} back face first, {Open} open edges ({OpenOffBase} off the base), {NonManifold} non-manifold";+ }++ /// <summary>The view elevations (degrees down) and sides the rays come from, and the ray grid's side per view.</summary>+ static readonly float[] Elevations = { 20f, 35f, 50f };+ const int Sides = 8, Grid = 96;++ /// <summary>A prefab's static meshes as the hex tiles draw them (HexModels.Parts, Fit.Width).</summary>+ public static Result Of(GameObject prefab, float weld = 1e-5f) =>+ Of(HexModels.Parts(prefab, Fit.Width).GroupBy(p => (p.Mesh, p.Local)).Select(g => (g.Key.Mesh, g.Key.Local)), weld);++ /// <summary>Meshes with their matrices into a y-up frame; welded together, so a model split over several meshes or+ /// submeshes counts as one surface.</summary>+ public static Result Of(IEnumerable<(Mesh mesh, Matrix4x4 local)> parts, float weld = 1e-5f)+ {+ var pts = new List<Vector3>(); var tris = new List<int>();+ foreach (var (mesh, local) in parts)+ {+ int start = pts.Count;+ pts.AddRange(mesh.vertices.Select(v => local.MultiplyPoint3x4(v)));+ for (int s = 0; s < mesh.subMeshCount; s++)+ {+ if (mesh.GetTopology(s) != MeshTopology.Triangles) continue;+ tris.AddRange(mesh.GetTriangles(s).Select(i => i + start));+ }+ }+ if (pts.Count == 0) return new Result(0, 0, 0, 0, 0, 0, 0);+ var b = new Bounds(pts[0], Vector3.zero); foreach (var p in pts) b.Encapsulate(p);+ var (open, offBase, nonManifold) = Edges(pts, tris, b, weld);+ var (hits, backFirst, through) = Rays(pts, tris, b);+ return new Result(tris.Count / 3, open, offBase, nonManifold, hits, backFirst, through);+ }++ /// <summary>Open edges (one face), those off the base plane (min y + 0.5% of the height) and non-manifold edges+ /// (three or more faces), once vertices within <paramref name="weld"/> of the model's size are one.</summary>+ static (int open, int offBase, int nonManifold) Edges(List<Vector3> pts, List<int> tris, Bounds b, float weld)+ {+ float grid = Mathf.Max(b.size.x, Mathf.Max(b.size.y, b.size.z)) * weld, baseY = b.min.y + 0.005f * b.size.y;+ var cells = new Dictionary<(long, long, long), int>(); var id = new int[pts.Count];+ for (int i = 0; i < pts.Count; i++)+ {+ var k = ((long)Mathf.Round(pts[i].x / grid), (long)Mathf.Round(pts[i].y / grid), (long)Mathf.Round(pts[i].z / grid));+ if (!cells.TryGetValue(k, out var w)) cells[k] = w = i;+ id[i] = w;+ }+ var edges = new Dictionary<(int, int), int>();+ for (int t = 0; t + 2 < tris.Count; t += 3)+ {+ int a = id[tris[t]], c = id[tris[t + 1]], d = id[tris[t + 2]];+ if (a == c || c == d || d == a) continue; // degenerate once welded+ foreach (var (u, v) in new[] { (a, c), (c, d), (d, a) })+ {+ var e = u < v ? (u, v) : (v, u);+ edges[e] = edges.TryGetValue(e, out var n) ? n + 1 : 1;+ }+ }+ int open = 0, offBase = 0, nonManifold = 0;+ foreach (var (e, n) in edges)+ {+ if (n > 2) nonManifold++;+ if (n != 1) continue;+ open++;+ if (pts[e.Item1].y > baseY || pts[e.Item2].y > baseY) offBase++;+ }+ return (open, offBase, nonManifold);+ }++ /// <summary>Parallel view rays from <see cref="Sides"/> sides at each of <see cref="Elevations"/>, on a+ /// <see cref="Grid"/>-square grid over the model: how many meet a triangle, how many of those meet a back face+ /// first, and how many meet no front face at all (Unity's front face winds clockwise to the viewer, so+ /// Cross(b - a, c - a) points at it). A software+ /// orthographic raster: each view bins the projected triangles by grid cell.</summary>+ static (int hits, int backFirst, int through) Rays(List<Vector3> pts, List<int> tris, Bounds b)+ {+ int hits = 0, backFirst = 0, through = 0, n = tris.Count / 3;+ float radius = b.extents.magnitude, cell = 2f * radius / Grid;+ var bins = new List<int>[Grid * Grid];+ for (int i = 0; i < bins.Length; i++) bins[i] = new List<int>();+ var uv = new Vector3[pts.Count];+ int Cell(float v) => Mathf.Clamp(Mathf.FloorToInt((v + radius) / cell), 0, Grid - 1);+ foreach (var elevation in Elevations)+ for (int side = 0; side < Sides; side++)+ {+ // Looking down and in; each elevation's sides offset a little, so the views do not repeat.+ var dir = Quaternion.Euler(elevation, 360f / Sides * side + 7.5f * System.Array.IndexOf(Elevations, elevation), 0f) * Vector3.forward;+ var right = Vector3.Cross(Vector3.up, dir).normalized; var up = Vector3.Cross(dir, right);+ for (int i = 0; i < pts.Count; i++)+ {+ var p = pts[i] - b.center;+ uv[i] = new Vector3(Vector3.Dot(p, right), Vector3.Dot(p, up), Vector3.Dot(p, dir));+ }+ foreach (var bin in bins) bin.Clear();+ for (int t = 0; t < n; t++)+ {+ Vector3 p0 = uv[tris[3 * t]], p1 = uv[tris[3 * t + 1]], p2 = uv[tris[3 * t + 2]];+ int x0 = Cell(Mathf.Min(p0.x, Mathf.Min(p1.x, p2.x))), x1 = Cell(Mathf.Max(p0.x, Mathf.Max(p1.x, p2.x)));+ int y0 = Cell(Mathf.Min(p0.y, Mathf.Min(p1.y, p2.y))), y1 = Cell(Mathf.Max(p0.y, Mathf.Max(p1.y, p2.y)));+ for (int y = y0; y <= y1; y++) for (int x = x0; x <= x1; x++) bins[y * Grid + x].Add(t);+ }+ for (int c = 0; c < Grid * Grid; c++)+ {+ // The ray through the cell's centre: its nearest triangle, and which side of it faces the ray.+ float rx = -radius + (c % Grid + 0.5f) * cell, ry = -radius + (c / Grid + 0.5f) * cell, near = float.MaxValue;+ bool back = false, front = false;+ foreach (var t in bins[c])+ {+ Vector3 p0 = uv[tris[3 * t]], p1 = uv[tris[3 * t + 1]], p2 = uv[tris[3 * t + 2]];+ float area = (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y);+ if (Mathf.Abs(area) < 1e-12f) continue;+ float w1 = ((rx - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (ry - p0.y)) / area;+ float w2 = ((p1.x - p0.x) * (ry - p0.y) - (rx - p0.x) * (p1.y - p0.y)) / area;+ if (w1 < 0f || w2 < 0f || w1 + w2 > 1f) continue;+ float z = p0.z + w1 * (p1.z - p0.z) + w2 * (p2.z - p0.z);+ var a = pts[tris[3 * t]];+ bool isBack = Vector3.Dot(Vector3.Cross(pts[tris[3 * t + 1]] - a, pts[tris[3 * t + 2]] - a), dir) > 0f;+ front |= !isBack;+ if (z >= near) continue;+ near = z; back = isBack;+ }+ if (near == float.MaxValue) continue;+ hits++;+ if (back) backFirst++;+ if (!front) through++;+ }+ }+ return (hits, backFirst, through);+ }++ /// <summary>The names of <see cref="Facing"/>'s scores: quarter turns about y, and the same mirrored in x.</summary>+ public static readonly string[] FacingNames = { "0", "90", "180", "270", "m0", "m90", "m180", "m270" };++ /// <summary>For each of the eight turns and mirrors of <paramref name="from"/>'s vertices, their mean distance to the+ /// nearest vertex of <paramref name="to"/>, both in the unit frame (Fit.Width): index 0 (as they are) is least when+ /// the two face the same way.</summary>+ public static float[] Facing(GameObject from, GameObject to)+ {+ static List<Vector3> Points(GameObject go, int most)+ {+ var all = HexModels.Parts(go, Fit.Width).GroupBy(p => (p.Mesh, p.Local))+ .SelectMany(g => g.Key.Mesh.vertices.Select(v => g.Key.Local.MultiplyPoint3x4(v))).ToList();+ int step = Mathf.Max(1, all.Count / most);+ return all.Where((_, i) => i % step == 0).ToList();+ }+ return Facing(Points(from, 600), Points(to, 6000));+ }++ /// <summary>A skinned mesh's vertices in world space as its bones stand now (CPU linear-blend skinning: each bone's+ /// localToWorld times its bind pose, weighted). BakeMesh is not used: it drops a scale inherited from a parent.</summary>+ public static Vector3[] Skinned(SkinnedMeshRenderer s, bool forceBake = false)+ {+ var mesh = s.sharedMesh; var v = mesh.vertices; var bones = s.bones; var bind = mesh.bindposes; var w = mesh.boneWeights;+ if (forceBake || bones.Length == 0 || w.Length != v.Length)+ {+ // No exposed bones (the Collection's near figures): Unity's own skinning. BakeMesh(false) already applies the+ // scale (measured: through the renderer's full transform it came out scale-squared), so only the+ // renderer's position and rotation place the vertices.+ var baked = new Mesh();+ var at = Matrix4x4.TRS(s.transform.position, s.transform.rotation, Vector3.one);+ try { s.BakeMesh(baked, false); return baked.vertices.Select(p => at.MultiplyPoint3x4(p)).ToArray(); }+ finally { Object.DestroyImmediate(baked); }+ }+ var m = new Matrix4x4[bones.Length];+ for (int i = 0; i < bones.Length; i++) m[i] = bones[i] != null ? bones[i].localToWorldMatrix * bind[i] : s.transform.localToWorldMatrix;+ var outp = new Vector3[v.Length];+ for (int i = 0; i < v.Length; i++)+ {+ var b = w[i];+ outp[i] = m[b.boneIndex0].MultiplyPoint3x4(v[i]) * b.weight0 + m[b.boneIndex1].MultiplyPoint3x4(v[i]) * b.weight1+ + m[b.boneIndex2].MultiplyPoint3x4(v[i]) * b.weight2 + m[b.boneIndex3].MultiplyPoint3x4(v[i]) * b.weight3;+ }+ return outp;+ }++ /// <summary>A figure object's meshes as they stand now, as new meshes in world space (skinned ones by+ /// <see cref="Skinned"/>, static ones through their transform); the caller destroys them.</summary>+ public static List<Mesh> WorldMeshes(GameObject go)+ {+ var list = new List<Mesh>();+ Mesh Copy(Mesh src, Vector3[] pts)+ {+ var m = new Mesh { indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };+ m.SetVertices(pts);+ m.SetTriangles(Enumerable.Range(0, src.subMeshCount).Where(i => src.GetTopology(i) == MeshTopology.Triangles).SelectMany(i => src.GetTriangles(i)).ToArray(), 0);+ return m;+ }+ foreach (var s in go.GetComponentsInChildren<SkinnedMeshRenderer>(true)) if (s.sharedMesh != null) list.Add(Copy(s.sharedMesh, Skinned(s)));+ foreach (var f in go.GetComponentsInChildren<MeshFilter>(true))+ if (f.sharedMesh != null && f.GetComponent<MeshRenderer>() != null) list.Add(Copy(f.sharedMesh, f.sharedMesh.vertices.Select(p => f.transform.localToWorldMatrix.MultiplyPoint3x4(p)).ToArray()));+ return list;+ }++ /// <summary>Runs <paramref name="use"/> on a figure prefab's meshes, in world space: an instance at the origin, posed+ /// as the hex tiles draw it (<paramref name="posed"/>: its idle clip's first frame, HexStandIns.SampleIdle) or at+ /// rest (the bones as the prefab has them: the bind pose for a Tripo rig; a Collection near prefab lies flat there,+ /// as its clip stands it up).</summary>+ static T AtRest<T>(GameObject prefab, Func<List<Mesh>, T> use, bool posed = true)+ {+ var go = Object.Instantiate(prefab);+ if (posed) foreach (var a in go.GetComponentsInChildren<Animator>(true)) HexStandIns.SampleIdle(a);+ var meshes = WorldMeshes(go);+ try { return use(meshes); }+ finally { foreach (var m in meshes) Object.DestroyImmediate(m); Object.DestroyImmediate(go); }+ }++ /// <summary>A figure's see-through and edges, posed (or in bind pose).</summary>+ public static Result OfFigure(GameObject prefab, bool posed = true) => AtRest(prefab, ms => Of(ms.Select(m => (m, Matrix4x4.identity))), posed);++ /// <summary>A figure's size, posed (or in bind pose), in the prefab's units.</summary>+ public static Vector3 FigureSize(GameObject prefab, bool posed = true) => AtRest(prefab, ms => SizeOf(ms.SelectMany(m => m.vertices)), posed);++ public static Vector3 SizeOf(IEnumerable<Vector3> pts)+ {+ var list = pts.ToList();+ var b = new Bounds(list[0], Vector3.zero); foreach (var p in list) b.Encapsulate(p);+ return b.size;+ }++ /// <summary><see cref="Facing(GameObject, GameObject)"/> for figures: both scaled to unit height, footprint centred,+ /// feet at 0.</summary>+ public static float[] FigureFacing(GameObject from, GameObject to)+ {+ static List<Vector3> Points(GameObject go, int most)+ {+ var all = AtRest(go, ms => ms.SelectMany(m => m.vertices).ToList());+ var b = new Bounds(all[0], Vector3.zero); foreach (var p in all) b.Encapsulate(p);+ float k = 1f / Mathf.Max(b.size.y, 1e-6f);+ int step = Mathf.Max(1, all.Count / most);+ return all.Where((_, i) => i % step == 0).Select(p => new Vector3(p.x - b.center.x, p.y - b.min.y, p.z - b.center.z) * k).ToList();+ }+ return Facing(Points(from, 600), Points(to, 6000));+ }++ static float[] Facing(List<Vector3> a, List<Vector3> b)+ {+ var scores = new float[8];+ for (int k = 0; k < 8; k++)+ {+ var turn = Quaternion.Euler(0f, 90f * (k % 4), 0f);+ double sum = 0;+ foreach (var p0 in a)+ {+ var p = turn * (k >= 4 ? new Vector3(-p0.x, p0.y, p0.z) : p0);+ float best = float.MaxValue;+ foreach (var q in b) { float d = (p - q).sqrMagnitude; if (d < best) best = d; }+ sum += Mathf.Sqrt(best);+ }+ scores[k] = (float)(sum / a.Count);+ }+ return scores;+ }+ }++ /// <summary>Close shots of every building model the hex tiles draw, alone on a plain ground, from four sides (one 2x2+ /// sheet per model at -captureSize, default 3840x2160): before (the sandbox prefab, when present on this machine) and+ /// after (what the id resolves to now, HexModels.Prefab). Uses the hex captures' stage (HexBoardCapture.Stage, Shoot).+ /// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity+ /// -executeMethod Statecraft.HexTiles.Capture.HexModelCapture.Run [-captureDir asset-staging/ui-local/hex-tiles/round2/buildings/models]</summary>+ public static class HexModelCapture+ {+ /// <summary>How large a model stands in the shot (m across), and how far the camera stands from it.</summary>+ const float WidthM = 1000f, DistanceM = 2600f;++ public static void Run()+ {+ try+ {+ var repo = Path.GetFullPath(Path.Combine(Application.dataPath, "..", ".."));+ var dir = Path.GetFullPath(Path.Combine(repo, HexBoardCapture.Arg("-captureDir") ?? "asset-staging/ui-local/hex-tiles/round2/buildings/models"));+ var size = (HexBoardCapture.Arg("-captureSize") ?? "3840x2160").Split('x');+ Capture(dir, int.Parse(size[0]), int.Parse(size[1]));+ }+ catch (Exception e)+ {+ Debug.LogError("HEX MODEL CAPTURE FAILED " + e);+ if (Application.isBatchMode) EditorApplication.Exit(1);+ else throw;+ }+ }++ /// <summary>The building ids the hex tiles may draw: every sandbox id with a town model; with -allTown also every+ /// town model at its full and mid level.</summary>+ static IEnumerable<string> Ids() => HexModels.TownAliases.Select(a => a.id).Distinct().OrderBy(i => i, StringComparer.Ordinal)+ .Concat(Environment.GetCommandLineArgs().Contains("-allTown")+ ? Statecraft.Game.Map.Kits.TownModels.Ids.SelectMany(t => new[] { HexModels.TownPrefix + t, HexModels.TownPrefix + t + HexModels.MidSuffix })+ : Enumerable.Empty<string>());++ static void Capture(string dir, int width, int height)+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ var cam = HexBoardCapture.Stage();+ var ground = GameObject.CreatePrimitive(PrimitiveType.Plane);+ ground.transform.localScale = Vector3.one * 600f;+ var gm = new Material(Shader.Find("Universal Render Pipeline/Lit")); gm.SetColor("_BaseColor", new Color(0.55f, 0.62f, 0.38f));+ ground.GetComponent<Renderer>().sharedMaterial = gm;+ Directory.CreateDirectory(dir);+ var lines = new List<string>();+ foreach (var id in Ids())+ {+ var name = id.Replace("sandbox:", "").Replace(HexModels.TownPrefix, "town-").Replace(HexModels.MidSuffix, "-mid");+ var before = id.StartsWith(HexModels.TownPrefix, StringComparison.Ordinal) ? null : Resources.Load<GameObject>(HexModels.PathOf(id));+ var after = HexModels.Prefab(id);+ if (before != null) Sheet(cam, before, Path.Combine(dir, $"{name}-before.png"), width, height);+ if (after != null) Sheet(cam, after, Path.Combine(dir, $"{name}-after.png"), width, height);+ lines.Add($"{id}: before {(before != null ? before.name : "-")}, after {(after != null ? after.name : "-")}");+ }+ File.WriteAllLines(Path.Combine(dir, "models.txt"), lines);+ Debug.Log("HEX MODEL CAPTURE " + string.Join(" | ", lines) + " -> " + dir);+ }++ /// <summary>Four shots of the model (from its front, then turned a quarter each time), tiled 2x2 into one image.</summary>+ static void Sheet(Camera cam, GameObject prefab, string path, int width, int height)+ {+ int w = width / 2, h = height / 2;+ var sheet = new Texture2D(width, height, TextureFormat.RGB24, false);+ var holder = new GameObject("model");+ try+ {+ foreach (var part in HexModels.Parts(prefab, Fit.Width))+ {+ var go = new GameObject(part.Mesh.name, typeof(MeshFilter), typeof(MeshRenderer));+ go.transform.SetParent(holder.transform, false);+ var m = Matrix4x4.Scale(Vector3.one * WidthM) * part.Local;+ go.transform.localPosition = m.GetColumn(3); go.transform.localRotation = m.rotation; go.transform.localScale = m.lossyScale;+ go.GetComponent<MeshFilter>().sharedMesh = part.Mesh;+ var mats = new Material[part.Mesh.subMeshCount];+ for (int i = 0; i < mats.Length; i++) mats[i] = part.Material;+ go.GetComponent<MeshRenderer>().sharedMaterials = mats;+ }+ for (int k = 0; k < 4; k++)+ {+ // The camera looks north (HexBoardCapture.Shoot): turning the model shows each side in turn; 0 shows its -z side.+ holder.transform.rotation = Quaternion.Euler(0f, 90f * k, 0f);+ var tmp = Path.Combine(Path.GetDirectoryName(path)!, "_tile.png");+ HexBoardCapture.Shoot(cam, new Vector3(0f, WidthM * 0.3f, 0f), DistanceM, tmp, w, h);+ var tile = new Texture2D(2, 2); tile.LoadImage(File.ReadAllBytes(tmp)); File.Delete(tmp);+ sheet.SetPixels((k % 2) * w, (1 - k / 2) * h, w, h, tile.GetPixels());+ Object.DestroyImmediate(tile);+ }+ sheet.Apply();+ File.WriteAllBytes(path, sheet.EncodeToPNG());+ }+ finally { Object.DestroyImmediate(holder); Object.DestroyImmediate(sheet); }+ }+ }+}diff --git a/unity/Assets/Editor/HexTiles/Capture/HexModelCapture.cs.meta b/unity/Assets/Editor/HexTiles/Capture/HexModelCapture.cs.metanew file mode 100644index 000000000..f47e136f0--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Capture/HexModelCapture.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ef0382e01d5984a4f9057f3dbd05dd01\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Capture/HexTilesAssets.cs b/unity/Assets/Editor/HexTiles/Capture/HexTilesAssets.csindex 22b54ec96..9c313ec80 100644--- a/unity/Assets/Editor/HexTiles/Capture/HexTilesAssets.cs+++ b/unity/Assets/Editor/HexTiles/Capture/HexTilesAssets.cs@@ -6,7 +6,7 @@ using UnityEngine;namespace Statecraft.HexTiles.Capture{/// <summary>Editor-made assets the hex-tile map needs in a player build: the material templates (tracked, in- /// Resources/HexTiles/Materials, so their shaders and variants ship), and a local copy of the ground textures in the+ /// Resources/HexTiles/Materials, so their shaders and variants ship; the under-attack look's among them), and a local copy of the ground textures in the/// git-ignored prototype Resources (Poly Haven CC0 and our generated crop rows; local until their asset batch)./// Unity -batchmode ... -executeMethod Statecraft.HexTiles.Capture.HexTilesAssets.Run</summary>public static class HexTilesAssets@@ -25,6 +25,12 @@ namespace Statecraft.HexTiles.Captureif (name == HexMaterials.Lit) m.SetFloat("_Smoothness", 0.05f);AssetDatabase.DeleteAsset(path); AssetDatabase.CreateAsset(m, path);}+ // The under-attack look's (HexUnderAttack): always rebuilt from their shaders, so a settings change lands.+ foreach (var name in HexUnderAttack.Materials)+ {+ var path = $"{Materials}/{name}.mat";+ AssetDatabase.DeleteAsset(path); AssetDatabase.CreateAsset(HexMaterials.FromShader(name), path);+ }if (Directory.Exists(GroundSource)){Directory.CreateDirectory(GroundLocal);diff --git a/unity/Assets/Editor/HexTiles/Capture/HexUnderAttackCapture.cs b/unity/Assets/Editor/HexTiles/Capture/HexUnderAttackCapture.csnew file mode 100644index 000000000..be732b8c0--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Capture/HexUnderAttackCapture.cs@@ -0,0 +1,94 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using Statecraft.Game.Map;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using Debug = UnityEngine.Debug;+using Object = UnityEngine.Object;++namespace Statecraft.HexTiles.Capture+{+ /// <summary>Before and after shots of the "under attack" look (HexUnderAttack) on a board, in a new, unsaved scene+ /// staged as HexBoardCapture stages it: a city hex and a unit hex, each at mid and close distance, without the look+ /// and with it at two pulse phases (the border low and high, the smoke a half-period apart). Writes+ /// <target>-before-{mid,close}.png, <target>-after-{low,high}-{mid,close}.png and stats.txt (the look's+ /// triangles, vertices and draws).+ /// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity+ /// -executeMethod Statecraft.HexTiles.Capture.HexUnderAttackCapture.Run [-board israel] [-city tel_aviv_city]+ /// [-unit palmach_squad] [-captureDir asset-staging/ui-local/hex-tiles/round2/attack] [-captureSize 3840x2160]</summary>+ public static class HexUnderAttackCapture+ {+ /// <summary>HexBoardCapture's tile shot distances: about three hexes, and one.</summary>+ const float MidDistanceM = 26000f, CloseDistanceM = 12500f;++ [MenuItem("Statecraft/Hex Tiles/Capture Under Attack")]+ public static void Run()+ {+ GameObject? root = null;+ try+ {+ var repo = Path.GetFullPath(Path.Combine(Application.dataPath, "..", ".."));+ var dir = Path.GetFullPath(Path.Combine(repo, HexBoardCapture.Arg("-captureDir") ?? "asset-staging/ui-local/hex-tiles/round2/attack"));+ var size = (HexBoardCapture.Arg("-captureSize") ?? "3840x2160").Split('x');+ int width = int.Parse(size[0]), height = int.Parse(size[1]);+ var boardId = HexBoardCapture.Arg("-board") ?? "israel";+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ var board = HexBoardCapture.LoadBoard(boardId);+ var cam = HexBoardCapture.Stage();+ (root, _) = HexBoardBuilder.Build(board, HexBoardCapture.Ground);+ var surface = new HexBoardSurface(board);+ Directory.CreateDirectory(dir);+ var city = HexBoardCapture.Arg("-city") ?? "tel_aviv_city";+ var unit = HexBoardCapture.Arg("-unit") ?? "palmach_squad";+ // The first hex (by q, r) with that tile or unit: on israel, Tel Aviv (-3,19) and the Palmach squad's hex.+ var hexes = board.Hexes.Values.OrderBy(h => h.q).ThenBy(h => h.r).ToList();+ var targets = new[]+ {+ ("city", hexes.FirstOrDefault(h => h.prototype == city) ?? throw new ArgumentException($"board {boardId} has no tile '{city}'")),+ ("unit", hexes.FirstOrDefault(h => h.unit == unit) ?? throw new ArgumentException($"board {boardId} has no unit '{unit}'")),+ };+ var lines = new List<string> { $"board {boardId}, {width}x{height}" };+ foreach (var (name, h) in targets)+ {+ var c = HexGeometry.Centre(h.q, h.r, HexScale.HexM);+ c.y = Mathf.Max(surface.Height(c), 0f);+ void Shoot(string shot)+ {+ HexBoardCapture.Shoot(cam, c, MidDistanceM, Path.Combine(dir, $"{name}-{shot}-mid.png"), width, height);+ HexBoardCapture.Shoot(cam, c, CloseDistanceM, Path.Combine(dir, $"{name}-{shot}-close.png"), width, height);+ }+ Shoot("before");+ var go = HexUnderAttack.Show(root.transform, surface, h.q, h.r);+ var look = go.GetComponent<HexUnderAttackLook>(); look.Hold = true;+ // Low and high border, half a pulse apart (the smoke has risen a little between them).+ const float t0 = 2f * HexUnderAttack.PulsePeriodS; // Pulse(t0) = 0+ look.Time(t0); Shoot("after-low");+ look.Time(t0 + HexUnderAttack.PulsePeriodS * 0.5f); Shoot("after-high");+ var meshes = go.GetComponentsInChildren<MeshFilter>().Select(f => f.sharedMesh).ToList();+ lines.Add($"{name}: {h.prototype} {(h.unit == "" ? "" : "+ " + h.unit + " ")}({h.q},{h.r}) | look: "+ + $"{meshes.Sum(m => m.triangles.Length / 3)} tris, {meshes.Sum(m => m.vertexCount)} verts, "+ + $"{go.GetComponentsInChildren<Renderer>().Length} draws ("+ + string.Join(", ", meshes.Select(m => $"{m.name} {m.triangles.Length / 3}")) + ")");+ HexUnderAttack.Hide(root.transform, h.q, h.r);+ }+ File.WriteAllLines(Path.Combine(dir, "stats.txt"), lines);+ Debug.Log("HEX UNDER ATTACK " + string.Join(" | ", lines) + " -> " + dir);+ }+ catch (Exception e)+ {+ Debug.LogError("HEX UNDER ATTACK CAPTURE FAILED " + e);+ if (Application.isBatchMode) EditorApplication.Exit(1);+ else throw;+ }+ finally+ {+ TiltShift.Reset();+ if (root != null) Object.DestroyImmediate(root);+ }+ }+ }+}diff --git a/unity/Assets/Editor/HexTiles/Capture/HexUnderAttackCapture.cs.meta b/unity/Assets/Editor/HexTiles/Capture/HexUnderAttackCapture.cs.metanew file mode 100644index 000000000..739abe5c6--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Capture/HexUnderAttackCapture.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 65988da3336514e6193a3fcc94185e51\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Painter/HexPainterCapture.cs b/unity/Assets/Editor/HexTiles/Painter/HexPainterCapture.csindex e272694b2..592a12540 100644--- a/unity/Assets/Editor/HexTiles/Painter/HexPainterCapture.cs+++ b/unity/Assets/Editor/HexTiles/Painter/HexPainterCapture.cs@@ -1,7 +1,10 @@#nullable enableusing System;+using System.Collections.Generic;using System.Diagnostics;+using System.Globalization;using System.IO;+using System.Linq;using Statecraft.Game.Map;using Statecraft.HexTiles.Capture;using UnityEditor;@@ -13,27 +16,81 @@ using Object = UnityEngine.Object;namespace Statecraft.HexTiles.Painter{/// <summary>The Hex Painter's path without its window, for checking it from the command line: loads a board as the- /// painter does, shoots one hex, makes one edit through HexPainter.Change (written to -overrides, by default a file- /// in the capture folder, so the board's own overrides are untouched), and shoots the hex again.+ /// painter does and runs a list of palette operations on one hex, shooting the hex before and after each. Edits go+ /// through HexPainter / HexPalette and are written to -overrides (by default a file in the capture folder, so the+ /// board's own overrides are untouched); the time-of-day and under-attack switches go through HexPainterSwitches and+ /// are undone after their shots, as the window undoes them./// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity- /// -executeMethod Statecraft.HexTiles.Painter.HexPainterCapture.Run -board israel -hex -3,19 -field prototype- /// -value kibbutz [-overrides <path>] [-captureDir asset-staging/ui-local/hex-tiles/painter] [-captureSize 3840x2160]- /// Writes <dir>/before.png, after.png and painter.txt (the overrides written, the rebuild time, the tile report).</summary>+ /// -executeMethod Statecraft.HexTiles.Painter.HexPainterCapture.Run -board israel -hex -3,19+ /// [-field prototype -value kibbutz | -field unit -value palmach_squad -facing 120] [-time dusk|night] [-attack]+ /// [-ops "prototype=kibbutz;unit=palmach_squad@120;time=dusk;time=night;attack"] [-thumbs]+ /// [-overrides <path>] [-captureDir asset-staging/ui-local/hex-tiles/painter] [-captureSize 3840x2160]+ /// -ops replaces -field, -time and -attack. -thumbs first makes the palette thumbnails (HexPaletteThumbs) and writes the+ /// contact sheet <dir>/palette.png and palette.txt. Writes <dir>/<n>-<op>/before.png and after.png per operation and+ /// <dir>/painter.txt (each operation, its time, the tile report, the overrides written).</summary>public static class HexPainterCapture{+ /// <summary>One operation: a field edit (prototype, ground, region, facing), a unit with a facing, a time of day,+ /// or the under-attack look.</summary>+ public sealed class Op+ {+ public string Kind = "", Value = ""; public float Facing;+ public string Folder(int n) => $"{n}-{Kind}" + (Value != "" ? "-" + Value : "") + (Kind == "unit" && Value != "" ? "-" + HexPalette.Degrees(Facing) : "");+ public override string ToString() => Kind == "attack" ? "attack" : Kind == "unit" && Value != "" ? $"unit={Value}@{HexPalette.Degrees(Facing)}" : $"{Kind}={Value}";+ }++ /// <summary>Parses "prototype=kibbutz;unit=palmach_squad@120;time=dusk;attack".</summary>+ public static List<Op> ParseOps(string ops) => ops.Split(';').Select(s => s.Trim()).Where(s => s != "").Select(s =>+ {+ if (s == "attack") return new Op { Kind = "attack" };+ int eq = s.IndexOf('=');+ if (eq < 0) throw new ArgumentException($"operation '{s}' is not field=value, time=..., or attack");+ var op = new Op { Kind = s.Substring(0, eq), Value = s.Substring(eq + 1) };+ int at = op.Value.IndexOf('@');+ if (op.Kind == "unit" && at >= 0) { op.Facing = float.Parse(op.Value.Substring(at + 1), CultureInfo.InvariantCulture); op.Value = op.Value.Substring(0, at); }+ if (op.Kind == "time" && !HexTimeOfDay.TryParse(op.Value, out _)) throw new ArgumentException($"time '{op.Value}' is not one of {string.Join(", ", HexTimeOfDay.Ids)}");+ if (op.Kind != "time") HexPainter.Validate(op.Kind, op.Value);+ return op;+ }).ToList();++ /// <summary>The operations from the command line: -ops, else -field/-value(/-facing), -time and -attack in that order.</summary>+ static List<Op> OpsFromArgs()+ {+ var ops = HexBoardCapture.Arg("-ops");+ if (ops != null) return ParseOps(ops);+ var parts = new List<string>();+ var field = HexBoardCapture.Arg("-field");+ if (field != null)+ {+ var facing = HexBoardCapture.Arg("-facing");+ parts.Add($"{field}={HexBoardCapture.Arg("-value") ?? ""}" + (field == "unit" && facing != null ? "@" + facing : ""));+ }+ if (HexBoardCapture.Arg("-time") is string time) parts.Add("time=" + time);+ if (Environment.GetCommandLineArgs().Contains("-attack")) parts.Add("attack");+ if (parts.Count == 0) throw new ArgumentException("nothing to do: give -field/-value, -time, -attack or -ops");+ return ParseOps(string.Join(";", parts));+ }+public static void Run(){try{- var repo = Path.GetFullPath(Path.Combine(Application.dataPath, "..", ".."));+ var repo = HexPalette.RepoRoot;var dir = Path.GetFullPath(Path.Combine(repo, HexBoardCapture.Arg("-captureDir") ?? "asset-staging/ui-local/hex-tiles/painter"));var size = (HexBoardCapture.Arg("-captureSize") ?? "3840x2160").Split('x');var hex = (HexBoardCapture.Arg("-hex") ?? throw new ArgumentException("-hex q,r")).Split(',');+ var ops = OpsFromArgs();Directory.CreateDirectory(dir);+ if (Environment.GetCommandLineArgs().Contains("-thumbs"))+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ var made = HexPaletteThumbs.MakeAll(HexPalette.ThumbsDir);+ HexPaletteThumbs.Sheet(HexPalette.ThumbsDir, Path.Combine(dir, "palette.png"), Path.Combine(dir, "palette.txt"));+ Debug.Log($"HEX PAINTER thumbnails: {made.Count} in {HexPalette.ThumbsDir}; contact sheet in {dir}");+ }var overrides = HexBoardCapture.Arg("-overrides") ?? Path.Combine(dir, "painter.overrides.json");if (HexBoardCapture.Arg("-overrides") == null && File.Exists(overrides)) File.Delete(overrides);- Shoot(HexBoardCapture.Arg("-board") ?? "israel", int.Parse(hex[0]), int.Parse(hex[1]), HexBoardCapture.Arg("-field") ?? "prototype",- HexBoardCapture.Arg("-value") ?? "", overrides, dir, int.Parse(size[0]), int.Parse(size[1]));+ Shoot(HexBoardCapture.Arg("-board") ?? "israel", int.Parse(hex[0]), int.Parse(hex[1]), ops, overrides, dir, int.Parse(size[0]), int.Parse(size[1]));}catch (Exception e){@@ -43,36 +100,79 @@ namespace Statecraft.HexTiles.Painter}}- static void Shoot(string boardId, int q, int r, string field, string value, string overrides, string dir, int width, int height)+ /// <summary>A unit or the attack look is shot at one hex's distance; the others at about three hexes.</summary>+ static float Distance(Op op) => op.Kind == "unit" || op.Kind == "attack" ? 12500f : 26000f;++ static void Shoot(string boardId, int q, int r, List<Op> ops, string overrides, string dir, int width, int height){EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);var cam = HexBoardCapture.Stage();var clock = Stopwatch.StartNew();var root = HexPainter.Load(boardId);long loadMs = clock.ElapsedMilliseconds;+ var switches = new HexPainterSwitches();+ var lines = new List<string> { $"board {boardId}: loaded in {loadMs} ms; hex ({q},{r}); {width}x{height}" };try{var state = root.GetComponent<HexBoardState>();var c = HexGeometry.Centre(q, r, HexScale.HexM);c.y = Mathf.Max(state.Surface.Height(c), 0f);var h = state.Board.Hexes[(q, r)];- string before = HexBoardOverrides.Get(h, field);- HexBoardCapture.Shoot(cam, c, 26000f, Path.Combine(dir, "before.png"), width, height);- clock.Restart();- var report = HexPainter.Change(root, overrides, q, r, field, value);- long rebuildMs = clock.ElapsedMilliseconds;- HexBoardCapture.Shoot(cam, c, 26000f, Path.Combine(dir, "after.png"), width, height);- var lines = new[]+ for (int i = 0; i < ops.Count; i++){- $"board {boardId}: loaded in {loadMs} ms; ({q},{r}) {field} '{before}' -> '{value}', rebuilt in {rebuildMs} ms",- "tile: " + (report?.ToString() ?? "none"),- "overrides written to " + overrides + ":", File.ReadAllText(overrides),- };+ var op = ops[i];+ var sub = Path.Combine(dir, op.Folder(i + 1));+ Directory.CreateDirectory(sub);+ HexBoardCapture.Shoot(cam, c, Distance(op), Path.Combine(sub, "before.png"), width, height);+ clock.Restart();+ string line;+ switch (op.Kind)+ {+ case "time":+ HexTimeOfDay.TryParse(op.Value, out var time);+ HexPainterStage.SetTime(switches, time, root);+ line = $"time {op.Value} applied in {clock.ElapsedMilliseconds} ms (preview: undone after the shot)";+ break;+ case "attack":+ switches.SetAttack(root.transform, state.Surface, q, r, true);+ line = $"under attack shown in {clock.ElapsedMilliseconds} ms, object '{HexUnderAttack.Name(q, r)}' present: {HexUnderAttack.IsShown(root.transform, q, r)} (preview: hidden after the shot)";+ break;+ case "unit" when op.Value != "":+ {+ string was = $"'{h.unit}' facing {HexPalette.Degrees(h.facing)}";+ var report = HexPalette.PlaceUnit(root, overrides, q, r, op.Value, op.Facing);+ line = $"unit {was} -> '{op.Value}' facing {HexPalette.Degrees(op.Facing)}, rebuilt in {clock.ElapsedMilliseconds} ms; tile: {report?.ToString() ?? "none"}";+ break;+ }+ case "prototype":+ {+ string was = h.prototype;+ HexPalette.Paint(root, overrides, new[] { (q, r) }, op.Value);+ line = $"prototype '{was}' -> '{op.Value}' (brush), rebuilt in {clock.ElapsedMilliseconds} ms; tile: {(state.Reports.TryGetValue((q, r), out var t) ? t.ToString() : "none")}";+ break;+ }+ default:+ {+ string was = HexBoardOverrides.Get(h, op.Kind);+ var report = HexPainter.Change(root, overrides, q, r, op.Kind, op.Value);+ line = $"{op.Kind} '{was}' -> '{op.Value}', rebuilt in {clock.ElapsedMilliseconds} ms; tile: {report?.ToString() ?? "none"}";+ break;+ }+ }+ if (op.Kind != "time" && op.Kind != "attack") switches.Rebuilt(q, r);+ HexBoardCapture.Shoot(cam, c, Distance(op), Path.Combine(sub, "after.png"), width, height);+ switches.Clear();+ lines.Add($"{i + 1}. {op} -> {op.Folder(i + 1)}/: {line}");+ }+ lines.Add($"switches after the run: time {HexTimeOfDay.Id(switches.Time)}, under attack on {switches.Attacked.Count} hexes, object present: {HexUnderAttack.IsShown(root.transform, q, r)}");+ lines.Add("overrides written to " + overrides + ":");+ lines.Add(File.Exists(overrides) ? File.ReadAllText(overrides) : "(none: no edit was written)");File.WriteAllLines(Path.Combine(dir, "painter.txt"), lines);Debug.Log("HEX PAINTER " + string.Join(" | ", lines) + " -> " + dir);}finally{+ switches.Clear();TiltShift.Reset();Object.DestroyImmediate(root);}diff --git a/unity/Assets/Editor/HexTiles/Painter/HexPainterStage.cs b/unity/Assets/Editor/HexTiles/Painter/HexPainterStage.csnew file mode 100644index 000000000..04f6ce7b2--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPainterStage.cs@@ -0,0 +1,49 @@+#nullable enable+using System.Linq;+using Statecraft.HexTiles.Capture;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.HexTiles.Painter+{+ /// <summary>The light and grade the painter's time-of-day switch works on: the Sun light and PostFX volume that+ /// HexBoardCapture.Stage makes ("Add the captures' light and grade"), found in the open scene or made once.</summary>+ public static class HexPainterStage+ {+ public const string SunName = "Sun", VolumeName = "PostFX";++ /// <summary>The scene's staged Sun and PostFX profile, or (null, null) when either is missing.</summary>+ public static (Light? sun, VolumeProfile? profile) Find()+ {+ var sun = Object.FindObjectsByType<Light>(FindObjectsSortMode.InstanceID)+ .FirstOrDefault(l => l.name == SunName && l.type == LightType.Directional);+ var volume = Object.FindObjectsByType<Volume>(FindObjectsSortMode.InstanceID)+ .FirstOrDefault(v => v.name == VolumeName && v.isGlobal);+ if (sun == null || volume == null) return (null, null);+ // Stage gives the volume its own profile instance, so editing it changes no asset.+ return (sun, volume.HasInstantiatedProfile() ? volume.profile : volume.sharedProfile);+ }++ /// <summary>The staged Sun and PostFX profile, staging them (HexBoardCapture.Stage) when the scene lacks either.</summary>+ public static (Light sun, VolumeProfile profile) FindOrStage()+ {+ var (sun, profile) = Find();+ if (sun == null || profile == null)+ {+ HexBoardCapture.Stage();+ (sun, profile) = Find();+ }+ return (sun!, profile!);+ }++ /// <summary>Switches <paramref name="switches"/> to <paramref name="time"/> on the staged light and grade and the+ /// board under <paramref name="boardRoot"/> (HexTimeOfDay.Apply), undoing the preset before it.</summary>+ public static void SetTime(HexPainterSwitches switches, HexTime time, GameObject? boardRoot)+ {+ switches.UndoTime(); // restore the day look before the light is looked up or staged+ if (time == HexTime.Day) return;+ var (sun, profile) = FindOrStage();+ switches.SetTime(time, t => HexTimeOfDay.Apply(t, profile, sun, boardRoot));+ }+ }+}diff --git a/unity/Assets/Editor/HexTiles/Painter/HexPainterStage.cs.meta b/unity/Assets/Editor/HexTiles/Painter/HexPainterStage.cs.metanew file mode 100644index 000000000..631cba84a--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPainterStage.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: eb561b543841b44a8bc0beaffd5f9dd6\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Painter/HexPainterSwitches.cs b/unity/Assets/Editor/HexTiles/Painter/HexPainterSwitches.csnew file mode 100644index 000000000..18ab8e3bf--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPainterSwitches.cs@@ -0,0 +1,99 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using UnityEngine;++namespace Statecraft.HexTiles.Painter+{+ /// <summary>The Hex Painter's transient looks: the time of day (HexTimeOfDay) and the under-attack preview+ /// (HexUnderAttack). Neither is written to a board or its overrides. It keeps the time preset's undo and runs it before+ /// the next preset and on Clear; it remembers which hexes show the attack look, re-shows one after its hex is rebuilt,+ /// and hides them all on Clear. The window calls Clear on unload, board reload, close and script reload, so nothing is+ /// left changed. The looks are passed in (the real ones by default) so tests can watch the calls.</summary>+ public sealed class HexPainterSwitches+ {+ readonly Func<Transform, IHexSurface, int, int, GameObject> show;+ readonly Func<Transform, int, int, bool> hide;+ readonly HashSet<(int q, int r)> attacked = new HashSet<(int q, int r)>();+ Action? undoTime;+ Func<HexTime, Action>? applyTime;+ Transform? board;+ IHexSurface? surface;++ public HexPainterSwitches(Func<Transform, IHexSurface, int, int, GameObject>? show = null, Func<Transform, int, int, bool>? hide = null)+ {+ this.show = show ?? ((b, s, q, r) => HexUnderAttack.Show(b, s, q, r));+ this.hide = hide ?? HexUnderAttack.Hide;+ }++ /// <summary>The preset applied now (Day when none is).</summary>+ public HexTime Time { get; private set; } = HexTime.Day;++ /// <summary>The hexes showing the under-attack look, in (q, r) order.</summary>+ public IReadOnlyList<(int q, int r)> Attacked => attacked.OrderBy(h => h.q).ThenBy(h => h.r).ToList();++ /// <summary>Undoes the preset applied now, then applies <paramref name="time"/> through <paramref name="apply"/>+ /// (HexTimeOfDay.Apply on the scene's light, grade and board) and keeps its undo.</summary>+ public void SetTime(HexTime time, Func<HexTime, Action> apply)+ {+ UndoTime();+ undoTime = apply(time);+ applyTime = apply;+ Time = time;+ }++ /// <summary>Undoes the preset applied now and applies it again: night's lit windows (HexNightWindows) are made+ /// from the board's pieces, so they go stale when a hex is rebuilt.</summary>+ public void ReapplyTime()+ {+ var (time, apply) = (Time, applyTime);+ if (apply == null) return;+ SetTime(time, apply);+ }++ /// <summary>Restores what the preset changed; the look is the day look again.</summary>+ public void UndoTime()+ {+ var undo = undoTime;+ undoTime = null; applyTime = null; Time = HexTime.Day;+ undo?.Invoke();+ }++ public bool IsAttacked(int q, int r) => attacked.Contains((q, r));++ /// <summary>Shows or hides the under-attack look on hex (q, r) of the board under <paramref name="boardRoot"/>.+ /// Hexes of another board are hidden first (a switch belongs to one board).</summary>+ public void SetAttack(Transform boardRoot, IHexSurface boardSurface, int q, int r, bool on)+ {+ if (board != boardRoot) ClearAttacks();+ board = boardRoot; surface = boardSurface;+ if (on) { show(boardRoot, boardSurface, q, r); attacked.Add((q, r)); }+ else if (attacked.Remove((q, r))) hide(boardRoot, q, r);+ }++ /// <summary>After hex (q, r) was rebuilt: applies the time preset again (so its look matches the rebuilt hex), and+ /// shows the hex's attack look again if it was on and the rebuild removed it.</summary>+ public void Rebuilt(int q, int r)+ {+ ReapplyTime();+ if (board == null || surface == null || !attacked.Contains((q, r))) return;+ if (!HexUnderAttack.IsShown(board, q, r)) show(board, surface, q, r);+ }++ /// <summary>Hides every attack look this switch showed (on the board while it still exists).</summary>+ public void ClearAttacks()+ {+ if (board != null) foreach (var (q, r) in Attacked) hide(board, q, r);+ attacked.Clear(); board = null; surface = null;+ }++ /// <summary>Undoes the time preset and hides every attack look. Call it before the board is torn down: a night+ /// preset may have changed the board's own objects.</summary>+ public void Clear()+ {+ ClearAttacks();+ UndoTime();+ }+ }+}diff --git a/unity/Assets/Editor/HexTiles/Painter/HexPainterSwitches.cs.meta b/unity/Assets/Editor/HexTiles/Painter/HexPainterSwitches.cs.metanew file mode 100644index 000000000..16653fe13--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPainterSwitches.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 41231503e2b174e3b9aac4a66c588992\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Painter/HexPainterWindow.cs b/unity/Assets/Editor/HexTiles/Painter/HexPainterWindow.csindex a2b2177bd..34e1578d7 100644--- a/unity/Assets/Editor/HexTiles/Painter/HexPainterWindow.cs+++ b/unity/Assets/Editor/HexTiles/Painter/HexPainterWindow.cs@@ -1,30 +1,51 @@#nullable enableusing System;+using System.Collections.Generic;using System.Globalization;using System.IO;using System.Linq;using UnityEditor;+using UnityEditor.SceneManagement;using UnityEngine;namespace Statecraft.HexTiles.Painter{/// <summary>Statecraft/Hex Tiles/Hex Painter: loads a board into the open scene (one object per hex), picks a hex by/// clicking it in the Scene view, and edits its hex-tile presentation: prototype, ground, unit, facing and region (the- /// trees of an environment hex). Each change rebuilds just that hex and is written to the board's+ /// trees of an environment hex). A palette of every registered tile and unit (HexPalette) paints tiles hex by hex as a+ /// brush and stands units with a facing. Each change rebuilds just that hex and is written to the board's/// <id>.overrides.json, so it survives regenerating the board (docs/hex-tiles/README.md, "Painting hexes by hand").- /// Terrain, control and locations are the map editor's (#1009), not the painter's. Editor only; the board in the scene- /// is never saved.</summary>+ /// The time-of-day and under-attack switches are previews only (HexPainterSwitches): never written, and undone on+ /// unload, reload, close and script reload. Terrain, control and locations are the map editor's (#1009), not the+ /// painter's. Editor only; the board in the scene is never saved.</summary>public sealed class HexPainterWindow : EditorWindow{const string None = "(none)";+ /// <summary>What a Scene-view click does: pick a hex, paint the brush tile on it, or stand the brush unit on it.</summary>+ enum Mode { Select, PaintTile, PlaceUnit }+ static readonly string[] ModeLabels = { "Select", "Paint tile", "Place unit" };+ const float Cell = 72f;+string[] boards = Array.Empty<string>();int boardIndex;string boardId = "";GameObject? root;(int q, int r)? selected;bool pick = true;+ Mode mode;+ /// <summary>The tile brush: null until one is picked, "" for no tile.</summary>+ string? brushTile;+ string brushUnit = "", filter = "";+ float brushFacing;string status = "";Vector2 scroll;+ /// <summary>Hexes painted in the current drag, so a drag paints each hex once.</summary>+ readonly HashSet<(int q, int r)> stroke = new HashSet<(int q, int r)>();+ readonly HashSet<string> folded = new HashSet<string>();+ List<HexPaletteGroup> tiles = new List<HexPaletteGroup>(), units = new List<HexPaletteGroup>();+ readonly Dictionary<string, Texture2D?> thumbs = new Dictionary<string, Texture2D?>();+ /// <summary>The time-of-day and under-attack previews (public so tests can watch what the window undoes).</summary>+ public HexPainterSwitches Switches { get; set; } = new HexPainterSwitches();[MenuItem("Statecraft/Hex Tiles/Hex Painter")]public static void Open() => GetWindow<HexPainterWindow>("Hex Painter");@@ -37,9 +58,36 @@ namespace Statecraft.HexTiles.PainterSceneView.duringSceneGui += OnScene;boards = Directory.Exists(BoardsDir) ? HexPainter.BoardIds(BoardsDir) : Array.Empty<string>();boardIndex = Mathf.Max(0, Array.IndexOf(boards, boardId));+ RefreshPalette();+ }++ /// <summary>Closing the window and reloading scripts both come here: nothing the switches changed is left behind.</summary>+ void OnDisable()+ {+ SceneView.duringSceneGui -= OnScene;+ Switches.Clear();+ DropThumbs();+ }++ void RefreshPalette()+ {+ try { tiles = HexPalette.Tiles(); units = HexPalette.Units(); }+ catch (Exception e) { status = e.Message; Debug.LogException(e); }+ DropThumbs();+ }++ void DropThumbs()+ {+ foreach (var t in thumbs.Values) if (t != null) DestroyImmediate(t);+ thumbs.Clear();}- void OnDisable() => SceneView.duringSceneGui -= OnScene;+ Texture2D? Thumb(HexPaletteEntry e)+ {+ var key = (e.IsUnit ? "unit-" : "") + e.Id;+ if (!thumbs.TryGetValue(key, out var t)) thumbs[key] = t = HexPalette.LoadThumb(HexPalette.ThumbsDir, e);+ return t;+ }void OnGUI(){@@ -50,23 +98,55 @@ namespace Statecraft.HexTiles.PainterboardIndex = EditorGUILayout.Popup(boardIndex, boards);using (new EditorGUI.DisabledScope(boards.Length == 0))if (GUILayout.Button("Load into scene", GUILayout.Width(120))) Load(boards[boardIndex]);+ using (new EditorGUI.DisabledScope(root == null))+ if (GUILayout.Button("Unload", GUILayout.Width(70))) UnloadAll();}- if (GUILayout.Button("Add the captures' light and grade")) Capture.HexBoardCapture.Stage();+ if (GUILayout.Button("Add the captures' light and grade")) HexPainterStage.FindOrStage();+ TimeOfDay();var state = State;if (state == null){EditorGUILayout.HelpBox("Load a board, then click a hex in the Scene view.", MessageType.Info);+ Palette(null);EditorGUILayout.EndScrollView();return;}EditorGUILayout.LabelField($"{boardId}: {state.Board.Hexes.Count} hexes. Edits go to {boardId}{HexBoardOverrides.Suffix}.json");pick = EditorGUILayout.ToggleLeft("Pick hexes in the Scene view", pick);+ mode = (Mode)GUILayout.Toolbar((int)mode, ModeLabels);+ if (mode == Mode.PaintTile) EditorGUILayout.HelpBox(brushTile == null ? "Pick a tile in the palette below." : $"Click or drag over hexes to paint {(brushTile == "" ? "no tile" : brushTile)}.", MessageType.None);+ if (mode == Mode.PlaceUnit) EditorGUILayout.HelpBox(brushUnit == "" ? "Pick a unit in the palette below." : $"Click a hex to stand {brushUnit} on it, facing {HexPalette.Degrees(brushFacing)} deg.", MessageType.None);EditorGUILayout.Space();+ SelectedHex(state);+ if (status != "") EditorGUILayout.HelpBox(status, MessageType.None);+ Palette(state);+ EditorGUILayout.EndScrollView();+ }++ void TimeOfDay()+ {+ using (new EditorGUILayout.HorizontalScope())+ {+ EditorGUILayout.LabelField("Time of day (preview)", GUILayout.Width(140));+ int now = (int)Switches.Time;+ int next = GUILayout.Toolbar(now, new[] { "Day", "Dusk", "Night" });+ if (next != now) SetTime((HexTime)next);+ }+ }++ void SetTime(HexTime time)+ {+ try { HexPainterStage.SetTime(Switches, time, root); status = $"time of day: {HexTimeOfDay.Id(time)} (preview, not saved)"; }+ catch (Exception e) { status = e.Message; Debug.LogException(e); }+ SceneView.RepaintAll();+ }++ void SelectedHex(HexBoardState state)+ {if (selected == null || !state.Board.Hexes.TryGetValue(selected.Value, out var h)){EditorGUILayout.HelpBox("No hex selected.", MessageType.None);- EditorGUILayout.EndScrollView();return;}var (q, r) = selected.Value;@@ -78,11 +158,82 @@ namespace Statecraft.HexTiles.PainterChoice(q, r, "unit", h.unit, HexUnitTypes.All.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray(), true);Choice(q, r, "region", h.region, state.Board.Regions.Keys.OrderBy(k => k, StringComparer.Ordinal).ToArray(), true);float facing = EditorGUILayout.DelayedFloatField("Facing (deg from north)", h.facing);- if (!Mathf.Approximately(facing, h.facing)) Apply(q, r, "facing", facing.ToString("R", CultureInfo.InvariantCulture));- if (status != "") EditorGUILayout.HelpBox(status, MessageType.None);- EditorGUILayout.EndScrollView();+ if (!Mathf.Approximately(facing, h.facing)) Apply(q, r, () => HexPalette.Face(root!, OverridesPath, q, r, facing), $"facing = {HexPalette.Degrees(facing)}");+ using (new EditorGUILayout.HorizontalScope())+ {+ using (new EditorGUI.DisabledScope(h.unit == ""))+ {+ foreach (var (label, deg) in HexPalette.Facings)+ if (GUILayout.Button(label, GUILayout.Width(38))) Apply(q, r, () => HexPalette.Face(root!, OverridesPath, q, r, deg), $"facing = {HexPalette.Degrees(deg)}");+ if (GUILayout.Button("Clear unit")) Apply(q, r, () => HexPalette.ClearUnit(root!, OverridesPath, q, r), "unit cleared");+ }+ }+ bool attacked = Switches.IsAttacked(q, r);+ bool want = EditorGUILayout.ToggleLeft("Under attack (preview, not saved)", attacked);+ if (want != attacked)+ {+ try { Switches.SetAttack(root!.transform, state.Surface, q, r, want); }+ catch (Exception e) { status = e.Message; Debug.LogException(e); }+ SceneView.RepaintAll();+ }+ }++ /// <summary>The palette: tiles by kind and region, then units by characters and vehicles, each a thumbnail (or its+ /// id when none was made) that becomes the brush. The unit brush has six hex-direction facings and a free angle.</summary>+ void Palette(HexBoardState? state)+ {+ EditorGUILayout.Space();+ EditorGUILayout.LabelField("Palette", EditorStyles.boldLabel);+ using (new EditorGUILayout.HorizontalScope())+ {+ filter = EditorGUILayout.TextField("Filter", filter);+ if (GUILayout.Button("Refresh", GUILayout.Width(70))) RefreshPalette();+ if (GUILayout.Button("Make thumbnails", GUILayout.Width(120))) MakeThumbnails();+ }+ EditorGUILayout.LabelField("Tiles", EditorStyles.miniBoldLabel);+ foreach (var g in tiles) Group(g, brushTile ?? "", id => { brushTile = id; mode = Mode.PaintTile; });+ if (GUILayout.Button("Brush: no tile (clears a hex's prototype)")) { brushTile = ""; mode = Mode.PaintTile; }++ EditorGUILayout.Space();+ EditorGUILayout.LabelField("Units", EditorStyles.miniBoldLabel);+ foreach (var g in units) Group(g, brushUnit, id => { brushUnit = id; mode = Mode.PlaceUnit; });+ using (new EditorGUILayout.HorizontalScope())+ {+ EditorGUILayout.LabelField("Unit facing", GUILayout.Width(80));+ foreach (var (label, deg) in HexPalette.Facings)+ if (GUILayout.Toggle(Mathf.Approximately(brushFacing, deg), label, EditorStyles.miniButton, GUILayout.Width(38))) brushFacing = deg;+ brushFacing = EditorGUILayout.FloatField(brushFacing, GUILayout.Width(60));+ }+ using (new EditorGUI.DisabledScope(state == null || selected == null || brushUnit == ""))+ if (GUILayout.Button("Stand the unit on the selected hex") && selected != null) PlaceUnit(selected.Value.q, selected.Value.r);}+ void Group(HexPaletteGroup g, string current, Action<string> choose)+ {+ var shown = g.Entries.Where(e => filter == "" || e.Id.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0+ || e.Title.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0).ToList();+ if (shown.Count == 0) return;+ bool open = !folded.Contains(g.Name);+ bool next = EditorGUILayout.Foldout(open, $"{g.Name} ({shown.Count})", true);+ if (next != open) { if (next) folded.Remove(g.Name); else folded.Add(g.Name); }+ if (!next) return;+ int columns = Mathf.Max(1, (int)((position.width - 30f) / (Cell + 4f)));+ for (int i = 0; i < shown.Count; i += columns)+ using (new EditorGUILayout.HorizontalScope())+ foreach (var e in shown.Skip(i).Take(columns))+ {+ var tex = Thumb(e);+ var content = tex != null ? new GUIContent(tex, $"{e.Id}\n{e.Title}") : new GUIContent(e.Id, e.Title);+ var style = tex != null ? GUI.skin.button : new GUIStyle(GUI.skin.button) { wordWrap = true, fontSize = 9 };+ bool on = e.Id == current;+ if (GUILayout.Toggle(on, content, style, GUILayout.Width(Cell), GUILayout.Height(Cell)) && !on) choose(e.Id);+ }+ var chosen = shown.FirstOrDefault(e => e.Id == current);+ if (chosen != null) EditorGUILayout.LabelField(" " + chosen.Title, EditorStyles.miniLabel);+ }++ string OverridesPath => HexPainter.OverridesPath(BoardsDir, boardId);+/// <summary>A dropdown of <paramref name="options"/> (with "(none)" for an empty value when allowed); a new pick/// is applied at once.</summary>void Choice(int q, int r, string field, string current, string[] options, bool allowNone)@@ -91,26 +242,38 @@ namespace Statecraft.HexTiles.Painterint at = Array.IndexOf(shown, current == "" && allowNone ? None : current);if (at < 0) { shown = shown.Append(current).ToArray(); at = shown.Length - 1; } // a value no longer registeredint next = EditorGUILayout.Popup(ObjectNames.NicifyVariableName(field), at, shown);- if (next != at) Apply(q, r, field, shown[next] == None ? "" : shown[next]);+ if (next == at) return;+ var value = shown[next] == None ? "" : shown[next];+ Apply(q, r, () => HexPainter.Change(root!, OverridesPath, q, r, field, value), $"{field} = '{value}'");}- void Apply(int q, int r, string field, string value)+ /// <summary>Runs one edit of hex (q, r), re-imports the overrides, and re-shows its under-attack preview.</summary>+ void Apply(int q, int r, Func<HexTileReport?> edit, string what){if (root == null) return;- var path = HexPainter.OverridesPath(BoardsDir, boardId);try{- var report = HexPainter.Change(root, path, q, r, field, value);- HexPainter.Import(path);- status = $"({q},{r}) {field} = '{value}', written to {Path.GetFileName(path)}\n" + (report?.ToString() ?? "no tile on this hex");+ var report = edit();+ HexPainter.Import(OverridesPath);+ Switches.Rebuilt(q, r);+ status = $"({q},{r}) {what}, written to {Path.GetFileName(OverridesPath)}\n" + (report?.ToString() ?? "no tile on this hex");}catch (Exception e) { status = e.Message; Debug.LogException(e); }SceneView.RepaintAll();}+ void PaintTile(int q, int r, string id) => Apply(q, r, () =>+ {+ HexPalette.Paint(root!, OverridesPath, new[] { (q, r) }, id);+ return State!.Reports.TryGetValue((q, r), out var report) ? report : null;+ }, $"painted '{id}'");++ void PlaceUnit(int q, int r) =>+ Apply(q, r, () => HexPalette.PlaceUnit(root!, OverridesPath, q, r, brushUnit, brushFacing), $"unit = '{brushUnit}', facing {HexPalette.Degrees(brushFacing)}");+void Load(string id){- foreach (var old in HexPainter.LoadedBoards()) Unload(old.gameObject);+ UnloadAll();boardId = id; selected = null;try{@@ -124,12 +287,44 @@ namespace Statecraft.HexTiles.Paintercatch (Exception e) { status = e.Message; Debug.LogException(e); }}+ /// <summary>Undoes the previews (while the board still stands) and removes every painter board from the scene.</summary>+ public void UnloadAll()+ {+ Switches.Clear();+ foreach (var old in HexPainter.LoadedBoards()) Unload(old.gameObject);+ root = null; selected = null;+ }+static void Unload(GameObject board){board.GetComponent<HexBoardAssets>()?.Teardown();DestroyImmediate(board);}+ /// <summary>Makes every thumbnail in a new empty scene (after asking to save the open one), then reopens the scene+ /// and the board.</summary>+ void MakeThumbnails()+ {+ if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) return;+ string reload = root != null ? boardId : "";+ UnloadAll();+ var scene = EditorSceneManager.GetActiveScene().path;+ try+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ var made = HexPaletteThumbs.MakeAll(HexPalette.ThumbsDir);+ status = $"{made.Count} thumbnails in {HexPalette.ThumbsDir}";+ }+ catch (Exception e) { status = e.Message; Debug.LogException(e); }+ finally+ {+ if (scene != "") EditorSceneManager.OpenScene(scene, OpenSceneMode.Single);+ else EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ RefreshPalette();+ if (reload != "") Load(reload);+ }+ }+void OnScene(SceneView view){var state = State;@@ -137,18 +332,28 @@ namespace Statecraft.HexTiles.Paintervar e = Event.current;int control = GUIUtility.GetControlID(FocusType.Passive);if (pick && e.type == EventType.Layout) HandleUtility.AddDefaultControl(control);- if (pick && e.type == EventType.MouseDown && e.button == 0 && !e.alt)+ if (pick && e.button == 0 && !e.alt && (e.type == EventType.MouseDown || (e.type == EventType.MouseDrag && mode == Mode.PaintTile))){+ if (e.type == EventType.MouseDown) stroke.Clear();var hit = HexPainter.Pick(root, HandleUtility.GUIPointToWorldRay(e.mousePosition));- if (hit != null) { selected = hit; status = ""; Repaint(); e.Use(); }+ if (hit != null)+ {+ var (q, r) = hit.Value;+ bool changed = selected != hit;+ selected = hit; if (changed) status = "";+ if (mode == Mode.PaintTile && brushTile != null && stroke.Add(hit.Value)) PaintTile(q, r, brushTile);+ else if (mode == Mode.PlaceUnit && e.type == EventType.MouseDown && brushUnit != "") PlaceUnit(q, r);+ Repaint(); e.Use();+ }}+ if (e.type == EventType.MouseUp) stroke.Clear();if (selected != null && e.type == EventType.Repaint){var (q, r) = selected.Value;var corners = HexGeometry.Corners(HexGeometry.Centre(q, r, HexScale.HexM), HexScale.HexM).Select(c => root.transform.TransformPoint(new Vector3(c.x, Mathf.Max(state.Surface.Height(c), 0f) + 60f, c.z))).ToList();corners.Add(corners[0]);- Handles.color = new Color(1f, 0.85f, 0.2f);+ Handles.color = mode == Mode.PaintTile ? new Color(0.3f, 0.9f, 1f) : new Color(1f, 0.85f, 0.2f);Handles.DrawAAPolyLine(6f, corners.ToArray());}}diff --git a/unity/Assets/Editor/HexTiles/Painter/HexPalette.cs b/unity/Assets/Editor/HexTiles/Painter/HexPalette.csnew file mode 100644index 000000000..1dbfabb24--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPalette.cs@@ -0,0 +1,156 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Linq;+using UnityEngine;++namespace Statecraft.HexTiles.Painter+{+ /// <summary>One palette entry: a prototype or a unit type, by its registered id.</summary>+ public sealed class HexPaletteEntry+ {+ public string Id = "", Title = "", Kind = "", Region = "";+ public bool IsUnit;+ public override string ToString() => $"{Id} ({Title})";+ }++ /// <summary>A palette group: a heading ("farm, north", "characters") and its entries in order.</summary>+ public sealed class HexPaletteGroup+ {+ public string Name = "";+ public List<HexPaletteEntry> Entries = new List<HexPaletteEntry>();+ }++ /// <summary>The Hex Painter's palette and brushes, apart from its window so tests can drive them. The groups come from+ /// what is registered (HexPrototype's Kind and Region, a unit type's members), never from a list kept here, so a new+ /// prototype or unit file shows up in the palette by itself.</summary>+ public static class HexPalette+ {+ /// <summary>The region group of a prototype drawn for anywhere (Region "").</summary>+ public const string AnyRegion = "any";+ public const string Characters = "characters", Vehicles = "vehicles", OtherUnits = "other units";++ /// <summary>Every registered prototype, grouped by Kind (HexPrototypes.Kinds order; none or unknown is "other"),+ /// then by Region (HexPrototypes.Regions order, then "any"), ids in ordinal order inside a group.</summary>+ public static List<HexPaletteGroup> Tiles() => GroupTiles(HexPrototypes.All.Keys.Select(id =>+ {+ var info = HexPrototypes.Info(id);+ return new HexPaletteEntry { Id = id, Title = HexPrototypes.Create(id).Title, Kind = info.Kind, Region = info.Region };+ }));++ /// <summary>The grouping of <see cref="Tiles"/>, for any entries.</summary>+ public static List<HexPaletteGroup> GroupTiles(IEnumerable<HexPaletteEntry> entries)+ {+ string Kind(HexPaletteEntry e) => HexPrototypes.Kinds.Contains(e.Kind) ? e.Kind : "other";+ string Region(HexPaletteEntry e) => HexPrototypes.Regions.Contains(e.Region) ? e.Region : AnyRegion;+ int RegionOrder(string region) => region == AnyRegion ? HexPrototypes.Regions.Length : Array.IndexOf(HexPrototypes.Regions, region);+ return entries.GroupBy(e => (kind: Kind(e), region: Region(e)))+ .OrderBy(g => Array.IndexOf(HexPrototypes.Kinds, g.Key.kind)).ThenBy(g => RegionOrder(g.Key.region))+ .Select(g => new HexPaletteGroup+ {+ Name = g.Key.region == AnyRegion ? g.Key.kind : $"{g.Key.kind}, {g.Key.region}",+ Entries = g.OrderBy(e => e.Id, StringComparer.Ordinal).ToList(),+ }).ToList();+ }++ /// <summary>Every registered unit type: characters (a squad of HexUnitScale.Characters figures), then vehicles+ /// (one vehicle each), told apart by the members its Create() returns. Anything else is "other units", so the+ /// palette still lists every type once. Call it once per window, not per frame: it creates each unit.</summary>+ public static List<HexPaletteGroup> Units() => GroupUnits(HexUnitTypes.All.Keys.Select(id =>+ {+ var type = HexUnitTypes.Create(id);+ return (new HexPaletteEntry { Id = id, Title = type.Title, IsUnit = true }, type.Create());+ }));++ /// <summary>The grouping of <see cref="Units"/>, for any (entry, unit) pairs; empty groups are left out.</summary>+ public static List<HexPaletteGroup> GroupUnits(IEnumerable<(HexPaletteEntry entry, HexUnit unit)> units)+ {+ var order = new[] { Characters, Vehicles, OtherUnits };+ var grouped = units.Select(u => { u.entry.Kind = UnitGroup(u.unit); return u.entry; }).ToList();+ return grouped.GroupBy(e => e.Kind).OrderBy(g => Array.IndexOf(order, g.Key))+ .Select(g => new HexPaletteGroup { Name = g.Key, Entries = g.OrderBy(e => e.Id, StringComparer.Ordinal).ToList() })+ .ToList();+ }++ /// <summary>Characters: exactly HexUnitScale.Characters figures. Vehicles: one member that is not a figure.</summary>+ public static string UnitGroup(HexUnit unit) =>+ unit.Members.Count == HexUnitScale.Characters && unit.Members.All(m => m.StandIn == StandIn.Figure) ? Characters+ : unit.Members.Count == 1 && unit.Members[0].StandIn != StandIn.Figure ? Vehicles+ : OtherUnits;++ // --- Facing ---++ /// <summary>The six hex directions as facings (degrees from north, clockwise seen from above, as HexUnitMotion+ /// reads them), in HexGeometry.Neighbours order, each with a compass label: the heading from a hex's centre to+ /// that neighbour's.</summary>+ public static IReadOnlyList<(string label, float degrees)> Facings { get; } = HexGeometry.Neighbours.Select(n =>+ {+ var a = HexGeometry.Centre(0, 0, HexScale.HexM); var b = HexGeometry.Centre(n.q, n.r, HexScale.HexM);+ float deg = Mathf.Repeat(Mathf.Round(Mathf.Atan2(b.x - a.x, b.z - a.z) * Mathf.Rad2Deg), 360f);+ return (Compass(deg), deg);+ }).OrderBy(f => f.deg).ToList();++ static string Compass(float deg) => new[] { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }[Mathf.RoundToInt(deg / 45f) % 8];++ public static string Degrees(float facing) => facing.ToString("R", CultureInfo.InvariantCulture);++ // --- Brushes (each edit goes through HexPainter, so it is written to the overrides and rebuilds the hex) ---++ /// <summary>Paints prototype <paramref name="id"/> ("" for none) on each hex, through HexPainter.Change: each is+ /// rebuilt and recorded in the overrides at <paramref name="overridesPath"/>. Returns the hexes painted.</summary>+ public static List<(int q, int r)> Paint(GameObject root, string overridesPath, IEnumerable<(int q, int r)> hexes, string id)+ {+ var done = new List<(int q, int r)>();+ foreach (var (q, r) in hexes.Distinct())+ {+ HexPainter.Change(root, overridesPath, q, r, "prototype", id);+ done.Add((q, r));+ }+ return done;+ }++ /// <summary>Stands unit <paramref name="unit"/> on hex (q, r) facing <paramref name="facing"/>: both fields are+ /// recorded in the overrides, and the hex is rebuilt once.</summary>+ public static HexTileReport? PlaceUnit(GameObject root, string overridesPath, int q, int r, string unit, float facing)+ {+ if (unit == "") throw new ArgumentException("no unit: use ClearUnit");+ var state = root.GetComponent<HexBoardState>() ?? throw new InvalidOperationException("load the board with the Hex Painter first");+ HexPainter.Validate("unit", unit);+ HexPainter.Write(state.Board, overridesPath, q, r, "facing", Degrees(facing));+ return HexPainter.Change(root, overridesPath, q, r, "unit", unit);+ }++ /// <summary>Removes the unit from hex (q, r) (recorded as an empty unit, so it stays off after regenerating).</summary>+ public static HexTileReport? ClearUnit(GameObject root, string overridesPath, int q, int r) =>+ HexPainter.Change(root, overridesPath, q, r, "unit", "");++ /// <summary>Turns the unit on hex (q, r) to <paramref name="facing"/>.</summary>+ public static HexTileReport? Face(GameObject root, string overridesPath, int q, int r, float facing) =>+ HexPainter.Change(root, overridesPath, q, r, "facing", Degrees(facing));++ // --- Thumbnails ---++ /// <summary>The git-ignored thumbnail folder, from the repo root.</summary>+ public const string ThumbsFolder = "asset-staging/ui-local/hex-tiles/thumbs";++ public static string RepoRoot => Path.GetFullPath(Path.Combine(Application.dataPath, "..", ".."));+ public static string ThumbsDir => Path.Combine(RepoRoot, ThumbsFolder);++ /// <summary><dir>/<id>.png for a prototype, <dir>/unit-<id>.png for a unit.</summary>+ public static string ThumbPath(string dir, HexPaletteEntry e) => Path.Combine(dir, (e.IsUnit ? "unit-" : "") + e.Id + ".png");++ /// <summary>The thumbnail of <paramref name="e"/>, or null when none was made (the palette then shows its text).+ /// The caller owns the texture.</summary>+ public static Texture2D? LoadThumb(string dir, HexPaletteEntry e)+ {+ var path = ThumbPath(dir, e);+ if (!File.Exists(path)) return null;+ var tex = new Texture2D(2, 2, TextureFormat.RGB24, false) { hideFlags = HideFlags.HideAndDontSave, name = Path.GetFileName(path) };+ if (tex.LoadImage(File.ReadAllBytes(path))) return tex;+ UnityEngine.Object.DestroyImmediate(tex);+ return null;+ }+ }+}diff --git a/unity/Assets/Editor/HexTiles/Painter/HexPalette.cs.meta b/unity/Assets/Editor/HexTiles/Painter/HexPalette.cs.metanew file mode 100644index 000000000..2f9144d54--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPalette.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ea9162f094456404f8506f6d6cae4ba3\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Painter/HexPaletteThumbs.cs b/unity/Assets/Editor/HexTiles/Painter/HexPaletteThumbs.csnew file mode 100644index 000000000..4ff0ba9c2--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPaletteThumbs.cs@@ -0,0 +1,160 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using Statecraft.Game.Map;+using Statecraft.HexTiles.Capture;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using Debug = UnityEngine.Debug;+using Object = UnityEngine.Object;++namespace Statecraft.HexTiles.Painter+{+ /// <summary>The palette's thumbnails: each prototype on a one-hex board with a ring of plain ground round it, each+ /// unit on plain grass, shot with the captures' camera, light and grade (HexBoardCapture) at about 256 px into the+ /// git-ignored asset-staging/ui-local/hex-tiles/thumbs (<id>.png, unit-<id>.png); plus a contact sheet of them in+ /// palette order with a text listing beside it.+ /// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity+ /// -executeMethod Statecraft.HexTiles.Painter.HexPaletteThumbs.Run [-thumbSize 256] [-only <id,...>]+ /// [-sheetDir asset-staging/ui-local/hex-tiles/round2/painter]</summary>+ public static class HexPaletteThumbs+ {+ /// <summary>Shot distances: a tile's hex fills the square; a unit's figures fill it.</summary>+ const float TileDistanceM = 15000f, UnitDistanceM = 8500f;+ /// <summary>A unit faces south-east in its thumbnail: three-quarters towards the camera, which looks north.</summary>+ const float UnitFacing = 150f;+ public const int Size = 256, SheetColumns = 8;++ public static void Run()+ {+ try+ {+ int size = int.Parse(HexBoardCapture.Arg("-thumbSize") ?? Size.ToString());+ var only = HexBoardCapture.Arg("-only")?.Split(',');+ var sheetDir = Path.Combine(HexPalette.RepoRoot, HexBoardCapture.Arg("-sheetDir") ?? "asset-staging/ui-local/hex-tiles/round2/painter");+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ var written = MakeAll(HexPalette.ThumbsDir, size, only);+ Sheet(HexPalette.ThumbsDir, Path.Combine(sheetDir, "palette.png"), Path.Combine(sheetDir, "palette.txt"), size);+ Debug.Log($"HEX PALETTE THUMBS {written.Count} -> {HexPalette.ThumbsDir}; sheet -> {sheetDir}");+ }+ catch (Exception e)+ {+ Debug.LogError("HEX PALETTE THUMBS FAILED " + e);+ if (Application.isBatchMode) EditorApplication.Exit(1);+ else throw;+ }+ }++ /// <summary>Every palette entry, tiles then units, in palette order.</summary>+ public static List<(HexPaletteGroup group, HexPaletteEntry entry)> Ordered() =>+ HexPalette.Tiles().Concat(HexPalette.Units()).SelectMany(g => g.Entries.Select(e => (g, e))).ToList();++ /// <summary>Makes the thumbnails of every entry (or of the ids in <paramref name="only"/>) into+ /// <paramref name="dir"/>, in the open scene, which should be empty: it adds the captures' light and grade.</summary>+ public static List<string> MakeAll(string dir, int size = Size, string[]? only = null)+ {+ Directory.CreateDirectory(dir);+ var cam = HexBoardCapture.Stage();+ var written = new List<string>();+ try+ {+ foreach (var (_, e) in Ordered().Where(p => only == null || only.Contains(p.entry.Id)))+ {+ var path = HexPalette.ThumbPath(dir, e);+ Make(cam, e, path, size);+ written.Add(path);+ }+ }+ finally { TiltShift.Reset(); }+ return written;+ }++ /// <summary>One thumbnail: builds the entry's little board, shoots it, and destroys it.</summary>+ public static void Make(Camera cam, HexPaletteEntry e, string path, int size)+ {+ var board = ThumbBoard(e);+ var root = HexBoardBuilder.Build(board, HexBoardCapture.Ground).root;+ try+ {+ var surface = new HexBoardSurface(board);+ var c = HexGeometry.Centre(0, 0, HexScale.HexM);+ c.y = Mathf.Max(surface.Height(c), 0f);+ HexBoardCapture.Shoot(cam, c, e.IsUnit ? UnitDistanceM : TileDistanceM, path, size, size);+ }+ finally+ {+ root.GetComponent<HexBoardAssets>()?.Teardown();+ Object.DestroyImmediate(root);+ }+ }++ /// <summary>Hex (0, 0) with the entry (a prototype on its own terrain and ground; a unit on flat grass) and a ring of+ /// six plain hexes of the same ground round it.</summary>+ public static HexBoard ThumbBoard(HexPaletteEntry e)+ {+ string terrain = "flat", ground = "grass";+ if (!e.IsUnit)+ {+ var proto = HexPrototypes.Create(e.Id);+ terrain = proto.Terrain.ToString().ToLowerInvariant(); ground = proto.Ground;+ }+ string ring = terrain == "mountain" ? "hills" : terrain == "water" ? "flat" : terrain;+ var hexes = new List<BoardHex>+ {+ new BoardHex { q = 0, r = 0, terrain = terrain, ground = ground, prototype = e.IsUnit ? "" : e.Id, unit = e.IsUnit ? e.Id : "", facing = UnitFacing },+ };+ hexes.AddRange(HexGeometry.Neighbours.Select(n => new BoardHex { q = n.q, r = n.r, terrain = ring, ground = ground }));+ return new HexBoard(new HexBoardFile { id = "thumb-" + e.Id, hexes = hexes.ToArray() });+ }++ /// <summary>The contact sheet: the thumbnails in palette order, SheetColumns to a row, each group starting a new+ /// row (a missing thumbnail is a grey cell), and a text listing of each cell's row, column, group, id and title.</summary>+ public static void Sheet(string thumbsDir, string pngPath, string txtPath, int cell = Size)+ {+ var cells = new List<(int row, int col, HexPaletteGroup group, HexPaletteEntry entry)>();+ int row = 0;+ foreach (var g in HexPalette.Tiles().Concat(HexPalette.Units()))+ {+ for (int i = 0; i < g.Entries.Count; i++) cells.Add((row + i / SheetColumns, i % SheetColumns, g, g.Entries[i]));+ row += (g.Entries.Count + SheetColumns - 1) / SheetColumns;+ }+ var sheet = new Texture2D(SheetColumns * cell, Math.Max(row, 1) * cell, TextureFormat.RGB24, false);+ var fill = Enumerable.Repeat(new Color32(40, 40, 40, 255), sheet.width * sheet.height).ToArray();+ sheet.SetPixels32(fill);+ var lines = new List<string> { $"Hex Painter palette: {cells.Count} entries, {SheetColumns} to a row, each group on new rows; cells {cell} px; row 1 is the top." };+ string lastGroup = "";+ foreach (var (r, c, g, e) in cells)+ {+ if (g.Name != lastGroup) { lines.Add(""); lines.Add($"[{g.Name}]"); lastGroup = g.Name; }+ var thumb = HexPalette.LoadThumb(thumbsDir, e);+ bool has = thumb != null; // read before the texture is destroyed: a destroyed texture equals null+ if (thumb != null)+ {+ var px = Scaled(thumb, cell);+ sheet.SetPixels(c * cell, sheet.height - (r + 1) * cell, cell, cell, px);+ Object.DestroyImmediate(thumb);+ }+ lines.Add($" row {r + 1}, col {c + 1}: {e.Id} {e.Title}{(has ? "" : " (no thumbnail)")}");+ }+ sheet.Apply();+ Directory.CreateDirectory(Path.GetDirectoryName(pngPath)!);+ File.WriteAllBytes(pngPath, sheet.EncodeToPNG());+ File.WriteAllLines(txtPath, lines);+ Object.DestroyImmediate(sheet);+ }++ /// <summary>A thumbnail's pixels at <paramref name="cell"/> square (nearest sample; thumbnails are made at that size).</summary>+ static Color[] Scaled(Texture2D t, int cell)+ {+ if (t.width == cell && t.height == cell) return t.GetPixels();+ var src = t.GetPixels(); var dst = new Color[cell * cell];+ for (int y = 0; y < cell; y++)+ for (int x = 0; x < cell; x++)+ dst[y * cell + x] = src[(y * t.height / cell) * t.width + x * t.width / cell];+ return dst;+ }+ }+}diff --git a/unity/Assets/Editor/HexTiles/Painter/HexPaletteThumbs.cs.meta b/unity/Assets/Editor/HexTiles/Painter/HexPaletteThumbs.cs.metanew file mode 100644index 000000000..7d2e4a703--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Painter/HexPaletteThumbs.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: c46993be8e3004b86ae1c6f9cdda65b7\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Tests/HexBoardCaptureTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexBoardCaptureTests.csnew file mode 100644index 000000000..32744c250--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexBoardCaptureTests.cs@@ -0,0 +1,53 @@+#nullable enable+using System.Linq;+using NUnit.Framework;+using Statecraft.HexTiles;+using Statecraft.HexTiles.Capture;+using UnityEngine;+using Object = UnityEngine.Object;++/// <summary>The whole-board capture's framing (HexBoardCapture.BoardDistance): a board framed whole shows all of its+/// rect, the near (southern) edge included, at landscape and portrait sizes; a small board keeps the standard distance.</summary>+public class HexBoardCaptureTests+{+ /// <summary>The shot's aim, as HexBoardCapture.Capture takes it: the mean hex centre, on the ground.</summary>+ static Vector3 Middle(HexBoard board)+ {+ var surface = new HexBoardSurface(board);+ var cs = board.Hexes.Values.Select(h => HexGeometry.Centre(h.q, h.r, HexScale.HexM)).ToList();+ var m = new Vector3(cs.Average(c => c.x), 0f, cs.Average(c => c.z));+ return new Vector3(m.x, Mathf.Max(surface.Height(m), 0f), m.z);+ }++ [TestCase("israel", 3840, 2160)]+ [TestCase("israel", 2160, 3840)]+ public void EveryCornerOfAWholeBoardIsInView(string id, int width, int height)+ {+ var board = HexBoard.Load(id);+ var lookAt = Middle(board);+ float distance = HexBoardCapture.BoardDistance(board, lookAt, width / (float)height);+ Assert.That(distance, Is.GreaterThan(2f * HexBoardCapture.BoardDistanceM), "the board is framed whole");+ // A real camera, placed as Shoot places it, checks the projection independently of BoardDistance's own maths.+ var cam = new GameObject("cam").AddComponent<Camera>();+ try+ {+ cam.fieldOfView = HexBoardCapture.Fov; cam.aspect = width / (float)height; cam.nearClipPlane = 50f; cam.farClipPlane = 1_000_000f;+ cam.transform.rotation = Quaternion.Euler(HexBoardCapture.Pitch, 0f, 0f);+ cam.transform.position = lookAt - cam.transform.forward * distance;+ var b = HexBoardBuilder.Bounds(board);+ foreach (var c in new[] { new Vector3(b.xMin, 0f, b.yMin), new Vector3(b.xMax, 0f, b.yMin), new Vector3(b.xMin, 0f, b.yMax), new Vector3(b.xMax, 0f, b.yMax) })+ {+ var v = cam.WorldToViewportPoint(c);+ Assert.That(v.x >= 0f && v.x <= 1f && v.y >= 0f && v.y <= 1f && v.z > cam.nearClipPlane && v.z < cam.farClipPlane, $"{id} {width}x{height}: corner {c} at {v}");+ }+ }+ finally { Object.DestroyImmediate(cam.gameObject); }+ }++ [Test]+ public void ASmallBoardKeepsTheStandardDistance()+ {+ var board = HexBoard.Load("tel_aviv");+ Assert.That(HexBoardCapture.BoardDistance(board, Middle(board), 16f / 9f), Is.EqualTo(HexBoardCapture.BoardDistanceM));+ }+}diff --git a/unity/Assets/Editor/HexTiles/Tests/HexBoardCaptureTests.cs.meta b/unity/Assets/Editor/HexTiles/Tests/HexBoardCaptureTests.cs.metanew file mode 100644index 000000000..d3af76d50--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexBoardCaptureTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: b20a498a5a40248e091b518884e57b03\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Tests/HexModelMeshTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexModelMeshTests.csnew file mode 100644index 000000000..469fe3317--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexModelMeshTests.cs@@ -0,0 +1,228 @@+#nullable enable+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game.Map.Kits;+using Statecraft.HexTiles;+using Statecraft.HexTiles.Capture;+using UnityEditor;+using UnityEngine;++/// <summary>Buildings must be whole (Tal, 19 October 2026: a Tel Aviv block with its walls missing, grass through its+/// windows). The buildings' materials cull back faces and Tripo's buildings are open underneath, so a view ray that meets+/// a building but none of its front faces shows the ground through it: every building mesh the hex tiles resolve to (ids+/// "sandbox:hq_*", "sandbox:kit_*" and "town:*") keeps that share of its view rays within <see cref="Tolerance"/>+/// (HexMeshCheck.SeeThrough). Open edges are not the test: the shipped b*-v2+/// meshes have thousands (T-junctions, hairline cracks and the open base), so they are reported only. The decimated+/// sandbox kit (planar dissolve) dropped faces; the shipped b*-v2 town models (TownModelSet) are whole. It writes the+/// measurements of every candidate mesh (the local sandbox prefabs and the set's full and mid meshes) to+/// asset-staging/ui-local/hex-tiles/round2/buildings/mesh-report.txt, and checks that each sandbox id drawn as a town+/// model faces the way its sandbox prefab faced (the prototypes turn doors to the street by the sandbox frame).+/// Not caught: a hole whose rays meet nothing behind it (a roof hole over the open base); the close shots+/// (HexModelCapture) are the check for that.</summary>+public class HexModelMeshTests+{+ /// <summary>The share of view rays a resolved building may see through (a few stray inverted faces in a Tripo mesh).</summary>+ const float Tolerance = 0.005f;+ /// <summary>Shipped models allowed a little more, each for a reason seen in its HexModelCapture sheet: thin slivers+ /// between balcony slabs, not a missing wall (Tal chose the full meshes on 19 October 2026 knowing of them).</summary>+ static readonly Dictionary<string, float> Slivers = new Dictionary<string, float>(System.StringComparer.Ordinal)+ {+ ["b02a-tel-aviv-corner-block-v2"] = 0.0065f, // 0.55%: between the balcony slabs+ ["b13a-netanya-two-storey-v2"] = 0.008f, // 0.69%: under the balcony slabs+ };++ static float ToleranceFor(GameObject drawn) => Slivers.TryGetValue(drawn.name, out var t) ? t : Tolerance;+ /// <summary>Another turn must lie this much nearer than the drawn one to count as a wrong facing.</summary>+ const float FacingMargin = 0.8f;++ static bool Building(string id) => id.StartsWith("sandbox:hq_") || id.StartsWith("sandbox:kit_") || id.StartsWith(HexModels.TownPrefix);++ /// <summary>Every building id a registered prototype places, with the concrete ids it resolves to there.</summary>+ static IEnumerable<string> ResolvedBuildings()+ {+ var ids = new SortedSet<string>(System.StringComparer.Ordinal);+ foreach (var proto in HexPrototypes.All.Keys)+ foreach (var seed in new[] { 1948, 7 })+ foreach (var (q, r) in new[] { (2, -1), (-3, 19), (0, 0) })+ {+ var ctx = new HexTileContext(q, r, new FlatSurface(), seed);+ HexPrototypes.Create(proto).Build(ctx);+ foreach (var p in ctx.Placements) if (Building(p.Model)) ids.Add(HexModels.Resolve(p.Model, p.Position));+ }+ return ids;+ }++ static Mesh Cube() => Resources.GetBuiltinResource<Mesh>("Cube.fbx");++ /// <summary>The check itself: Unity's cube (split vertices, welded here) is whole; without its top face, rays from+ /// above meet the inside of its bottom face (a back face) and see through.</summary>+ [Test]+ public void CheckSeesAMissingFace()+ {+ var whole = HexMeshCheck.Of(new[] { (Cube(), Matrix4x4.identity) });+ Assert.That(whole.SeeThrough, Is.Zero, whole.ToString());+ Assert.That(whole.Open, Is.Zero, whole.ToString());+ var open = Object.Instantiate(Cube());+ try+ {+ var v = open.vertices; var t = open.triangles;+ bool Top(int i) => v[t[3 * i]].y > 0.4f && v[t[3 * i + 1]].y > 0.4f && v[t[3 * i + 2]].y > 0.4f;+ open.triangles = Enumerable.Range(0, t.Length / 3).Where(i => !Top(i)).SelectMany(i => new[] { t[3 * i], t[3 * i + 1], t[3 * i + 2] }).ToArray();+ var m = HexMeshCheck.Of(new[] { (open, Matrix4x4.identity) });+ Assert.That(m.SeeThroughShare, Is.GreaterThan(Tolerance), m.ToString());+ Assert.That(m.OpenOffBase, Is.EqualTo(4), m.ToString());+ }+ finally { Object.DestroyImmediate(open); }+ }++ [Test]+ public void ResolvedBuildingsAreWhole()+ {+ WriteReport();+ var holes = new List<string>(); int checkedCount = 0;+ foreach (var id in ResolvedBuildings())+ {+ var prefab = HexModels.Prefab(id);+ if (prefab == null) continue; // drawn as its stand-in on this machine+ var m = HexMeshCheck.Of(prefab); checkedCount++;+ if (m.SeeThroughShare > ToleranceFor(prefab)) holes.Add($"{id} ({prefab.name}): {m}");+ }+ Assert.That(checkedCount, Is.GreaterThan(0), "no building model resolved (no town set and no local sandbox kit)");+ Assert.That(holes, Is.Empty, "buildings that show the ground through their walls:\n" + string.Join("\n", holes));+ }++ // The set's baked mid levels are not tested here: the hex tiles draw only full meshes (Tal, 19 October 2026), and+ // most mid levels see through (the report lists them); they are the main map's, a follow-up of their own.++ /// <summary>With the town models off (or their set missing) a sandbox id draws its sandbox prefab again, or nothing+ /// (its stand-in) on a machine without it; a "town:" id draws nothing. With them on, it draws its town model.</summary>+ [Test]+ public void WithoutTownModelsTheSandboxPrefabDraws()+ {+ var (first, town, _) = HexModels.TownAliases[0];+ try+ {+ HexModels.DrawTownModels = false; HexModels.Clear();+ foreach (var (id, _, _) in HexModels.TownAliases)+ Assert.That(HexModels.Prefab(id), Is.EqualTo(Resources.Load<GameObject>(HexModels.PathOf(id))), id);+ Assert.That(HexModels.Prefab(town), Is.Null, town);+ }+ finally { HexModels.DrawTownModels = true; HexModels.Clear(); }+ var drawn = HexModels.Prefab(first);+ Assert.That(drawn, Is.Not.Null, first);+ Assert.That(drawn!.name, Is.EqualTo(town.Substring(HexModels.TownPrefix.Length)), first);+ Assert.That(drawn.activeInHierarchy, Is.False, "a template must not draw itself");+ }++ /// <summary>Every sandbox id drawn as the same Tripo model keeps its facing: of the four quarter turns, the sandbox+ /// prefab's vertices lie nearest the town model's as drawn (both in the unit frame), unless another turn is within+ /// <see cref="FacingMargin"/> of it (a near-symmetric block, where the close shots decide). Mirrors are reported, not+ /// tested: the renderer cannot draw a negative scale.</summary>+ [Test]+ public void TownAliasesFaceAsTheirSandboxPrefabs()+ {+ var wrong = new List<string>(); int compared = 0;+ foreach (var (id, town, same) in HexModels.TownAliases)+ {+ if (!same) continue; // a remap to another model: nothing to match+ var sandbox = Resources.Load<GameObject>(HexModels.PathOf(id));+ var drawn = HexModels.Prefab(id);+ if (sandbox == null || drawn == null || drawn == sandbox) continue;+ var scores = HexMeshCheck.Facing(sandbox, drawn); compared++;+ var turns = scores.Take(4).ToArray();+ int best = System.Array.IndexOf(turns, turns.Min());+ if (best != 0 && turns[best] < FacingMargin * turns[0]) wrong.Add($"{id} -> {town}: best {HexMeshCheck.FacingNames[best]} ({scores[best]:F4}) vs as drawn {scores[0]:F4}");+ }+ if (compared == 0) Assert.Ignore("no local sandbox prefabs to compare");+ Assert.That(wrong, Is.Empty, string.Join("\n", wrong));+ }++ static void WriteReport()+ {+ var lines = new List<string>+ {+ "Hex-tile building meshes. seeThru: share of view rays on the model (8 sides x 20/35/50 degrees down, 96x96 each)",+ "that meet no front face of it (back faces are culled, so the ground shows through): the test. Informational:",+ "backFirst: rays whose first face is a back face (also one-sided railings and awnings seen from behind);",+ "open: boundary edges after welding by position; offBase: those above the base plane (min height + 0.5%);",+ "nonMan: edges of 3+ faces (the shipped meshes have thousands of T-junction and crack edges that never show).",+ "Written by HexModelMeshTests.",+ "",+ $"{"mesh".PadRight(58)} {"tris",6} {"seeThru",8} {"backFirst",9} {"open",6} {"offBase",8} {"nonMan",7}",+ };+ void Row(string name, HexMeshCheck.Result r) => lines.Add($"{name.PadRight(58)} {r.Triangles,6} {r.SeeThroughShare,8:P2} {r.BackFirstShare,9:P2} {r.Open,6} {r.OpenOffBase,8} {r.NonManifold,7}");+ lines.Add("-- local sandbox prefabs (Resources/HexSandbox, git-ignored) --");+ foreach (var go in Resources.LoadAll<GameObject>("HexSandbox").Where(g => g.name.StartsWith("hq_") || g.name.StartsWith("kit_")).OrderBy(g => g.name, System.StringComparer.Ordinal))+ Row("sandbox:" + go.name, HexMeshCheck.Of(go));+ var set = AssetDatabase.LoadAssetAtPath<TownModelSet>(TownModels.SetPath);+ lines.Add("-- TownModelSet (" + TownModels.SetPath + ") --");+ if (set != null)+ foreach (TownModel t in System.Enum.GetValues(typeof(TownModel)))+ {+ Row(TownModels.Ids[(int)t] + " full", HexMeshCheck.Of(new[] { (set.Mesh(t), HexModels.TownTurn) }));+ Row(TownModels.Ids[(int)t] + " mid", HexMeshCheck.Of(new[] { (set.mid[(int)t], HexModels.TownTurn) }));+ }+ lines.Add("-- what each building id resolves to now --");+ foreach (var id in ResolvedBuildings())+ {+ var prefab = HexModels.Prefab(id);+ if (prefab == null) { lines.Add($"{id.PadRight(58)} (stand-in)"); continue; }+ Row(id + " -> " + prefab.name, HexMeshCheck.Of(prefab));+ }+ lines.Add("-- facing: sandbox prefab vs drawn town model, mean nearest distance (unit frame) per turn --");+ foreach (var (id, town, same) in HexModels.TownAliases)+ {+ var sandbox = Resources.Load<GameObject>(HexModels.PathOf(id));+ var drawn = HexModels.Prefab(id);+ if (!same || sandbox == null || drawn == null || drawn == sandbox) { lines.Add($"{id} -> {town}: {(same ? "not compared" : "remap")}"); continue; }+ var s = HexMeshCheck.Facing(sandbox, drawn);+ lines.Add($"{id} -> {town}: " + string.Join(" ", s.Select((v, i) => $"{HexMeshCheck.FacingNames[i]}={v:F4}")));+ }+ lines.AddRange(BudgetLines());+ // Only on a machine with the local asset-staging folder: a test must not make an untracked folder on any clone.+ var staging = Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", "asset-staging"));+ var path = Path.Combine(staging, "ui-local/hex-tiles/round2/buildings/mesh-report.txt");+ if (Directory.Exists(staging)) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllLines(path, lines); }+ Debug.Log("HEX MESH REPORT" + (Directory.Exists(staging) ? " -> " + path : "") + "\n" + string.Join("\n", lines));+ }++ /// <summary>Each building tile's triangles on KeepsToItsTriangleBudget's hex ((2,-1), seed 1948) by which level the+ /// town aliases draw: the sandbox kit (town models off), every alias full, every alias mid, and mid only where the+ /// mid level is whole (within <see cref="Tolerance"/>), else full.</summary>+ static List<string> BudgetLines()+ {+ var lines = new List<string> { "-- triangles per building tile at hex (2,-1), seed 1948, by the level the aliases draw --",+ $"{"tile".PadRight(22)} {"budget",7} {"sandbox",8} {"all full",9} {"all mid",8} {"mid where whole",16}" };+ var set = HexModels.TownSet();+ if (set == null) return lines;+ var alias = HexModels.TownAliases.ToDictionary(a => a.id, a => a.town);+ var whole = new Dictionary<int, bool>();+ int Index(string town) => System.Array.IndexOf(TownModels.Ids, town.Substring(HexModels.TownPrefix.Length).Replace(HexModels.MidSuffix, ""));+ bool MidWhole(int i) => whole.TryGetValue(i, out var w) ? w : whole[i] = HexMeshCheck.Of(new[] { (set.mid[i], HexModels.TownTurn) }).SeeThroughShare <= Tolerance;+ foreach (var id in HexPrototypes.All.Keys.OrderBy(k => k, System.StringComparer.Ordinal))+ {+ var proto = HexPrototypes.Create(id);+ var ctx = new HexTileContext(2, -1, new FlatSurface(), 1948);+ proto.Build(ctx);+ if (!ctx.Placements.Any(p => alias.ContainsKey(HexModels.Resolve(p.Model, p.Position)))) continue;+ int Sum(System.Func<int, bool> mid) => ctx.Placements.Sum(p =>+ {+ if (p.StandIn == StandIn.Flat) return 12;+ if (!alias.TryGetValue(HexModels.Resolve(p.Model, p.Position), out var t)) return HexModels.Triangles(p.Model, p.StandIn, p.Position);+ int i = Index(t);+ return HexModels.IndexTriangles(mid(i) ? set.mid[i] : set.meshes[i]);+ });+ int sandbox;+ try+ {+ HexModels.DrawTownModels = false; HexModels.Clear();+ sandbox = ctx.Placements.Sum(p => p.StandIn == StandIn.Flat ? 12 : HexModels.Triangles(p.Model, p.StandIn, p.Position));+ }+ finally { HexModels.DrawTownModels = true; HexModels.Clear(); }+ lines.Add($"{id.PadRight(22)} {proto.TriangleBudget,7} {sandbox,8} {Sum(_ => false),9} {Sum(_ => true),8} {Sum(MidWhole),16}");+ }+ return lines;+ }+}diff --git a/unity/Assets/Editor/HexTiles/Tests/HexModelMeshTests.cs.meta b/unity/Assets/Editor/HexTiles/Tests/HexModelMeshTests.cs.metanew file mode 100644index 000000000..388584109--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexModelMeshTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ab779ab845ac24ba2900ed7f5176e71d\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Tests/HexPainterTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexPainterTests.csindex e8d9f85ce..d972f2205 100644--- a/unity/Assets/Editor/HexTiles/Tests/HexPainterTests.cs+++ b/unity/Assets/Editor/HexTiles/Tests/HexPainterTests.cs@@ -11,8 +11,8 @@ using UnityEditor.SceneManagement;using UnityEngine;using Object = UnityEngine.Object;-/// <summary>The map builder's hand edits (HexBoardOverrides), the Hex Painter's write-back and one-hex rebuild, and-/// the environment's region species (docs/hex-tiles/README.md, "Laying out the whole map").</summary>+/// <summary>The map builder's hand edits (HexBoardOverrides), the Hex Painter's write-back and one-hex rebuild, its+/// palette, brushes and preview switches, and the environment's region species (docs/hex-tiles/README.md, "Laying out the whole map").</summary>public class HexPainterTests{string dir = "";@@ -221,6 +221,242 @@ public class HexPainterTests}}+ // --- The palette ---++ [Test]+ public void TheTilesPaletteListsEveryPrototypeOnceInKindThenRegionOrder()+ {+ var groups = HexPalette.Tiles();+ var ids = groups.SelectMany(g => g.Entries).Select(e => e.Id).ToList();+ Assert.That(ids.Count, Is.EqualTo(ids.Distinct().Count()), "listed twice");+ CollectionAssert.AreEquivalent(HexPrototypes.All.Keys, ids);+ int Order(HexPaletteEntry e) => Array.IndexOf(HexPrototypes.Kinds, HexPrototypes.Kinds.Contains(e.Kind) ? e.Kind : "other") * 10+ + (HexPrototypes.Regions.Contains(e.Region) ? Array.IndexOf(HexPrototypes.Regions, e.Region) : HexPrototypes.Regions.Length);+ var orders = groups.SelectMany(g => g.Entries).Select(Order).ToList();+ Assert.That(orders, Is.Ordered, "kind order, then region order");+ Assert.That(groups.Select(g => g.Name), Is.Unique);+ foreach (var e in groups.SelectMany(g => g.Entries))+ Assert.That((e.Kind, e.Region, e.Title), Is.EqualTo((HexPrototypes.Info(e.Id).Kind, HexPrototypes.Info(e.Id).Region, HexPrototypes.Create(e.Id).Title)));+ }++ [Test]+ public void TheTilesGroupingComesFromTheAttributeNotAList()+ {+ // As the regional variants another lane adds will register: farm and forest, north, centre or south.+ HexPaletteEntry E(string id, string kind, string region = "") => new HexPaletteEntry { Id = id, Kind = kind, Region = region };+ var groups = HexPalette.GroupTiles(new[]+ {+ E("wheat_fields_south_a", "farm", "south"), E("odd_one", ""), E("pine_forest_north_b", "forest", "north"), E("wheat_fields", "farm"),+ E("wheat_fields_north_b", "farm", "north"), E("wheat_fields_north_a", "farm", "north"), E("tel_aviv_city", "city"), E("odd_two", "nowhere", "mars"),+ });+ Assert.That(groups.Select(g => g.Name), Is.EqualTo(new[] { "city", "farm, north", "farm, south", "farm", "forest, north", "other" }));+ Assert.That(groups[1].Entries.Select(e => e.Id), Is.EqualTo(new[] { "wheat_fields_north_a", "wheat_fields_north_b" }));+ Assert.That(groups.Last().Entries.Select(e => e.Id), Is.EqualTo(new[] { "odd_one", "odd_two" }));+ }++ [Test]+ public void TheUnitsPaletteListsEveryUnitTypeOnceCharactersThenVehicles()+ {+ var groups = HexPalette.Units();+ var ids = groups.SelectMany(g => g.Entries).Select(e => e.Id).ToList();+ Assert.That(ids.Count, Is.EqualTo(ids.Distinct().Count()), "listed twice");+ CollectionAssert.AreEquivalent(HexUnitTypes.All.Keys, ids);+ Assert.That(groups.Select(g => g.Name).Take(2), Is.EqualTo(new[] { HexPalette.Characters, HexPalette.Vehicles }));+ foreach (var e in groups[0].Entries) Assert.That(HexUnitTypes.Create(e.Id).Create().Members.Count, Is.EqualTo(HexUnitScale.Characters), e.Id);+ foreach (var e in groups[1].Entries) Assert.That(HexUnitTypes.Create(e.Id).Create().Members.Count, Is.EqualTo(1), e.Id);+ Assert.That(groups[0].Entries.Select(e => e.Id), Does.Contain("palmach_squad"));+ Assert.That(groups[1].Entries.Select(e => e.Id), Does.Contain("willys_jeep"));+ Assert.That(groups.SelectMany(g => g.Entries).All(e => e.IsUnit));+ }++ [Test]+ public void TheSixFacingsPointAtTheSixNeighbours()+ {+ Assert.That(HexPalette.Facings.Select(f => f.degrees), Is.EqualTo(new[] { 30f, 90f, 150f, 210f, 270f, 330f }));+ Assert.That(HexPalette.Facings.Select(f => f.label), Is.EqualTo(new[] { "NE", "E", "SE", "SW", "W", "NW" }));+ // East is the neighbour (1, 0): the heading HexUnitMotion gives a unit walking there.+ var east = HexGeometry.Centre(1, 0, HexScale.HexM) - HexGeometry.Centre(0, 0, HexScale.HexM);+ Assert.That(Mathf.Atan2(east.x, east.z) * Mathf.Rad2Deg, Is.EqualTo(90f).Within(1e-3f));+ }++ /// <summary>A small per-hex board in a new scene, as the painter loads one.</summary>+ static GameObject PainterBoard()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ var file = new HexBoardFile { id = "t", hexes = new[] { Hex(0, 0), Hex(1, 0, "pine_forest"), Hex(0, 1, ""), Hex(-1, 1, unit: "palmach_squad") } };+ return HexBoardBuilder.Build(new HexBoard(file), null, options: new HexBoardBuilder.Options { PerHex = true }).root;+ }++ static void Destroy(GameObject? root)+ {+ if (root == null) return;+ root.GetComponent<HexBoardAssets>().Teardown();+ Object.DestroyImmediate(root);+ }++ [Test]+ public void TheBrushWritesAnOverrideForEachPaintedHex()+ {+ var root = PainterBoard();+ try+ {+ var path = HexPainter.OverridesPath(dir, "t");+ var painted = HexPalette.Paint(root, path, new[] { (0, 0), (1, 0), (0, 1), (1, 0) }, "kibbutz");+ Assert.That(painted, Is.EqualTo(new[] { (0, 0), (1, 0), (0, 1) }), "a hex painted twice in a stroke is painted once");+ var saved = HexBoardOverrides.FromJson(File.ReadAllText(path));+ Assert.That(All(saved), Is.EqualTo(new[] { (0, 0, "prototype", "kibbutz"), (1, 0, "prototype", "kibbutz"), (0, 1, "prototype", "kibbutz") }));+ var state = root.GetComponent<HexBoardState>();+ var pieces = root.transform.Find(HexBoardBuilder.PiecesName);+ foreach (var hex in painted)+ {+ Assert.That(state.Board.Hexes[hex].prototype, Is.EqualTo("kibbutz"));+ Assert.That(state.Reports[hex].Prototype, Is.EqualTo("kibbutz"), "the hex was rebuilt");+ Assert.That(pieces.Find(HexBoardBuilder.HexName(hex.Item1, hex.Item2)), Is.Not.Null);+ }+ }+ finally { Destroy(root); }+ }++ [Test]+ public void PlacingAUnitWritesItsUnitAndFacingAndClearingRemovesIt()+ {+ var root = PainterBoard();+ try+ {+ var path = HexPainter.OverridesPath(dir, "t");+ HexPalette.PlaceUnit(root, path, 0, 0, "willys_jeep", 120f);+ var saved = HexBoardOverrides.FromJson(File.ReadAllText(path));+ Assert.That(All(saved), Is.EqualTo(new[] { (0, 0, "unit", "willys_jeep"), (0, 0, "facing", "120") }));+ var h = root.GetComponent<HexBoardState>().Board.Hexes[(0, 0)];+ Assert.That((h.unit, h.facing), Is.EqualTo(("willys_jeep", 120f)));+ var unit = root.transform.Find(HexBoardBuilder.UnitsName).Find(HexBoardBuilder.UnitName(0, 0));+ Assert.That(unit.childCount, Is.EqualTo(1));+ Assert.That(unit.GetChild(0).localEulerAngles.y, Is.EqualTo(Mathf.Repeat(120f - 90f, 360f)).Within(0.01f), "the jeep's -90 model turn on top of the facing");++ HexPalette.Face(root, path, 0, 0, 270f);+ Assert.That(HexBoardOverrides.FromJson(File.ReadAllText(path)).List("facing").Single().value, Is.EqualTo("270"));+ HexPalette.ClearUnit(root, path, 0, 0);+ Assert.That(root.transform.Find(HexBoardBuilder.UnitsName).Find(HexBoardBuilder.UnitName(0, 0)), Is.Null);+ Assert.That(HexBoardOverrides.FromJson(File.ReadAllText(path)).List("unit").Single().value, Is.EqualTo(""), "cleared stays cleared after regenerating");+ Assert.Throws<ArgumentException>(() => HexPalette.PlaceUnit(root, path, 0, 0, "no_such_unit", 0f));+ }+ finally { Destroy(root); }+ }++ // --- The time-of-day and under-attack switches (previews: undone, never written) ---++ [Test]+ public void TheTimeOfDayIsUndoneBeforeTheNextPresetAndOnClear()+ {+ var log = new List<string>();+ Action Apply(HexTime t) { log.Add("apply " + HexTimeOfDay.Id(t)); return () => log.Add("undo " + HexTimeOfDay.Id(t)); }+ var switches = new HexPainterSwitches();+ switches.SetTime(HexTime.Dusk, Apply);+ switches.SetTime(HexTime.Night, Apply);+ Assert.That(switches.Time, Is.EqualTo(HexTime.Night));+ // A painter edit rebuilds a hex: night's lit windows are made again for it.+ switches.Rebuilt(0, 0);+ Assert.That(switches.Time, Is.EqualTo(HexTime.Night));+ switches.Clear();+ switches.Clear();+ switches.Rebuilt(0, 0); // day: nothing to apply again+ Assert.That(log, Is.EqualTo(new[] { "apply dusk", "undo dusk", "apply night", "undo night", "apply night", "undo night" }));+ Assert.That(switches.Time, Is.EqualTo(HexTime.Day));+ }++ [Test]+ public void UnderAttackSurvivesARebuildAndIsHiddenOnClearNeverWritten()+ {+ var root = PainterBoard();+ try+ {+ var hidden = new List<(int, int)>();+ var switches = new HexPainterSwitches(hide: (b, q, r) => { hidden.Add((q, r)); return HexUnderAttack.Hide(b, q, r); });+ var state = root.GetComponent<HexBoardState>();+ var path = HexPainter.OverridesPath(dir, "t");+ switches.SetAttack(root.transform, state.Surface, 0, 0, true);+ switches.SetAttack(root.transform, state.Surface, 1, 0, true);+ HexPainter.Change(root, path, 0, 0, "prototype", "kibbutz");+ switches.Rebuilt(0, 0);+ Assert.That(HexUnderAttack.IsShown(root.transform, 0, 0), Is.True, "after the hex's rebuild");+ switches.SetAttack(root.transform, state.Surface, 1, 0, false);+ Assert.That(HexUnderAttack.IsShown(root.transform, 1, 0), Is.False);+ switches.Clear();+ Assert.That(hidden, Is.EqualTo(new[] { (1, 0), (0, 0) }));+ Assert.That(HexUnderAttack.IsShown(root.transform, 0, 0), Is.False);+ Assert.That(switches.Attacked, Is.Empty);+ Assert.That(File.ReadAllText(path), Does.Not.Contain("attack"));+ Assert.That(All(HexBoardOverrides.FromJson(File.ReadAllText(path))), Is.EqualTo(new[] { (0, 0, "prototype", "kibbutz") }));+ }+ finally { Destroy(root); }+ }++ [Test]+ public void TheWindowUndoesTheSwitchesOnUnloadAndOnClose()+ {+ var root = PainterBoard();+ var window = ScriptableObject.CreateInstance<HexPainterWindow>();+ try+ {+ var log = new List<string>();+ window.Switches = new HexPainterSwitches(hide: (b, q, r) => { log.Add($"hide {q},{r}"); return HexUnderAttack.Hide(b, q, r); });+ window.Switches.SetTime(HexTime.Night, t => () => log.Add("undo night"));+ window.Switches.SetAttack(root.transform, root.GetComponent<HexBoardState>().Surface, 0, 0, true);+ window.UnloadAll();+ Assert.That(log, Is.EqualTo(new[] { "hide 0,0", "undo night" }), "the previews are undone while the board still stands");+ Assert.That(root == null, Is.True, "the board is unloaded");++ log.Clear();+ window.Switches.SetTime(HexTime.Dusk, t => () => log.Add("undo dusk"));+ Object.DestroyImmediate(window); // closing the window (and a script reload) runs OnDisable+ Assert.That(log, Is.EqualTo(new[] { "undo dusk" }));+ }+ finally+ {+ if (window != null) Object.DestroyImmediate(window);+ Destroy(root);+ }+ }++ // --- Thumbnails and the command line ---++ [Test]+ public void AMissingThumbnailFallsBackToText()+ {+ var tile = new HexPaletteEntry { Id = "kibbutz" };+ var unit = new HexPaletteEntry { Id = "palmach_squad", IsUnit = true };+ Assert.That(Path.GetFileName(HexPalette.ThumbPath(dir, tile)), Is.EqualTo("kibbutz.png"));+ Assert.That(Path.GetFileName(HexPalette.ThumbPath(dir, unit)), Is.EqualTo("unit-palmach_squad.png"));+ Assert.That(HexPalette.LoadThumb(dir, tile), Is.Null);+ var png = new Texture2D(4, 4); File.WriteAllBytes(HexPalette.ThumbPath(dir, unit), png.EncodeToPNG()); Object.DestroyImmediate(png);+ var loaded = HexPalette.LoadThumb(dir, unit);+ Assert.That(loaded!.width, Is.EqualTo(4));+ Object.DestroyImmediate(loaded);+ }++ [Test]+ public void AThumbnailBoardIsTheEntryRingedByPlainGround()+ {+ var board = HexPaletteThumbs.ThumbBoard(new HexPaletteEntry { Id = "judean_highlands" });+ Assert.That(board.Hexes.Count, Is.EqualTo(7));+ var c = board.Hexes[(0, 0)];+ Assert.That((c.prototype, c.terrain, c.unit), Is.EqualTo(("judean_highlands", "mountain", "")));+ Assert.That(board.Hexes.Values.Count(h => h.prototype == "" && h.unit == ""), Is.EqualTo(6));+ var u = HexPaletteThumbs.ThumbBoard(new HexPaletteEntry { Id = "palmach_squad", IsUnit = true }).Hexes[(0, 0)];+ Assert.That((u.prototype, u.unit), Is.EqualTo(("", "palmach_squad")));+ }++ [Test]+ public void TheCaptureReadsAnOperationList()+ {+ var ops = HexPainterCapture.ParseOps("prototype=kibbutz; unit=palmach_squad@120;time=dusk;attack");+ Assert.That(ops.Select(o => o.ToString()), Is.EqualTo(new[] { "prototype=kibbutz", "unit=palmach_squad@120", "time=dusk", "attack" }));+ Assert.That(ops.Select((o, i) => o.Folder(i + 1)), Is.EqualTo(new[] { "1-prototype-kibbutz", "2-unit-palmach_squad-120", "3-time-dusk", "4-attack" }));+ Assert.Throws<ArgumentException>(() => HexPainterCapture.ParseOps("time=noon"));+ Assert.Throws<ArgumentException>(() => HexPainterCapture.ParseOps("prototype=no_such_tile"));+ Assert.Throws<ArgumentException>(() => HexPainterCapture.ParseOps("terrain=water"));+ }+// --- The environment's region species ---static HexBoard EnvBoard(BoardRegion[] regions, string region, string terrain = "flat")diff --git a/unity/Assets/Editor/HexTiles/Tests/HexPrototypeTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexPrototypeTests.csindex 9e36b7949..74f6eb58f 100644--- a/unity/Assets/Editor/HexTiles/Tests/HexPrototypeTests.cs+++ b/unity/Assets/Editor/HexTiles/Tests/HexPrototypeTests.cs@@ -26,6 +26,14 @@ public class HexPrototypeTests[TestCaseSource(nameof(Ids))]public void IdIsLowerSnakeCase(string id) => Assert.That(Regex.IsMatch(id, "^[a-z][a-z0-9_]*$"), id);+ [TestCaseSource(nameof(Ids))]+ public void NamesAPaletteKindAndRegion(string id)+ {+ var info = HexPrototypes.Info(id);+ Assert.That(HexPrototypes.Kinds, Does.Contain(info.Kind), $"{id}: kind '{info.Kind}'");+ Assert.That(info.Region == "" || HexPrototypes.Regions.Contains(info.Region), $"{id}: region '{info.Region}'");+ }+[TestCaseSource(nameof(Ids))]public void BuildsSomething(string id) => Assert.That(Built(id).Placements.Count, Is.GreaterThan(0), id);diff --git a/unity/Assets/Editor/HexTiles/Tests/HexTimeOfDayTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexTimeOfDayTests.csnew file mode 100644index 000000000..65aec7fba--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexTimeOfDayTests.cs@@ -0,0 +1,278 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game.Map;+using Statecraft.HexTiles;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.Rendering;+using Object = UnityEngine.Object;++/// <summary>The hex-tile map's time of day (HexTimeOfDay): which preset the URL or the command line asks for, and that+/// each preset's undo puts back exactly what it changed (the grade, the sun, the ambient and the board's lit windows).</summary>+public class HexTimeOfDayTests+{+ VolumeProfile profile = null!;+ Light sun = null!;+ readonly List<Object> made = new List<Object>();++ [SetUp]+ public void Scene()+ {+ // RenderSettings belong to the active scene: a new one per test, lit the way the board is (map light, then HexLook).+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ sun = new GameObject("Sun").AddComponent<Light>(); sun.type = LightType.Directional;+ profile = ScriptableObject.CreateInstance<VolumeProfile>();+ made.Add(sun.gameObject); made.Add(profile);+ }++ [TearDown] public void Clean() { foreach (var o in made) if (o != null) Object.DestroyImmediate(o); made.Clear(); }++ static IEnumerable<HexTime> All() => (HexTime[])Enum.GetValues(typeof(HexTime));+ static IEnumerable<HexTime> Presets() => All().Where(t => t != HexTime.Day);++ // --- Which preset is asked for ---++ [TestCase("https://x/play?hex-tiles&hex-time=dusk", HexTime.Dusk)]+ [TestCase("https://x/play?hex-time=night&hex-tiles", HexTime.Night)]+ [TestCase("https://x/play?hex-tiles&hex-time=night#top", HexTime.Night)]+ [TestCase("https://x/play?hex-tiles&hex-time=day", HexTime.Day)]+ [TestCase("https://x/play?hex-tiles#hex-time=night", HexTime.Day)] // after '#': not a query parameter+ [TestCase("https://x/play#?hex-time=night", HexTime.Day)]+ [TestCase("https://x/play?hex-tiles&hex-time", HexTime.Day)] // the flag alone names no preset+ [TestCase("https://x/play?hex-tiles&hex-time=", HexTime.Day)]+ [TestCase("https://x/play?hex-tiles&hex-time=noon", HexTime.Day)] // a bad value+ [TestCase("https://x/play?hex-tiles&hex-time=Night", HexTime.Day)] // ids are lower case+ [TestCase("https://x/play?hex-tiles&hex-time=nightly", HexTime.Day)]+ [TestCase("https://x/play?hex-tiles&old-hex-time=night", HexTime.Day)] // another parameter's tail+ [TestCase("https://x/play?hex-tiles", HexTime.Day)]+ [TestCase("https://x/play", HexTime.Day)]+ [TestCase("", HexTime.Day)]+ [TestCase(null, HexTime.Day)]+ public void TheWebReadsATopLevelQueryParameter(string? url, HexTime expected) =>+ Assert.That(HexTimeOfDay.Requested(url, new[] { "-hex-time", "night" }, webgl: true), Is.EqualTo(expected));++ [TestCase(new[] { "unity", "-hex-tiles", "-hex-time", "dusk" }, HexTime.Dusk)]+ [TestCase(new[] { "unity", "-hex-time", "night", "-hex-tiles" }, HexTime.Night)]+ [TestCase(new[] { "unity", "-hex-time", "day" }, HexTime.Day)]+ [TestCase(new[] { "unity", "-hex-tiles", "-hex-time" }, HexTime.Day)] // the flag alone+ [TestCase(new[] { "unity", "-hex-time", "-hex-tiles" }, HexTime.Day)] // the next argument is another flag+ [TestCase(new[] { "unity", "-hex-time", "dawn" }, HexTime.Day)] // a bad value+ [TestCase(new[] { "unity", "-hex-time=night" }, HexTime.Day)]+ [TestCase(new[] { "unity", "-hex-tiles" }, HexTime.Day)]+ [TestCase(new string[0], HexTime.Day)]+ public void TheDesktopReadsTheArgumentAfterTheFlag(string[] args, HexTime expected) =>+ Assert.That(HexTimeOfDay.Requested("https://x/play?hex-time=night", args, webgl: false), Is.EqualTo(expected));++ [Test]+ public void IdsRoundTrip()+ {+ foreach (var t in All())+ {+ Assert.That(HexTimeOfDay.TryParse(HexTimeOfDay.Id(t), out var back), Is.True);+ Assert.That(back, Is.EqualTo(t));+ }+ Assert.That(HexTimeOfDay.TryParse("evening", out var none), Is.False);+ Assert.That(none, Is.EqualTo(HexTime.Day));+ }++ // --- What a preset changes, and its undo ---++ /// <summary>Everything a preset may touch: every volume component and parameter (value and override state), the+ /// sun's light and rotation, the scene's ambient, fog and skybox.</summary>+ string Snapshot(GameObject? root = null)+ {+ var lines = new List<string>();+ foreach (var c in profile.components)+ {+ lines.Add($"{c.GetType().Name} active={c.active}");+ var ps = c.parameters;+ for (int i = 0; i < ps.Count; i++)+ {+ var value = ps[i].GetType().GetProperty("value")?.GetValue(ps[i]);+ lines.Add($" {i}: {Show(value)} override={ps[i].overrideState}");+ }+ }+ var r = sun.transform.localRotation;+ lines.Add($"sun {sun.intensity:R} {Show(sun.color)} rot=({r.x:R},{r.y:R},{r.z:R},{r.w:R}) shadows={sun.shadows} strength={sun.shadowStrength:R} enabled={sun.enabled}");+ lines.Add($"ambient {RenderSettings.ambientMode} {Show(RenderSettings.ambientSkyColor)} {Show(RenderSettings.ambientEquatorColor)} {Show(RenderSettings.ambientGroundColor)} {Show(RenderSettings.ambientLight)} {RenderSettings.ambientIntensity:R}");+ lines.Add($"fog {RenderSettings.fog} {Show(RenderSettings.fogColor)} {RenderSettings.fogMode} {RenderSettings.fogDensity:R} {RenderSettings.fogStartDistance:R} {RenderSettings.fogEndDistance:R} sky={RenderSettings.skybox} rsun={RenderSettings.sun}");+ if (root != null) lines.AddRange(root.GetComponentsInChildren<Transform>(true).Select(t => "node " + t.name + " " + t.childCount));+ return string.Join("\n", lines);+ }++ static string Show(object? v) => v switch+ {+ null => "null",+ Color c => $"({c.r:R},{c.g:R},{c.b:R},{c.a:R})",+ float f => f.ToString("R"),+ _ => v.ToString(),+ };++ void LightTheBoard(bool grade)+ {+ MapLighting.Apply(sun);+ if (grade) MapGrade.Apply(profile);+ HexLook.Apply(profile, sun);+ }++ [TestCaseSource(nameof(All))]+ public void TheUndoRestoresEverythingOnAFreshProfileAndLight(HexTime time)+ {+ var before = Snapshot();+ var undo = HexTimeOfDay.Apply(time, profile, sun, null);+ undo();+ Assert.That(Snapshot(), Is.EqualTo(before), HexTimeOfDay.Id(time));+ Assert.That(profile.components, Is.Empty, "components the preset added are removed");+ }++ [TestCaseSource(nameof(All))]+ public void TheUndoRestoresEverythingOverTheBoardsLook(HexTime time)+ {+ LightTheBoard(grade: true);+ var before = Snapshot();+ HexTimeOfDay.Apply(time, profile, sun, null)();+ Assert.That(Snapshot(), Is.EqualTo(before), HexTimeOfDay.Id(time));+ }++ [Test]+ public void TheUndoKeepsHexLooksOwnComponents()+ {+ // HexLook adds a WhiteBalance to a profile without one; the time undo, which runs first, must leave it there.+ HexLook.Apply(profile, sun);+ var before = Snapshot();+ HexTimeOfDay.Apply(HexTime.Night, profile, sun, null)();+ Assert.That(Snapshot(), Is.EqualTo(before));+ }++ [TestCaseSource(nameof(Presets))]+ public void APresetChangesTheLook(HexTime time)+ {+ LightTheBoard(grade: true);+ var before = Snapshot();+ var undo = HexTimeOfDay.Apply(time, profile, sun, null);+ Assert.That(Snapshot(), Is.Not.EqualTo(before), HexTimeOfDay.Id(time));+ undo();+ }++ [Test]+ public void DayChangesNothing()+ {+ LightTheBoard(grade: true);+ var root = new GameObject("board"); made.Add(root);+ var before = Snapshot(root);+ var undo = HexTimeOfDay.Apply(HexTime.Day, profile, sun, root, CityBoard());+ Assert.That(Snapshot(root), Is.EqualTo(before));+ undo();+ Assert.That(Snapshot(root), Is.EqualTo(before));+ }++ [Test]+ public void ThePresetsAreDistinct()+ {+ var looks = new List<string>();+ LightTheBoard(grade: true);+ foreach (var t in All())+ {+ var undo = HexTimeOfDay.Apply(t, profile, sun, null);+ looks.Add(Snapshot());+ undo();+ }+ Assert.That(looks.Distinct().Count(), Is.EqualTo(looks.Count));+ }++ [Test]+ public void ThePresetsKeepTheirIdea()+ {+ // The presets keep their idea: night's light is dimmer than dusk's, and bluer than red; dusk's sun is low and warm.+ var dusk = HexTimeOfDay.PresetOf(HexTime.Dusk)!; var night = HexTimeOfDay.PresetOf(HexTime.Night)!;+ Assert.That(HexTimeOfDay.PresetOf(HexTime.Day), Is.Null);+ Assert.That(night.SunIntensity, Is.LessThan(dusk.SunIntensity));+ Assert.That(night.SunColour.b, Is.GreaterThan(night.SunColour.r));+ Assert.That(dusk.SunColour.r, Is.GreaterThan(dusk.SunColour.b));+ Assert.That(dusk.SunElevation, Is.LessThan(MapLighting.SunElevation));+ Assert.That(night.PostExposure, Is.LessThan(HexLook.PostExposure));+ Assert.That(dusk.AmbientSky.b, Is.GreaterThan(dusk.AmbientSky.r), "dusk's ambient is cooler than its sun");+ }++ [Test]+ public void NullsChangeNothingAndDoNotThrow()+ {+ foreach (var t in All())+ {+ var undo = HexTimeOfDay.Apply(t, null, null, null);+ undo();+ undo(); // a second run does no harm+ }+ }++ // --- The board's lit windows ---++ static HexBoard CityBoard(string prototype = "tel_aviv_city") => new HexBoard(new HexBoardFile+ {+ id = "t", hexes = new[] { new BoardHex { q = 0, r = 0, prototype = prototype }, new BoardHex { q = 1, r = 0, prototype = "wheat_fields" } },+ });++ [Test]+ public void NightLightsWindowsInACityAndTheUndoRemovesThem()+ {+ LightTheBoard(grade: false);+ var root = new GameObject("board"); made.Add(root);+ new GameObject("pieces").transform.SetParent(root.transform, false);+ var before = Snapshot(root);+ var undo = HexTimeOfDay.Apply(HexTime.Night, profile, sun, root, CityBoard());+ var windows = root.transform.Find(HexTimeOfDay.WindowsName);+ Assert.That(windows, Is.Not.Null);+ var mesh = windows.GetComponent<MeshFilter>().sharedMesh; var material = windows.GetComponent<MeshRenderer>().sharedMaterial;+ Assert.That(mesh.vertexCount, Is.GreaterThan(0));+ undo();+ Assert.That(Snapshot(root), Is.EqualTo(before));+ Assert.That(mesh == null && material == null, "the windows' mesh and material are destroyed with them");+ }++ [Test]+ public void TheWindowsAreTheSameEachTime()+ {+ var root = new GameObject("board"); made.Add(root);+ Vector3[] Windows()+ {+ var undo = HexTimeOfDay.Apply(HexTime.Night, profile, sun, root, CityBoard());+ var v = root.transform.Find(HexTimeOfDay.WindowsName).GetComponent<MeshFilter>().sharedMesh.vertices;+ undo();+ return v;+ }+ Assert.That(Windows(), Is.EqualTo(Windows()));+ }++ [TestCase(HexTime.Dusk, "tel_aviv_city")]+ [TestCase(HexTime.Night, "wheat_fields")]+ public void NoWindowsAtDuskOrOutsideTowns(HexTime time, string prototype)+ {+ var root = new GameObject("board"); made.Add(root);+ var undo = HexTimeOfDay.Apply(time, profile, sun, root, CityBoard(prototype));+ Assert.That(root.transform.Find(HexTimeOfDay.WindowsName), Is.Null);+ undo();+ }++ [Test]+ public void OnlyLightsTheOneTileACaptureBuilds()+ {+ var root = new GameObject("board"); made.Add(root);+ var undo = HexTimeOfDay.Apply(HexTime.Night, profile, sun, root, CityBoard(), only: "kibbutz");+ Assert.That(root.transform.Find(HexTimeOfDay.WindowsName), Is.Null);+ undo();+ }++ [Test]+ public void ABoardRootWithNoBoardGetsNoWindows()+ {+ var root = new GameObject("board"); made.Add(root);+ var before = Snapshot(root);+ var undo = HexTimeOfDay.Apply(HexTime.Night, profile, sun, root);+ Assert.That(root.transform.Find(HexTimeOfDay.WindowsName), Is.Null);+ undo();+ Assert.That(Snapshot(root), Is.EqualTo(before));+ }+}diff --git a/unity/Assets/Editor/HexTiles/Tests/HexTimeOfDayTests.cs.meta b/unity/Assets/Editor/HexTiles/Tests/HexTimeOfDayTests.cs.metanew file mode 100644index 000000000..e87af01bc--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexTimeOfDayTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: b682b4c72921d476a8fa2a3eacc09196\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.csnew file mode 100644index 000000000..10cb4c893--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs@@ -0,0 +1,149 @@+#nullable enable+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.HexTiles;+using UnityEngine;+using Object = UnityEngine.Object;++/// <summary>The "under attack" look (HexUnderAttack): presentation only, shown on one hex and hidden again. It sits on+/// the hex centre and stays inside the hex at every time, shows once however often it is shown, frees every mesh and+/// material it made when hidden, samples the same pulse and smoke for the same time, and ships its material templates.</summary>+public class HexUnderAttackTests+{+ const int Q = -3, R = 19;+ readonly List<GameObject> roots = new List<GameObject>();++ [TearDown] public void DestroyRoots() { foreach (var r in roots) if (r != null) Object.DestroyImmediate(r); roots.Clear(); }++ Transform Root() { var go = new GameObject("HexBoard"); roots.Add(go); return go.transform; }++ /// <summary>Raised ground, so the look must take its height from the surface.</summary>+ sealed class Raised : IHexSurface+ {+ public float Height(Vector3 p) => 80f + p.x * 0.004f;+ public float SlopeDeg(Vector3 p) => 0.2f;+ public bool IsWater(Vector3 p) => false;+ }++ static (MeshFilter[] meshes, Renderer[] renderers) Parts(GameObject go) =>+ (go.GetComponentsInChildren<MeshFilter>(true), go.GetComponentsInChildren<Renderer>(true));++ [Test]+ public void ShowSitsOnTheHexCentreAndStaysInsideIt()+ {+ var root = Root();+ var surface = new Raised();+ var go = HexUnderAttack.Show(root, surface, Q, R);+ var c = HexGeometry.Centre(Q, R, HexScale.HexM);+ Assert.That(go.transform.parent, Is.SameAs(root));+ Assert.That(Vector3.Distance(go.transform.localPosition, new Vector3(c.x, surface.Height(c), c.z)), Is.LessThan(0.01f));+ var look = go.GetComponent<HexUnderAttackLook>();+ Assert.That(look, Is.Not.Null, "the look animates through its component");+ foreach (var t in new[] { 0f, 0.7f, 2.9f, 5.3f, 11.1f, 47.5f })+ {+ look.Time(t);+ var (meshes, _) = Parts(go);+ Assert.That(meshes.Count(m => m.sharedMesh != null && m.sharedMesh.vertexCount > 0), Is.GreaterThanOrEqualTo(3), "smoke, glow and border");+ foreach (var mf in meshes)+ foreach (var v in mf.sharedMesh.vertices)+ {+ var p = root.InverseTransformPoint(mf.transform.TransformPoint(v));+ Assert.That(HexGeometry.InHex(p, c, HexScale.HexM), $"{mf.name} vertex {p} at t={t} is outside hex {Q},{R}");+ }+ }+ }++ [Test]+ public void ShowTwiceLeavesOne()+ {+ var root = Root();+ HexUnderAttack.Show(root, new FlatSurface(), Q, R);+ HexUnderAttack.Show(root, new FlatSurface(), Q, R);+ Assert.That(root.Cast<Transform>().Count(t => t.name == HexUnderAttack.Name(Q, R)), Is.EqualTo(1));+ }++ [Test]+ public void HideRemovesItAndReleasesWhatItMade()+ {+ var root = Root();+ var go = HexUnderAttack.Show(root, new FlatSurface(), Q, R);+ go.GetComponent<HexUnderAttackLook>().Time(1.5f);+ var (meshes, renderers) = Parts(go);+ var materials = renderers.SelectMany(r => r.sharedMaterials).ToList();+ var made = meshes.Select(m => (Object)m.sharedMesh).Concat(materials)+ .Concat(materials.Select(m => m.GetTexture("_BaseMap")).Where(t => t != null)).ToList();+ Assert.That(made.Count, Is.GreaterThanOrEqualTo(6), "three meshes and three materials at least");+ Assert.That(made.All(o => o != null));+ Assert.That(HexUnderAttack.Hide(root, Q, R), Is.True);+ Assert.That(made.Where(o => o != null).Select(o => o.name), Is.Empty, "every mesh and material the look made is destroyed");+ Assert.That(HexUnderAttack.Hide(root, Q, R), Is.False);+ }++ [Test]+ public void IsShownFollowsShowAndHide()+ {+ var root = Root();+ Assert.That(HexUnderAttack.IsShown(root, Q, R), Is.False);+ HexUnderAttack.Show(root, new FlatSurface(), Q, R);+ Assert.That(HexUnderAttack.IsShown(root, Q, R), Is.True);+ Assert.That(HexUnderAttack.IsShown(root, Q + 1, R), Is.False);+ HexUnderAttack.Hide(root, Q, R);+ Assert.That(HexUnderAttack.IsShown(root, Q, R), Is.False);+ }++ /// <summary>What a sampled look draws: the border colour and every mesh's vertices and colours.</summary>+ static List<object> Sample(GameObject go)+ {+ var (meshes, renderers) = Parts(go);+ var s = new List<object>();+ s.AddRange(renderers.SelectMany(r => r.sharedMaterials).Select(m => (object)m.GetColor("_BaseColor")));+ foreach (var mf in meshes.OrderBy(m => m.name)) { s.AddRange(mf.sharedMesh.vertices.Cast<object>()); s.AddRange(mf.sharedMesh.colors32.Cast<object>()); }+ return s;+ }++ [Test]+ public void ThePulseAndTheSmokeAreDeterministicForAGivenTime()+ {+ var a = HexUnderAttack.Show(Root(), new FlatSurface(), Q, R).GetComponent<HexUnderAttackLook>();+ var b = HexUnderAttack.Show(Root(), new FlatSurface(), Q, R).GetComponent<HexUnderAttackLook>();+ a.Time(3.25f); b.Time(0.4f); b.Time(3.25f);+ CollectionAssert.AreEqual(Sample(a.gameObject), Sample(b.gameObject));+ Assert.That(HexUnderAttack.Pulse(1.1f), Is.EqualTo(HexUnderAttack.Pulse(1.1f)));+ Assert.That(HexUnderAttack.Pulse(0f), Is.Not.EqualTo(HexUnderAttack.Pulse(HexUnderAttack.PulsePeriodS * 0.5f)).Within(0.2f), "it pulses");+ Assert.That(Enumerable.Range(0, 40).Select(i => HexUnderAttack.Pulse(i * 0.137f)).All(p => p >= 0f && p <= 1f));+ var before = Sample(a.gameObject);+ a.Time(4.1f);+ CollectionAssert.AreNotEqual(before, Sample(a.gameObject), "the smoke and the pulse move with time");+ }++ [Test]+ public void TheSmokeIsSeededByTheHex()+ {+ var a = HexUnderAttack.SmokeBases(Q, R, HexScale.HexM);+ CollectionAssert.AreEqual(a, HexUnderAttack.SmokeBases(Q, R, HexScale.HexM));+ CollectionAssert.AreNotEqual(a, HexUnderAttack.SmokeBases(Q + 1, R, HexScale.HexM));+ Assert.That(a.Length, Is.InRange(2, 4));+ // On every hex: outside the unit spot, and in the north half, so (seen from the south, as the board camera sees+ // it) no column stands in front of the unit or the city's centre.+ for (int q = -6; q <= 6; q++)+ for (int r = -6; r <= 24; r++)+ foreach (var p in HexUnderAttack.SmokeBases(q, r, HexScale.HexM))+ {+ Assert.That(new Vector2(p.x, p.z).magnitude, Is.GreaterThan(HexScale.UnitSpotShare * HexScale.HexM), $"hex {q},{r}: smoke base {p}");+ Assert.That(p.z, Is.GreaterThanOrEqualTo(0f), $"hex {q},{r}: smoke base {p} is in the south half");+ }+ }++ [Test]+ public void TheTemplatesShipInResources()+ {+ foreach (var name in HexUnderAttack.Materials)+ {+ var m = Resources.Load<Material>(HexMaterials.Folder + "/" + name);+ Assert.That(m, Is.Not.Null, $"Resources/{HexMaterials.Folder}/{name}.mat (Statecraft/Hex Tiles/Make Materials)");+ Assert.That(m.shader.isSupported, name);+ Assert.That(m.renderQueue, Is.GreaterThanOrEqualTo((int)UnityEngine.Rendering.RenderQueue.Transparent), $"{name} is transparent");+ }+ }+}diff --git a/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs.meta b/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs.metanew file mode 100644index 000000000..4f428595e--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 5cd3e376e82064cdeaa5a203aaace5bc\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Tests/HexUnitTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexUnitTests.csnew file mode 100644index 000000000..2a3342216--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexUnitTests.cs@@ -0,0 +1,193 @@+#nullable enable+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.HexTiles;+using Statecraft.HexTiles.Capture;+using UnityEditor;+using UnityEngine;++/// <summary>The character units and the figures the hex tiles draw (Tal, 19 October 2026): a character unit is one model+/// times <see cref="HexUnitScale.Characters"/>, never a mix; every figure a unit or a tile places, people, animals and vehicles, is whole (no view ray+/// through its clothes, boots or face: HexMeshCheck on the skinned mesh posed as drawn, its idle clip's first frame, as for the buildings); and a squad+/// stands posed (not in its T-pose) at <see cref="HexUnitScale.FigureHeight"/>. Writes the figure measurements (the+/// local proto prefab and the Collection's near and far prefabs of each) to+/// asset-staging/ui-local/hex-tiles/round2/units/figure-report.txt where that local folder exists.</summary>+public class HexUnitTests+{+ /// <summary>The share of view rays a figure may see through, as for the buildings.</summary>+ const float Tolerance = 0.005f;++ static IEnumerable<string> CharacterUnits() =>+ HexUnitTypes.All.Keys.Where(id => HexUnitTypes.Create(id).Create().Members.Any(m => m.StandIn == StandIn.Figure)).OrderBy(k => k, System.StringComparer.Ordinal);++ [TestCaseSource(nameof(CharacterUnits))]+ public void IsOneModelTimesTheCharacterCount(string id)+ {+ var unit = HexUnitTypes.Create(id).Create();+ Assert.That(unit.Members.Count, Is.EqualTo(HexUnitScale.Characters), id);+ Assert.That(unit.Members.Select(m => m.Model).Distinct().ToList(), Has.Count.EqualTo(1), $"{id}: one model per character unit");+ }++ /// <summary>Every figure the units and tiles draw: each unit member's model, each "proto:figure-*" a tile places+ /// (people, animals, the horse wagon), and every id in HexModels.FigureAliases.</summary>+ static IEnumerable<string> Figures()+ {+ var ids = new SortedSet<string>(System.StringComparer.Ordinal);+ foreach (var id in HexUnitTypes.All.Keys) foreach (var m in HexUnitTypes.Create(id).Create().Members) ids.Add(m.Model);+ foreach (var p in AllFigurePlacements()) ids.Add(p);+ foreach (var a in HexModels.FigureAliases) ids.Add(a.id);+ return ids;+ }++ static IEnumerable<string> AllFigurePlacements()+ {+ foreach (var proto in HexPrototypes.All.Keys)+ {+ var ctx = new HexTileContext(2, -1, new FlatSurface(), 1948);+ HexPrototypes.Create(proto).Build(ctx);+ foreach (var p in ctx.Placements) if (p.Model.StartsWith("proto:figure-", System.StringComparison.Ordinal)) yield return p.Model;+ }+ }++ [Test]+ public void FiguresAreWhole()+ {+ WriteReport();+ var holes = new List<string>(); int measured = 0;+ foreach (var id in Figures())+ {+ var prefab = HexModels.Prefab(id);+ if (prefab == null) continue; // its stand-in on this machine+ var m = HexMeshCheck.OfFigure(prefab); measured++;+ if (m.SeeThroughShare > Tolerance) holes.Add($"{id} ({prefab.name}): {m}");+ }+ Assert.That(measured, Is.GreaterThan(0), "no figure model resolved");+ Assert.That(holes, Is.Empty, "figures that show the ground through them:\n" + string.Join("\n", holes));+ }++ /// <summary>Each Collection figure drawn faces as its proto figure faced (the units and tiles turn figures by that+ /// frame): of the four quarter turns, the proto's vertices lie nearest the drawn figure's as they are, unless another+ /// turn is within a fifth of it. Ignored without the local proto figures.</summary>+ [Test]+ public void CollectionFiguresFaceAsTheirProtoFigures()+ {+ var wrong = new List<string>(); int compared = 0;+ foreach (var (id, _, _) in HexModels.FigureAliases)+ {+ var proto = Resources.Load<GameObject>(HexModels.PathOf(id));+ var drawn = HexModels.Prefab(id);+ if (proto == null || drawn == null || drawn == proto) continue;+ var turns = HexMeshCheck.FigureFacing(proto, drawn).Take(4).ToArray(); compared++;+ int best = System.Array.IndexOf(turns, turns.Min());+ if (best != 0 && turns[best] < 0.8f * turns[0]) wrong.Add($"{id} -> {drawn.name}: turn {HexMeshCheck.FacingNames[best]} {turns[best]:F4} vs as drawn {turns[0]:F4}");+ }+ if (compared == 0) Assert.Ignore("no local proto figures to compare");+ Assert.That(wrong, Is.Empty, string.Join("\n", wrong));+ }++ /// <summary>With the Collection figures off (as in a player, where the Collection streams from bundles) a figure id+ /// draws its local proto prefab again, or nothing (its stand-in).</summary>+ [Test]+ public void WithoutCollectionFiguresTheProtoFigureDraws()+ {+ try+ {+ HexModels.DrawCollectionFigures = false; HexModels.Clear();+ foreach (var (id, _, _) in HexModels.FigureAliases)+ Assert.That(HexModels.Prefab(id), Is.EqualTo(Resources.Load<GameObject>(HexModels.PathOf(id))), id);+ }+ finally { HexModels.DrawCollectionFigures = true; HexModels.Clear(); }+ foreach (var (id, figure, level) in HexModels.FigureAliases)+ Assert.That(HexModels.Prefab(id), Is.EqualTo(AssetDatabase.LoadAssetAtPath<GameObject>(HexModels.FigurePath(figure, level))), id);+ }++ /// <summary>Each squad member, posed standing (HexUnitMotion.Pose, the idle clip's first frame), measured from its+ /// skinned mesh baked in that pose: as tall as HexUnitScale.FigureHeight of the hex (within 15%), and not spread in a+ /// T-pose (its widest side under 0.6 of its height).</summary>+ [TestCaseSource(nameof(CharacterUnits))]+ public void StandsPosedAtFigureHeight(string id)+ {+ var parent = new GameObject("units");+ try+ {+ var motion = new HexUnitMotion(HexUnitTypes.Create(id).Create(), new[] { (0, 0) }, new FlatSurface(), parent.transform);+ motion.Pose(0f, false);+ float want = HexUnitScale.FigureHeight * HexScale.HexM;+ foreach (var go in motion.Objects)+ {+ var size = PosedSize(go);+ Assert.That(size.y, Is.InRange(0.85f * want, 1.15f * want), $"{id} {go.name}: {size.y:F0} m tall, want {want:F0}");+ Assert.That(Mathf.Max(size.x, size.z), Is.LessThan(0.6f * size.y), $"{id} {go.name}: {size.x:F0} x {size.z:F0} m wide for {size.y:F0} m tall (a T-pose?)");+ }+ }+ finally { Object.DestroyImmediate(parent); }+ }++ /// <summary>A placed figure's size in metres in its own frame (x across, z front to back), from its meshes as posed now.</summary>+ static Vector3 PosedSize(GameObject go)+ {+ var inv = Quaternion.Inverse(go.transform.rotation);+ var meshes = HexMeshCheck.WorldMeshes(go);+ try { return HexMeshCheck.SizeOf(meshes.SelectMany(m => m.vertices).Select(v => inv * v)); }+ finally { foreach (var m in meshes) Object.DestroyImmediate(m); }+ }++ static void WriteReport()+ {+ var lines = new List<string>+ {+ "Hex-tile figures, posed as drawn (idle clip, first frame; bind pose in the last two columns). HexMeshCheck: seeThru = view rays that meet the figure but none of",+ "its front faces; the test, within 0.5%. Local proto prefab vs the Collection's near and far prefabs. size = posed",+ "height and widest side in the prefab's units. facing: mean nearest distance of the proto's vertices to the near",+ "prefab's under quarter turns (0 least = same facing). Written by HexUnitTests.",+ "",+ $"{"figure".PadRight(58)} {"tris",6} {"seeThru",8} {"backFirst",9} {"height",7} {"width",7} {"bind seeThru",13} {"bind h",7}",+ };+ void Row(string name, GameObject? go)+ {+ if (go == null) { lines.Add($"{name.PadRight(58)} (missing)"); return; }+ var r = HexMeshCheck.OfFigure(go); var s = HexMeshCheck.FigureSize(go);+ var rb = HexMeshCheck.OfFigure(go, false); var sb = HexMeshCheck.FigureSize(go, false);+ lines.Add($"{name.PadRight(58)} {r.Triangles,6} {r.SeeThroughShare,8:P2} {r.BackFirstShare,9:P2} {s.y,7:F3} {Mathf.Max(s.x, s.z),7:F3} {rb.SeeThroughShare,13:P2} {sb.y,7:F3}");+ }+ foreach (var (id, figure, level) in HexModels.FigureAliases)+ {+ var proto = Resources.Load<GameObject>(HexModels.PathOf(id));+ var near = AssetDatabase.LoadAssetAtPath<GameObject>(HexModels.FigurePath(figure, "near"));+ var far = AssetDatabase.LoadAssetAtPath<GameObject>(HexModels.FigurePath(figure, "far"));+ Row(id + " (local proto)", proto);+ Row(figure + "-near", near);+ Row(figure + "-far", far);+ foreach (var (label, other) in new[] { ("near", near), ("far", far) })+ if (proto != null && other != null)+ {+ var f = HexMeshCheck.FigureFacing(proto, other);+ lines.Add($" facing proto vs {label}: " + string.Join(" ", f.Take(4).Select((v, i) => $"{HexMeshCheck.FacingNames[i]}={v:F4}")));+ }+ var drawn = HexModels.Prefab(id);+ lines.Add($" drawn now: {(drawn != null ? drawn.name : "stand-in")} (alias level {level})");+ foreach (var (label, go) in new[] { ("proto", proto), ("near", near) })+ {+ if (go == null) continue;+ var inst = Object.Instantiate(go);+ foreach (var s in inst.GetComponentsInChildren<SkinnedMeshRenderer>())+ {+ float hCpu = HexMeshCheck.SizeOf(HexMeshCheck.Skinned(s)).y, hBake = HexMeshCheck.SizeOf(HexMeshCheck.Skinned(s, true)).y;+ lines.Add($" {label} skin: {s.bones.Length} bones, {s.sharedMesh.boneWeights.Length}/{s.sharedMesh.vertexCount} weights, readable {s.sharedMesh.isReadable}, "+ + $"height cpu {hCpu:F3} bake {hBake:F3}, root rot {inst.transform.localRotation.eulerAngles}, clips {string.Join("/", inst.GetComponentsInChildren<Animator>().SelectMany(a => a.runtimeAnimatorController != null ? a.runtimeAnimatorController.animationClips.Select(c => c.name) : new string[0]))}");+ }+ Object.DestroyImmediate(inst);+ }+ }+ lines.Add("-- other figures the tiles place (reported only) --");+ var known = new HashSet<string>(HexModels.FigureAliases.Select(a => a.id));+ foreach (var id in AllFigurePlacements().Distinct().Where(i => !known.Contains(i)).OrderBy(i => i, System.StringComparer.Ordinal))+ Row(id, HexModels.Prefab(id));+ var staging = Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", "asset-staging"));+ var path = Path.Combine(staging, "ui-local/hex-tiles/round2/units/figure-report.txt");+ if (Directory.Exists(staging)) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllLines(path, lines); }+ Debug.Log("HEX FIGURE REPORT" + (Directory.Exists(staging) ? " -> " + path : "") + "\n" + string.Join("\n", lines));+ }+}diff --git a/unity/Assets/Editor/HexTiles/Tests/HexUnitTests.cs.meta b/unity/Assets/Editor/HexTiles/Tests/HexUnitTests.cs.metanew file mode 100644index 000000000..05086ce4b--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexUnitTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 5b684b6c1c27647cea97f1e7b3cc4ee0\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Tests/HexVariantTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexVariantTests.csnew file mode 100644index 000000000..32c77dc95--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexVariantTests.cs@@ -0,0 +1,103 @@+#nullable enable+using System.Collections.Generic;+using System.Globalization;+using System.Linq;+using System.Text;+using NUnit.Framework;+using Statecraft.HexTiles;+using UnityEngine;++/// <summary>The regional farm and forest variants (two per type and region, docs/hex-tiles/README.md): every type has+/// an a and a b for each region, tagged with its kind and region; a and b build differently from each other and from+/// their base; and the base tiles the existing boards use still build exactly what they built before the variants+/// subclassed them (a fingerprint of every placement and paint, recorded before the refactor).</summary>+public class HexVariantTests+{+ static readonly (string type, string kind)[] Types =+ {+ ("wheat_fields", "farm"), ("citrus_orchard", "farm"), ("olive_terraces", "farm"), ("mixed_farm", "farm"), ("forest", "forest"),+ };++ static IEnumerable<string> VariantIds() =>+ from t in Types from r in HexPrototypes.Regions from v in new[] { "a", "b" } select $"{t.type}_{r}_{v}";++ static HexTileContext Built(string id, int q = 2, int r = -1, int seed = 1948)+ {+ var ctx = new HexTileContext(q, r, new FlatSurface(), seed);+ HexPrototypes.Create(id).Build(ctx);+ return ctx;+ }++ static string F(float f) => f.ToString("R", CultureInfo.InvariantCulture);+ static string V(Vector3 v) => $"{F(v.x)},{F(v.y)},{F(v.z)}";++ /// <summary>Every placement and paint of a build, as text, hashed (FNV-1a 64) so the expected value is one line.</summary>+ static string Fingerprint(HexTileContext ctx)+ {+ var sb = new StringBuilder();+ foreach (var p in ctx.Placements)+ {+ sb.Append(p.Model).Append('|').Append(p.StandIn).Append('|').Append(p.Fit).Append('|').Append(F(p.Tint.r)).Append(',').Append(F(p.Tint.g)).Append(',').Append(F(p.Tint.b));+ for (int i = 0; i < 16; i++) sb.Append('|').Append(F(p.Matrix[i]));+ sb.Append('\n');+ }+ foreach (var p in ctx.Paints)+ sb.Append(p.Layer).Append('|').Append(V(p.A)).Append('|').Append(V(p.B)).Append('|').Append(F(p.Width)).Append('|').Append(F(p.Depth))+ .Append('|').Append(F(p.Yaw)).Append('|').Append(F(p.Soft)).Append('|').Append(F(p.Strength)).Append('|').Append(p.Line).Append('\n');+ ulong h = 14695981039346656037UL;+ foreach (char c in sb.ToString()) { h ^= c; h *= 1099511628211UL; }+ return $"{ctx.Placements.Count}/{ctx.Paints.Count}/{h:x16}";+ }++ static string Fingerprints(string id) =>+ string.Join(" ", new[] { Fingerprint(Built(id)), Fingerprint(Built(id, -3, 5, 7)), Fingerprint(Built(id, 11, -8, 31415)) });++ [TestCaseSource(nameof(VariantIds))]+ public void IsRegisteredWithItsKindAndRegion(string id)+ {+ Assert.That(HexPrototypes.All.ContainsKey(id), $"no prototype '{id}'");+ var info = HexPrototypes.Info(id);+ string kind = Types.First(t => id.StartsWith(t.type + "_")).kind, region = id.Split('_')[id.Split('_').Length - 2];+ Assert.That((info.Kind, info.Region), Is.EqualTo((kind, region)), id);+ }++ [TestCaseSource(nameof(VariantIds))]+ public void BuildsDifferentlyFromItsPairAndItsBase(string id)+ {+ string pair = id.EndsWith("_a") ? id.Substring(0, id.Length - 1) + "b" : id.Substring(0, id.Length - 1) + "a";+ string type = Types.First(t => id.StartsWith(t.type + "_")).type, baseId = type == "forest" ? "pine_forest" : type;+ Assert.That(Fingerprints(id), Is.Not.EqualTo(Fingerprints(pair)), $"{id} builds as {pair}");+ Assert.That(Fingerprints(id), Is.Not.EqualTo(Fingerprints(baseId)), $"{id} builds as {baseId}");+ }++ [Test]+ public void MixedFarmIsAFarmForAnyRegion()+ {+ Assert.That(HexPrototypes.All.ContainsKey("mixed_farm"), "no prototype 'mixed_farm'");+ var info = HexPrototypes.Info("mixed_farm");+ Assert.That((info.Kind, info.Region), Is.EqualTo(("farm", "")));+ }++ /// <summary>Recorded on 4841e34c, before the bases were opened for subclassing (FlatSurface, three hexes and seeds), then+ /// re-recorded on a clean checkout after main's #1160 sized a missing model's footprint by its stand-in: the same tiles+ /// on the same code, but without the git-ignored local models (Resources/HexSandbox, Resources/SettlementPrototypes)+ /// some trees no longer fit and the rest shift. With those models present #1160 changes nothing, so the test is ignored+ /// there rather than pinned twice.</summary>+ static readonly Dictionary<string, string> Before = new Dictionary<string, string>+ {+ ["wheat_fields"] = "6/23/8dc0de48cc6e25f0 11/21/0ec106c62c81994e 8/23/0b8b66bfd537c34d",+ ["grazing_land"] = "22/0/1389752806d94528 22/0/312ddbb3232f3c2b 22/0/fece2adb178546f6",+ ["citrus_orchard"] = "27/6/3fc025f769e42c67 27/6/1ec6cc42eb7d765f 27/6/c992d3cc18de5d6c",+ ["olive_terraces"] = "29/171/d46f8a175d59dccf 31/171/0f0b67936ea68a16 35/171/48024bc52f4d25e9",+ ["pine_forest"] = "53/18/3856750dc7f51f71 49/18/6b8d058df492107b 47/18/8811cda5be0a88f3",+ };++ [TestCase("wheat_fields"), TestCase("grazing_land"), TestCase("citrus_orchard"), TestCase("olive_terraces"), TestCase("pine_forest")]+ public void BaseTileBuildsAsBefore(string id)+ {+ if (Resources.LoadAll<GameObject>("HexSandbox").Length > 0 || Resources.LoadAll<GameObject>("SettlementPrototypes").Length > 0)+ Assert.Ignore("recorded without the local models; with them the stand-in footprints (#1160) do not apply");+ string now = Fingerprints(id);+ Assert.That(now, Is.EqualTo(Before[id]), $"{id} now builds {now}");+ }+}diff --git a/unity/Assets/Editor/HexTiles/Tests/HexVariantTests.cs.meta b/unity/Assets/Editor/HexTiles/Tests/HexVariantTests.cs.metanew file mode 100644index 000000000..fc95937e7--- /dev/null+++ b/unity/Assets/Editor/HexTiles/Tests/HexVariantTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: da721683e6df8483db118599c33b57c3\ No newline at end of filediff --git a/unity/Assets/Editor/HexTiles/Tests/Statecraft.HexTiles.Tests.asmdef b/unity/Assets/Editor/HexTiles/Tests/Statecraft.HexTiles.Tests.asmdefindex eb65ab490..975ecf545 100644--- a/unity/Assets/Editor/HexTiles/Tests/Statecraft.HexTiles.Tests.asmdef+++ b/unity/Assets/Editor/HexTiles/Tests/Statecraft.HexTiles.Tests.asmdef@@ -1,6 +1,6 @@{"name": "Statecraft.HexTiles.Tests",- "references": ["Statecraft.HexTiles.Editor", "Statecraft.Game", "UnityEngine.TestRunner", "UnityEditor.TestRunner"],+ "references": ["Statecraft.HexTiles.Editor", "Statecraft.Game", "Unity.RenderPipelines.Core.Runtime", "Unity.RenderPipelines.Universal.Runtime", "UnityEngine.TestRunner", "UnityEditor.TestRunner"],"includePlatforms": ["Editor"],"overrideReferences": true,"precompiledReferences": ["nunit.framework.dll"],diff --git a/unity/Assets/Resources/HexTiles/Materials/HexAttackBorder.mat b/unity/Assets/Resources/HexTiles/Materials/HexAttackBorder.matnew file mode 100644index 000000000..21f30b8e3--- /dev/null+++ b/unity/Assets/Resources/HexTiles/Materials/HexAttackBorder.mat@@ -0,0 +1,93 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!114 &-1831372688658766013+MonoBehaviour:+ m_ObjectHideFlags: 11+ 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: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}+ m_Name:+ m_EditorClassIdentifier: Unity.RenderPipelines.Universal.Editor::UnityEditor.Rendering.Universal.AssetVersion+ version: 10+--- !u!21 &2100000+Material:+ serializedVersion: 8+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_Name: HexAttackBorder+ m_Shader: {fileID: 4800000, guid: 0406db5a14f94604a8c57ccfbc9f3b46, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords:+ - _SURFACE_TYPE_TRANSPARENT+ m_InvalidKeywords:+ - _FLIPBOOKBLENDING_OFF+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 0+ m_DoubleSidedGI: 1+ m_CustomRenderQueue: 3000+ stringTagMap:+ RenderType: Transparent+ disabledShaderPasses:+ - DepthOnly+ - SHADOWCASTER+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs:+ - _BaseMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ - _BumpMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ - _EmissionMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ m_Ints: []+ m_Floats:+ - _AlphaClip: 0+ - _AlphaToMask: 0+ - _Blend: 0+ - _BlendOp: 0+ - _CameraFadingEnabled: 0+ - _CameraFarFadeDistance: 2+ - _CameraNearFadeDistance: 1+ - _ColorMode: 0+ - _Cull: 0+ - _Cutoff: 0.5+ - _DistortionBlend: 0.5+ - _DistortionEnabled: 0+ - _DistortionStrength: 1+ - _DistortionStrengthScaled: 0.1+ - _DstBlend: 10+ - _DstBlendAlpha: 10+ - _FlipbookBlending: 0+ - _FlipbookMode: 0+ - _Mode: 0+ - _QueueOffset: 0+ - _SoftParticlesEnabled: 0+ - _SoftParticlesFarFadeDistance: 1+ - _SoftParticlesNearFadeDistance: 0+ - _SrcBlend: 5+ - _SrcBlendAlpha: 1+ - _Surface: 1+ - _ZWrite: 0+ m_Colors:+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}+ - _BaseColorAddSubDiff: {r: 0, g: 0, b: 0, a: 0}+ - _CameraFadeParams: {r: 0, g: Infinity, b: 0, a: 0}+ - _Color: {r: 1, g: 1, b: 1, a: 1}+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}+ - _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0}+ m_BuildTextureStacks: []+ m_AllowLocking: 1diff --git a/unity/Assets/Resources/HexTiles/Materials/HexAttackBorder.mat.meta b/unity/Assets/Resources/HexTiles/Materials/HexAttackBorder.mat.metanew file mode 100644index 000000000..20cf16a76--- /dev/null+++ b/unity/Assets/Resources/HexTiles/Materials/HexAttackBorder.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: d7c4db528fbce4e9b90ffdd5ca02fb58+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Resources/HexTiles/Materials/HexAttackGlow.mat b/unity/Assets/Resources/HexTiles/Materials/HexAttackGlow.matnew file mode 100644index 000000000..c1d48fc01--- /dev/null+++ b/unity/Assets/Resources/HexTiles/Materials/HexAttackGlow.mat@@ -0,0 +1,93 @@+%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: HexAttackGlow+ m_Shader: {fileID: 4800000, guid: 0406db5a14f94604a8c57ccfbc9f3b46, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords:+ - _SURFACE_TYPE_TRANSPARENT+ m_InvalidKeywords:+ - _FLIPBOOKBLENDING_OFF+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 0+ m_DoubleSidedGI: 1+ m_CustomRenderQueue: 3000+ stringTagMap:+ RenderType: Transparent+ disabledShaderPasses:+ - DepthOnly+ - SHADOWCASTER+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs:+ - _BaseMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ - _BumpMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ - _EmissionMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ m_Ints: []+ m_Floats:+ - _AlphaClip: 0+ - _AlphaToMask: 0+ - _Blend: 2+ - _BlendOp: 0+ - _CameraFadingEnabled: 0+ - _CameraFarFadeDistance: 2+ - _CameraNearFadeDistance: 1+ - _ColorMode: 0+ - _Cull: 0+ - _Cutoff: 0.5+ - _DistortionBlend: 0.5+ - _DistortionEnabled: 0+ - _DistortionStrength: 1+ - _DistortionStrengthScaled: 0.1+ - _DstBlend: 1+ - _DstBlendAlpha: 1+ - _FlipbookBlending: 0+ - _FlipbookMode: 0+ - _Mode: 0+ - _QueueOffset: 0+ - _SoftParticlesEnabled: 0+ - _SoftParticlesFarFadeDistance: 1+ - _SoftParticlesNearFadeDistance: 0+ - _SrcBlend: 5+ - _SrcBlendAlpha: 1+ - _Surface: 1+ - _ZWrite: 0+ m_Colors:+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}+ - _BaseColorAddSubDiff: {r: 0, g: 0, b: 0, a: 0}+ - _CameraFadeParams: {r: 0, g: Infinity, b: 0, a: 0}+ - _Color: {r: 1, g: 1, b: 1, a: 1}+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}+ - _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0}+ m_BuildTextureStacks: []+ m_AllowLocking: 1+--- !u!114 &1937469085994230332+MonoBehaviour:+ m_ObjectHideFlags: 11+ 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: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}+ m_Name:+ m_EditorClassIdentifier: Unity.RenderPipelines.Universal.Editor::UnityEditor.Rendering.Universal.AssetVersion+ version: 10diff --git a/unity/Assets/Resources/HexTiles/Materials/HexAttackGlow.mat.meta b/unity/Assets/Resources/HexTiles/Materials/HexAttackGlow.mat.metanew file mode 100644index 000000000..0804bd12b--- /dev/null+++ b/unity/Assets/Resources/HexTiles/Materials/HexAttackGlow.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 293dcbaf87f2347dbad21ee9a01d0730+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Resources/HexTiles/Materials/HexAttackSmoke.mat b/unity/Assets/Resources/HexTiles/Materials/HexAttackSmoke.matnew file mode 100644index 000000000..42d2adc2a--- /dev/null+++ b/unity/Assets/Resources/HexTiles/Materials/HexAttackSmoke.mat@@ -0,0 +1,104 @@+%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: HexAttackSmoke+ m_Shader: {fileID: 4800000, guid: 8516d7a69675844a7a0b7095af7c46af, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords:+ - _SURFACE_TYPE_TRANSPARENT+ m_InvalidKeywords:+ - _FLIPBOOKBLENDING_OFF+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 0+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: 3000+ stringTagMap:+ RenderType: Transparent+ disabledShaderPasses:+ - DepthOnly+ - SHADOWCASTER+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs:+ - _BaseMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ - _BumpMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ - _EmissionMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ - _SpecGlossMap:+ m_Texture: {fileID: 0}+ m_Scale: {x: 1, y: 1}+ m_Offset: {x: 0, y: 0}+ m_Ints: []+ m_Floats:+ - _AlphaClip: 0+ - _AlphaToMask: 0+ - _Blend: 0+ - _BlendOp: 0+ - _BumpScale: 1+ - _CameraFadingEnabled: 0+ - _CameraFarFadeDistance: 2+ - _CameraNearFadeDistance: 1+ - _ColorMode: 0+ - _Cull: 2+ - _Cutoff: 0.5+ - _DistortionBlend: 0.5+ - _DistortionEnabled: 0+ - _DistortionStrength: 1+ - _DistortionStrengthScaled: 0.1+ - _DstBlend: 10+ - _DstBlendAlpha: 10+ - _FlipbookBlending: 0+ - _FlipbookMode: 0+ - _Glossiness: 0+ - _Mode: 0+ - _QueueOffset: 0+ - _ReceiveShadows: 1+ - _Smoothness: 0.5+ - _SmoothnessSource: 0+ - _SoftParticlesEnabled: 0+ - _SoftParticlesFarFadeDistance: 1+ - _SoftParticlesNearFadeDistance: 0+ - _SpecularHighlights: 1+ - _SrcBlend: 5+ - _SrcBlendAlpha: 1+ - _Surface: 1+ - _ZWrite: 0+ m_Colors:+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}+ - _BaseColorAddSubDiff: {r: 0, g: 0, b: 0, a: 0}+ - _CameraFadeParams: {r: 0, g: Infinity, b: 0, a: 0}+ - _Color: {r: 1, g: 1, b: 1, a: 1}+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}+ - _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0}+ - _SpecColor: {r: 1, g: 1, b: 1, a: 1}+ m_BuildTextureStacks: []+ m_AllowLocking: 1+--- !u!114 &6419078913306314730+MonoBehaviour:+ m_ObjectHideFlags: 11+ 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: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}+ m_Name:+ m_EditorClassIdentifier: Unity.RenderPipelines.Universal.Editor::UnityEditor.Rendering.Universal.AssetVersion+ version: 10diff --git a/unity/Assets/Resources/HexTiles/Materials/HexAttackSmoke.mat.meta b/unity/Assets/Resources/HexTiles/Materials/HexAttackSmoke.mat.metanew file mode 100644index 000000000..0b12b2a63--- /dev/null+++ b/unity/Assets/Resources/HexTiles/Materials/HexAttackSmoke.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 43370b17cd9b94d0c9dd0257942d2e3a+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexMaterials.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexMaterials.csindex c3f3c0e9c..ba1bd410d 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexMaterials.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexMaterials.cs@@ -12,11 +12,13 @@ namespace Statecraft.HexTiles{public const string Folder = "HexTiles/Materials";public const string Terrain = "HexTerrain", TerrainHoles = "HexTerrainHoles", Lit = "HexLit", Sea = "HexSea", Edges = "HexEdges";+ public const string AttackSmoke = "HexAttackSmoke", AttackGlow = "HexAttackGlow", AttackBorder = "HexAttackBorder";public static Material New(string name){var template = Resources.Load<Material>(Folder + "/" + name);if (template != null) return new Material(template) { name = name };+ if (name is AttackSmoke or AttackGlow or AttackBorder) return FromShader(name);var shader = Shader.Find(name switch{Terrain or TerrainHoles => "Universal Render Pipeline/Terrain/Lit",@@ -30,6 +32,31 @@ namespace Statecraft.HexTilesreturn m;}+ /// <summary>The under-attack look's materials (HexUnderAttack) built from their shaders, as Make Materials writes+ /// their templates: URP particle shaders, because they multiply the mesh's vertex colours (soft smoke puffs, a+ /// glow that fades to its rim). Smoke is lit and alpha-blended; the fire glow additive; the border alpha-blended.+ /// Both unlit ones draw both faces.</summary>+ public static Material FromShader(string name)+ {+ var shader = Shader.Find(name switch+ {+ AttackSmoke => "Universal Render Pipeline/Particles/Simple Lit",+ AttackGlow or AttackBorder => "Universal Render Pipeline/Particles/Unlit",+ _ => throw new ArgumentException($"no under-attack material '{name}'"),+ }) ?? throw new InvalidOperationException($"no material Resources/{Folder}/{name} and no shader for it");+ var m = new Material(shader) { name = name };+ MakeTransparent(m);+ if (name == AttackGlow)+ {+ m.SetFloat("_Blend", 2f); // additive+ m.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.SrcAlpha); m.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.One);+ m.SetFloat("_SrcBlendAlpha", (float)UnityEngine.Rendering.BlendMode.One); m.SetFloat("_DstBlendAlpha", (float)UnityEngine.Rendering.BlendMode.One);+ }+ if (name is AttackGlow or AttackBorder) m.SetFloat("_Cull", (float)UnityEngine.Rendering.CullMode.Off);+ m.SetColor("_BaseColor", Color.white);+ return m;+ }+/// <summary>URP Lit/Unlit set to alpha-blended transparency (the settings the shipped templates carry).</summary>public static void MakeTransparent(Material m){diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.csindex 859ad70c4..1e496fb95 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.cs@@ -2,6 +2,7 @@using System;using System.Collections.Generic;using System.Linq;+using Statecraft.Game.Map.Kits;using UnityEngine;using Object = UnityEngine.Object;@@ -11,6 +12,8 @@ namespace Statecraft.HexTiles/// "tiles:<path>" Resources/HexTiles/<path> (a contributor's own models, one folder per prototype)/// "sandbox:<name>" Resources/HexSandbox/<name> (EZ-Tree trees, Poly Haven rocks, decimated Tripo building kit)/// "proto:<name>" Resources/SettlementPrototypes/<name> (Tripo heroes, figures, animals, vehicles)+ /// "town:<folder>[@mid]" a shipped b*-v2 building (TownModels.Ids; TownModelSet's full mesh, or its baked mid+ /// level), which the sandbox building ids draw instead while the set is found (TownAliases)/// A trailing "*" picks among <name>, <name>_2, <name>_3 ... per placement. A missing model draws its stand-in, so a/// tile works on a machine without the local (git-ignored, pending-rights) models.</summary>public static class HexModels@@ -21,8 +24,120 @@ namespace Statecraft.HexTilespublic Part(Mesh mesh, int subMesh, Material material, Matrix4x4 local) { Mesh = mesh; SubMesh = subMesh; Material = material; Local = local; }}+ public const string TownPrefix = "town:", MidSuffix = "@mid";+ /// <summary>Stands a Z-up town mesh up (mesh z to y, mesh y to -z), as SettlementKits.Fit does.</summary>+ public static readonly Matrix4x4 TownTurn = Matrix4x4.Rotate(Quaternion.Euler(-90f, 0f, 0f));++ const string B01 = TownPrefix + "b01-white-city-v2", B02a = TownPrefix + "b02a-tel-aviv-corner-block-v2",+ B02b = TownPrefix + "b02b-tel-aviv-narrow-block-v2", B03a = TownPrefix + "b03a-jerusalem-arches-v2",+ B03b = TownPrefix + "b03b-jerusalem-external-stair-v2", B03c = TownPrefix + "b03c-jerusalem-plain-v2",+ B04b = TownPrefix + "b04b-haifa-loading-doors-v2",+ B05a = TownPrefix + "b05a-moshava-house-v2", B07 = TownPrefix + "b07-kibbutz-dining-hall-v2",+ B09a = TownPrefix + "b09a-kibbutz-communal-building-v2", B13a = TownPrefix + "b13a-netanya-two-storey-v2",+ B16 = TownPrefix + "b16-farmhouse-v2", B17 = TownPrefix + "b17-stone-courtyard-house-v2",+ B24 = TownPrefix + "b24-agricultural-barn-v2", B28 = TownPrefix + "b28-water-tower-v2", B32 = TownPrefix + "b32-port-cargo-shed-v2";++ /// <summary>The sandbox building ids drawn as the shipped b*-v2 town models when the set is found (Tal, 19 October+ /// 2026: the decimated sandbox kit had lost faces, so the ground showed through walls and windows). Each names its+ /// "town:" id and whether it is the same Tripo model; false is a remap, because its own model (b11, b21) is not in+ /// the set and is not pulled into a build. All take the full mesh (Tal, 19 October 2026): most baked mid levels have lost faces too,+ /// and the generator's in-between levels smear their textures (HexModelMeshTests' report), so the city and village+ /// tiles' budgets were raised to the full meshes (about 6,000 triangles each). A lighter level that keeps its UV+ /// seams is a follow-up.</summary>+ public static readonly (string id, string town, bool same)[] TownAliases =+ {+ ("sandbox:hq_white_city_hero", B01, true),+ ("sandbox:hq_white_city", B02a, true),+ ("sandbox:hq_white_city_2", B02b, true),+ ("sandbox:hq_white_city_3", B13a, true),+ ("sandbox:kit_white_city", B02a, true),+ ("sandbox:kit_white_city_2", B02b, true),+ ("sandbox:kit_white_city_3", B13a, true),+ ("sandbox:kit_white_city_4", B13a, false), // b11 shikun block+ ("sandbox:kit_jaffa", B17, true),+ ("sandbox:kit_jaffa_2", B03a, false), // b21 artisan workshop+ ("sandbox:kit_jaffa_3", B03c, true),+ ("sandbox:kit_haifa", B17, false), // b04a: its full mesh has open wall triangles (1.33% see-through)+ ("sandbox:kit_haifa_2", B04b, true),+ ("sandbox:kit_haifa_3", B05a, true),+ ("sandbox:kit_jerusalem", B03a, true),+ ("sandbox:kit_jerusalem_2", B03b, true),+ ("sandbox:kit_jerusalem_3", B03c, true),+ ("sandbox:kit_jerusalem_4", B17, true),+ ("sandbox:kit_negev", B17, true),+ ("sandbox:kit_negev_2", B03c, true),+ ("sandbox:kit_negev_3", B03a, false), // b21 artisan workshop+ ("sandbox:kit_moshava", B05a, true),+ ("sandbox:kit_moshava_2", B16, true),+ ("sandbox:kit_moshava_3", B24, true),+ ("sandbox:kit_kibbutz", B09a, true),+ ("sandbox:kit_kibbutz_2", B07, true),+ ("sandbox:kit_kibbutz_3", B24, true),+ ("sandbox:kit_kibbutz_4", B28, true),+ ("sandbox:kit_stone_village", B17, true),+ ("sandbox:kit_stone_village_2", B03c, true),+ ("sandbox:kit_port", B32, true),+ };++ /// <summary>Off draws the sandbox prefabs again (a before shot, or a test of the fallback); call+ /// <see cref="Clear"/> after switching.</summary>+ public static bool DrawTownModels = true;++ /// <summary>The cleared, tracked figure library (the game's Collection), one folder per figure with its -near (rigged,+ /// idle clip) and -far (static) prefabs.</summary>+ public const string CollectionFolder = "Assets/Art/Collection";++ /// <summary>The local proto figures the hex tiles and units place, drawn in the editor as their figure in the+ /// Collection (<see cref="CollectionFolder"/>) at the level given (Tal, 19 October 2026: the proto figures are our+ /// own decimations and show the ground through clothes, boots and faces, 2.7-6.5% of view rays; the Collection's+ /// are whole, HexUnitTests' report). The soldiers take the rigged near prefab (about 7,200 triangles, idle clip);+ /// the Tel Aviv townspeople the static far one (about 1,350, so the tile keeps its budget), but c01, whose far mesh+ /// is holed (1.8%), the near one. A player keeps the proto prefab, then the stand-in: the Collection streams from+ /// AssetBundles there, not Resources.</summary>+ public static readonly (string id, string figure, string level)[] FigureAliases =+ {+ ("proto:figure-palmach-scout-c12f-1948-v2", "figure-c12f-palmach-scout-v2", "near"),+ ("proto:figure-veteran-fighter-c07-1948-v2", "figure-c07-veteran-fighter-v2", "near"),+ ("proto:figure-young-recruit-c06-1948-v2", "figure-c06-young-recruit-v2", "near"),+ ("proto:figure-townsman-c02-1948-v2", "figure-c02-townsman-v2", "far"),+ ("proto:figure-woman-blue-dress-c10-1948-v2", "figure-c10-woman-blue-dress-v2", "far"),+ ("proto:figure-nurse-c13-1948-v2", "figure-c13-nurse-v2", "far"),+ ("proto:figure-arriving-man-c01-1948-v2", "figure-c01-arriving-man-v2", "near"),+ ("proto:figure-sabra-pioneer-c04-1948-v2", "figure-c04-sabra-pioneer-v3", "far"),+ // The grazing flock (Tal, 19 October 2026: the lite protos see through on 8.4% and 6.3% of rays): the static far+ // level, whole and lighter than the protos (about 1,350 triangles each). The horse wagon and the vehicle units'+ // protos measure whole and keep drawing.+ ("proto:figure-sheep-lite-1948", "figure-sheep-idle-1948-v1", "far"),+ ("proto:figure-donkey-lite-1948", "figure-donkey-1948-v1", "far"),+ };++ /// <summary>Off draws the proto figures again (a before shot, or a test of the fallback); call <see cref="Clear"/>+ /// after switching.</summary>+ public static bool DrawCollectionFigures = true;++ static readonly Dictionary<string, (string figure, string level)> figureOf =+ FigureAliases.ToDictionary(a => a.id, a => (a.figure, a.level), StringComparer.Ordinal);++ /// <summary>The Collection prefab a figure id draws in the editor (AssetDatabase), or null: in a player, without+ /// the Collection folder, or switched off.</summary>+ static GameObject? CollectionFigure(string id)+ {+#if UNITY_EDITOR+ if (DrawCollectionFigures && figureOf.TryGetValue(id, out var f))+ return UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(FigurePath(f.figure, f.level));+#endif+ return null;+ }++ /// <summary>A Collection figure's prefab path at a level ("near" or "far").</summary>+ public static string FigurePath(string figure, string level) => $"{CollectionFolder}/{figure}/{figure}-{level}.prefab";+static readonly Dictionary<string, GameObject?> prefabs = new Dictionary<string, GameObject?>(StringComparer.Ordinal);static readonly Dictionary<string, string[]> variants = new Dictionary<string, string[]>(StringComparer.Ordinal);+ static readonly Dictionary<string, string> townOf = TownAliases.ToDictionary(a => a.id, a => a.town, StringComparer.Ordinal);+ static readonly Dictionary<string, GameObject> templates = new Dictionary<string, GameObject>(StringComparer.Ordinal);+ static TownModelSet? townSet;+ static Transform? templateRoot;public static string PathOf(string id) =>id.StartsWith("tiles:", StringComparison.Ordinal) ? "HexTiles/" + id.Substring(6)@@ -30,11 +145,68 @@ namespace Statecraft.HexTiles: id.StartsWith("proto:", StringComparison.Ordinal) ? "SettlementPrototypes/" + id.Substring(6): "HexTiles/" + id;+ /// <summary>What <paramref name="id"/> draws: a town model's template (a "town:" id, or a sandbox id in+ /// <see cref="TownAliases"/>, while the set is found), else its Resources prefab, else null (its stand-in).</summary>public static GameObject? Prefab(string id){if (string.IsNullOrEmpty(id)) return null;- if (prefabs.TryGetValue(id, out var p)) return p;- return prefabs[id] = Resources.Load<GameObject>(PathOf(id));+ // A cached template is made again if it was destroyed (Unity's fake null); a cached miss stays a miss.+ if (prefabs.TryGetValue(id, out var p) && (ReferenceEquals(p, null) || p != null)) return p;+ bool town = id.StartsWith(TownPrefix, StringComparison.Ordinal), alias = townOf.ContainsKey(id);+ var made = town || alias ? Town(town ? id : townOf[id]) : null;+ if (made != null) return prefabs[id] = made;+ var figure = CollectionFigure(id);+ if (figure != null) return prefabs[id] = figure;+ var prefab = town ? null : Resources.Load<GameObject>(PathOf(id));+ // Without the set (a player before the map scene has loaded it), not remembered, so the set is looked for again.+ if (!(DrawTownModels && (town || alias))) prefabs[id] = prefab;+ return prefab;+ }++ /// <summary>Forgets every model looked up, the town set and the "*" variants.</summary>+ public static void Clear() { prefabs.Clear(); variants.Clear(); townSet = null; }++ /// <summary>The town models' list (TownModelSet, complete): in the editor the asset itself, in a player the one+ /// the map scene loaded (MapScene references it; no Resources folder, so it adds nothing to a build). Null until+ /// found; a miss is not remembered.</summary>+ public static TownModelSet? TownSet()+ {+ if (townSet != null) return townSet;+#if UNITY_EDITOR+ townSet = UnityEditor.AssetDatabase.LoadAssetAtPath<TownModelSet>(TownModels.SetPath);+#endif+ if (townSet == null) townSet = Resources.FindObjectsOfTypeAll<TownModelSet>().FirstOrDefault();+ if (townSet != null && townSet.Missing() != null) townSet = null;+ return townSet;+ }++ /// <summary>The template a "town:" id draws: an object under a hidden, inactive root holding the set's mesh (full,+ /// or the baked mid level for "@mid") and material, stood up from Z-up. The template's own object is active, so a+ /// copy of it (Parts) has renderer bounds; the inactive root keeps the template itself from drawing. Parts puts it+ /// in the unit frame (footprint centred, base at y = 0).</summary>+ static GameObject? Town(string town)+ {+ if (!DrawTownModels) return null;+ if (templates.TryGetValue(town, out var made) && made != null) return made;+ var set = TownSet();+ if (set == null) return null;+ bool mid = town.EndsWith(MidSuffix, StringComparison.Ordinal);+ int i = Array.IndexOf(TownModels.Ids, town.Substring(TownPrefix.Length, town.Length - TownPrefix.Length - (mid ? MidSuffix.Length : 0)));+ if (i < 0) return null;+ if (templateRoot == null)+ {+ var root = new GameObject("HexModels town templates") { hideFlags = HideFlags.HideAndDontSave };+ root.SetActive(false);+ templateRoot = root.transform;+ }+ var go = new GameObject(town.Substring(TownPrefix.Length)) { hideFlags = HideFlags.HideAndDontSave };+ go.transform.SetParent(templateRoot, false);+ var child = new GameObject("mesh", typeof(MeshFilter), typeof(MeshRenderer)) { hideFlags = HideFlags.HideAndDontSave };+ child.transform.SetParent(go.transform, false);+ child.transform.localRotation = TownTurn.rotation;+ child.GetComponent<MeshFilter>().sharedMesh = mid ? set.mid[i] : set.meshes[i];+ child.GetComponent<MeshRenderer>().sharedMaterial = set.materials[i];+ return templates[town] = go;}/// <summary>The concrete id for a placement: a "*" id picks a present variant by the placement's position.</summary>@@ -87,10 +259,38 @@ namespace Statecraft.HexTiles{var rs = go.GetComponentsInChildren<Renderer>();if (rs.Length == 0) return new Bounds(Vector3.zero, Vector3.one);- var b = rs[0].bounds; foreach (var r in rs) b.Encapsulate(r.bounds);+ var b = RendererBounds(rs[0]); foreach (var r in rs) b.Encapsulate(RendererBounds(r));return b;}+ /// <summary>A renderer's world bounds. In the editor a skinned renderer without exposed bones (the Collection's near+ /// figures: their rig hides its transforms) reports nearly empty bounds until it has drawn, which scaled a squad to+ /// hundreds of kilometres: measure its baked vertices instead (BakeMesh already applies the scale, so only the+ /// renderer's position and rotation place them).</summary>+ static Bounds RendererBounds(Renderer r)+ {+#if UNITY_EDITOR+ if (r is SkinnedMeshRenderer s && s.sharedMesh != null && s.bones.Length == 0)+ {+ var baked = new Mesh();+ try+ {+ s.BakeMesh(baked, false);+ var v = baked.vertices;+ if (v.Length > 0)+ {+ var m = Matrix4x4.TRS(s.transform.position, s.transform.rotation, Vector3.one);+ var b = new Bounds(m.MultiplyPoint3x4(v[0]), Vector3.zero);+ foreach (var p in v) b.Encapsulate(m.MultiplyPoint3x4(p));+ return b;+ }+ }+ finally { Object.DestroyImmediate(baked); }+ }+#endif+ return r.bounds;+ }+/// <summary>Triangles one placement of <paramref name="id"/> draws (its stand-in's when the model is missing).</summary>public static int Triangles(string id, StandIn standIn, Vector3 at){diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexTileContract.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexTileContract.csindex 1c49e52e9..1199671d6 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexTileContract.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexTileContract.cs@@ -15,6 +15,11 @@ namespace Statecraft.HexTilespublic sealed class HexPrototypeAttribute : Attribute{public string Id { get; }+ /// <summary>What the tile is, for the Hex Painter's palette: one of <see cref="HexPrototypes.Kinds"/>.</summary>+ public string Kind { get; set; } = "";+ /// <summary>The landscape it is drawn for (north, centre, south), or "" for anywhere. A regional variant is one file+ /// named by its region; the recipes in tools/hex_tiles/regions.yaml pick between the variants per hex.</summary>+ public string Region { get; set; } = "";public HexPrototypeAttribute(string id) => Id = id;}@@ -69,6 +74,14 @@ namespace Statecraft.HexTiles.Where(p => p.attr != null).ToDictionary(p => p.attr!.Id, p => p.t!, StringComparer.Ordinal);+ /// <summary>The palette groups, in the order the painter shows them; a prototype without a Kind is "other".</summary>+ public static readonly string[] Kinds = { "city", "town", "village", "farm", "forest", "nature", "other" };+ /// <summary>The regions a variant may name, north to south.</summary>+ public static readonly string[] Regions = { "north", "centre", "south" };++ public static HexPrototypeAttribute Info(string id) =>+ (HexPrototypeAttribute)Attribute.GetCustomAttribute(All[id], typeof(HexPrototypeAttribute))!;+public static IHexPrototype Create(string id) =>All.TryGetValue(id, out var t) ? (IHexPrototype)Activator.CreateInstance(t)! : throw new KeyNotFoundException($"no hex prototype '{id}' (known: {string.Join(", ", All.Keys)})");}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexTimeOfDay.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexTimeOfDay.csnew file mode 100644index 000000000..0f1b736b2--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexTimeOfDay.cs@@ -0,0 +1,281 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using System.Text.RegularExpressions;+using UnityEngine;+using UnityEngine.Rendering;+using UnityEngine.Rendering.Universal;+using Object = UnityEngine.Object;++namespace Statecraft.HexTiles+{+ /// <summary>The hex-tile map's time of day. Day is today's warm look (HexLook); dusk and night are presets laid over it.</summary>+ public enum HexTime { Day, Dusk, Night }++ /// <summary>Time-of-day presets for the opt-in hex-tile map, next to HexLook: presentation only, no simulation state is+ /// read or written. Web ?hex-time=dusk|night (a top-level query parameter, with ?hex-tiles), desktop -hex-time dusk|night;+ /// the Hex Painter has a switch. Dusk is a low, warm-orange sun with long shadows under a cooler sky; night is a dim,+ /// blue-white moon, a dark-blue sky and a lower exposure, still bright enough to read the tiles and units, with lit+ /// windows in city and town tiles. Apply returns the undo, which restores everything it changed.</summary>+ public static class HexTimeOfDay+ {+ public static readonly string[] Ids = { "day", "dusk", "night" };+ /// <summary>The child of the board root that holds the night's lit windows (one mesh, one unlit material).</summary>+ public const string WindowsName = "HexNightWindows";+ static readonly Regex Flag = new Regex(@"(?:^|&)hex-time=(?<time>[a-z]+)(?=&|$)", RegexOptions.CultureInvariant);++ public static string Id(HexTime time) => Ids[(int)time];++ /// <summary>A preset by its id (day, dusk, night).</summary>+ public static bool TryParse(string? id, out HexTime time)+ {+ int i = Array.IndexOf(Ids, id ?? "");+ time = i < 0 ? HexTime.Day : (HexTime)i;+ return i >= 0;+ }++ public static HexTime Requested() =>+ Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);++ /// <summary>The preset asked for, day when the flag is absent or names no preset. Web: only a top-level query+ /// parameter counts (HexTilesLook's rule: a value after '#' does not). Desktop: the argument after -hex-time.</summary>+ public static HexTime Requested(string? url, string[] args, bool webgl)+ {+ if (!webgl)+ {+ int i = Array.IndexOf(args, "-hex-time");+ return i >= 0 && i + 1 < args.Length && TryParse(args[i + 1], out var t) ? t : HexTime.Day;+ }+ var address = (url ?? "").Split('#')[0];+ var start = address.IndexOf('?');+ if (start < 0) return HexTime.Day;+ var m = Flag.Match(address.Substring(start + 1));+ return m.Success && TryParse(m.Groups["time"].Value, out var time) ? time : HexTime.Day;+ }++ /// <summary>One preset's light and grade. The sun is set outright (MapLighting's convention: elevation above the+ /// horizon, azimuth clockwise from north); the grade replaces HexLook's exposure, saturation and white balance.</summary>+ public sealed class Preset+ {+ public float SunElevation, SunAzimuth, SunIntensity, ShadowStrength;+ public Color SunColour, AmbientSky, AmbientEquator, AmbientGround;+ public float PostExposure, Saturation, Temperature, Tint;+ /// <summary>Lit windows in city and town tiles.</summary>+ public bool Windows;+ }++ /// <summary>Dusk: the sun low in the west-north-west (where the map's sun already stands, so the shadows only+ /// lengthen), deep orange, under a cooler, dimmer sky. The grade stays warm but a little darker.</summary>+ public static readonly Preset Dusk = new Preset+ {+ SunElevation = 14f, SunAzimuth = 290f, SunIntensity = 2.0f, ShadowStrength = 0.75f,+ SunColour = new Color(1.00f, 0.70f, 0.47f),+ AmbientSky = new Color(0.48f, 0.52f, 0.72f), AmbientEquator = new Color(0.52f, 0.47f, 0.50f), AmbientGround = new Color(0.24f, 0.21f, 0.20f),+ PostExposure = 0.30f, Saturation = 22f, Temperature = 6f, Tint = 3f,+ };++ /// <summary>Night: a blue-white moon high in the south-west, dim, with soft shadows; a dark-blue sky fill strong+ /// enough that the shadow side still reads; a lower exposure and a cool white balance. Not a horror game: the+ /// board is a strategy board at night, so the tiles keep their colours, only darker and bluer.</summary>+ public static readonly Preset Night = new Preset+ {+ SunElevation = 48f, SunAzimuth = 215f, SunIntensity = 0.85f, ShadowStrength = 0.55f,+ SunColour = new Color(0.70f, 0.80f, 1.00f),+ AmbientSky = new Color(0.22f, 0.27f, 0.42f), AmbientEquator = new Color(0.17f, 0.20f, 0.28f), AmbientGround = new Color(0.08f, 0.09f, 0.12f),+ PostExposure = 0.10f, Saturation = -4f, Temperature = -10f, Tint = 0f,+ Windows = true,+ };++ /// <summary>The preset for <paramref name="time"/>; null for day, which is HexLook as it is.</summary>+ public static Preset? PresetOf(HexTime time) => time switch { HexTime.Dusk => Dusk, HexTime.Night => Night, _ => null };++ /// <summary>Lays <paramref name="time"/> over the day look already applied (HexLook.Apply): the grade in+ /// <paramref name="profile"/>, the <paramref name="sun"/>, the ambient light and, for night, the board under+ /// <paramref name="boardRoot"/> (null: none). Day changes nothing. Returns the undo. The lit windows need the board:+ /// a board built for the Hex Painter carries it (HexBoardState); otherwise pass it to the overload.</summary>+ public static Action Apply(HexTime time, VolumeProfile? profile, Light? sun, GameObject? boardRoot)+ {+ // Not "?.": in the editor a missing component is a fake null that "?." does not see.+ var state = boardRoot != null ? boardRoot.GetComponent<HexBoardState>() : null;+ return Apply(time, profile, sun, boardRoot, state != null ? state.Board : null);+ }++ /// <summary>Apply, with the <paramref name="board"/> built under <paramref name="boardRoot"/> (board space is the+ /// root's local space), for the night's lit windows; <paramref name="only"/> lights just that prototype's tiles+ /// (a capture that built one tile). The undo restores each value and override state it changed, removes the+ /// volume components it added (never HexLook's) and destroys the windows, their mesh and their material.</summary>+ public static Action Apply(HexTime time, VolumeProfile? profile, Light? sun, GameObject? boardRoot, HexBoard? board, string? only = null)+ {+ var preset = PresetOf(time);+ if (preset == null) return () => { };+ var undo = new List<Action>();+ if (profile != null)+ {+ bool addedCa = !profile.TryGet(out ColorAdjustments ca);+ if (addedCa) ca = profile.Add<ColorAdjustments>();+ var c0 = (ca.postExposure.value, ca.postExposure.overrideState, ca.saturation.value, ca.saturation.overrideState);+ ca.postExposure.Override(preset.PostExposure); ca.saturation.Override(preset.Saturation);+ undo.Add(() =>+ {+ if (addedCa) { profile.Remove<ColorAdjustments>(); return; }+ ca.postExposure.value = c0.Item1; ca.postExposure.overrideState = c0.Item2; ca.saturation.value = c0.Item3; ca.saturation.overrideState = c0.Item4;+ });+ bool addedWb = !profile.TryGet(out WhiteBalance wb);+ if (addedWb) wb = profile.Add<WhiteBalance>();+ var w0 = (wb.temperature.value, wb.temperature.overrideState, wb.tint.value, wb.tint.overrideState);+ wb.temperature.Override(preset.Temperature); wb.tint.Override(preset.Tint);+ undo.Add(() =>+ {+ if (addedWb) { profile.Remove<WhiteBalance>(); return; }+ wb.temperature.value = w0.Item1; wb.temperature.overrideState = w0.Item2; wb.tint.value = w0.Item3; wb.tint.overrideState = w0.Item4;+ });+ }+ if (sun != null)+ {+ var s0 = (sun.transform.localRotation, sun.intensity, sun.color, sun.shadows, sun.shadowStrength);+ // A light shines along its forward axis: towards the azimuth opposite the sun, tilted down by the elevation.+ sun.transform.rotation = Quaternion.Euler(preset.SunElevation, preset.SunAzimuth - 180f, 0f);+ sun.intensity = preset.SunIntensity; sun.color = preset.SunColour;+ sun.shadows = LightShadows.Soft; sun.shadowStrength = preset.ShadowStrength;+ undo.Add(() =>+ {+ if (sun == null) return;+ sun.transform.localRotation = s0.Item1; sun.intensity = s0.Item2; sun.color = s0.Item3; sun.shadows = s0.Item4; sun.shadowStrength = s0.Item5;+ });+ }+ var a0 = (RenderSettings.ambientMode, RenderSettings.ambientSkyColor, RenderSettings.ambientEquatorColor, RenderSettings.ambientGroundColor, RenderSettings.ambientProbe);+ RenderSettings.ambientMode = AmbientMode.Trilight;+ RenderSettings.ambientSkyColor = preset.AmbientSky; RenderSettings.ambientEquatorColor = preset.AmbientEquator; RenderSettings.ambientGroundColor = preset.AmbientGround;+ undo.Add(() =>+ {+ RenderSettings.ambientMode = a0.Item1; RenderSettings.ambientSkyColor = a0.Item2;+ RenderSettings.ambientEquatorColor = a0.Item3; RenderSettings.ambientGroundColor = a0.Item4;+ // Last: a Trilight scene regenerates its probe from the colours anyway; any other mode gets its own back.+ RenderSettings.ambientProbe = a0.Item5;+ });+ if (preset.Windows && boardRoot != null && board != null)+ {+ var windows = LitWindows(board, only);+ if (windows.Count > 0) undo.Add(Emit(boardRoot.transform, windows));+ }+ bool done = false;+ return () => { if (done) return; done = true; for (int i = undo.Count - 1; i >= 0; i--) undo[i](); };+ }++ // --- the night's lit windows ---++ /// <summary>The prototype kinds whose buildings get lit windows at night.</summary>+ public static readonly string[] LitKinds = { "city", "town" };+ public static readonly Color WindowColour = new Color(1.00f, 0.80f, 0.46f);+ /// <summary>A window's width and height and the gap off the wall, as shares of the building's footprint side; the+ /// share of windows lit.</summary>+ const float WindowW = 0.13f, WindowH = 0.085f, OffWall = 0.012f, LitShare = 0.55f;++ /// <summary>One window: its centre, its outward normal and its in-wall right axis, in board space, and its size (m).</summary>+ public readonly struct Window+ {+ public readonly Vector3 Centre, Normal, Right; public readonly float Width, Height;+ public Window(Vector3 centre, Vector3 normal, Vector3 right, float width, float height) { Centre = centre; Normal = normal; Right = right; Width = width; Height = height; }+ }++ /// <summary>The lit windows of the board's city and town tiles (deterministic: the tiles' own placements at the+ /// build's seed, and a hash of each window's place for which are lit). A building is a piece placed by its width+ /// as a box (its model's footprint and height, or the box stand-in's); its four walls get a grid of windows, the+ /// rows by its height.</summary>+ public static List<Window> LitWindows(HexBoard board, string? only = null, int seed = 1948)+ {+ var list = new List<Window>();+ var surface = new HexBoardSurface(board);+ var shapes = new Dictionary<string, Vector3>(StringComparer.Ordinal);+ foreach (var h in board.Hexes.Values.OrderBy(h => h.q).ThenBy(h => h.r))+ {+ if (h.prototype == "" || (only != null && h.prototype != only) || !HexPrototypes.All.ContainsKey(h.prototype)) continue;+ if (Array.IndexOf(LitKinds, HexPrototypes.Info(h.prototype).Kind) < 0) continue;+ var ctx = new HexTileContext(h.q, h.r, surface, seed);+ HexPrototypes.Create(h.prototype).Build(ctx);+ foreach (var p in ctx.Placements)+ {+ if (p.StandIn != StandIn.Box || p.Fit != Fit.Width) continue;+ var id = HexModels.Resolve(p.Model, p.Position);+ if (!shapes.TryGetValue(id, out var shape)) shapes[id] = shape = Shape(id);+ AddWalls(list, p.Matrix, shape);+ }+ }+ return list;+ }++ /// <summary>A building's size in its placement's unit frame (the larger footprint side is 1).</summary>+ static Vector3 Shape(string id)+ {+ var prefab = HexModels.Prefab(id);+ if (prefab == null || HexModels.Skinned(prefab)) return new Vector3(1f, 0.65f, 1f); // the box stand-in+ var go = Object.Instantiate(prefab);+ try+ {+ var b = HexModels.Bounds(go).size;+ float side = Mathf.Max(b.x, b.z, 1e-4f);+ return new Vector3(b.x / side, b.y / side, b.z / side);+ }+ finally { Object.DestroyImmediate(go); }+ }++ static void AddWalls(List<Window> list, Matrix4x4 m, Vector3 shape)+ {+ float side = m.lossyScale.x;+ int rows = Mathf.Clamp(Mathf.RoundToInt(shape.y / 0.2f), 1, 8);+ for (int wall = 0; wall < 4; wall++)+ {+ bool alongX = wall % 2 == 0; // walls 0 and 2 face +z and -z and run along x+ float sign = wall < 2 ? 1f : -1f;+ var normal = alongX ? new Vector3(0f, 0f, sign) : new Vector3(sign, 0f, 0f);+ var right = alongX ? Vector3.right : Vector3.forward;+ float half = (alongX ? shape.z : shape.x) * 0.5f, length = alongX ? shape.x : shape.z;+ int cols = Mathf.Clamp(Mathf.RoundToInt(length / 0.28f), 1, 4);+ for (int row = 0; row < rows; row++)+ for (int col = 0; col < cols; col++)+ {+ var local = normal * (half + OffWall) + right * ((col + 0.5f) / cols - 0.5f) * length * 0.8f+ + Vector3.up * shape.y * (0.18f + 0.62f * (row + 0.5f) / rows);+ var centre = m.MultiplyPoint3x4(local);+ uint hash = unchecked((uint)(Mathf.FloorToInt(centre.x) * 73856093 ^ Mathf.FloorToInt(centre.y) * 83492791 ^ Mathf.FloorToInt(centre.z) * 19349663));+ if ((hash % 1000u) / 1000f >= LitShare) continue;+ list.Add(new Window(centre, m.MultiplyVector(normal).normalized, m.MultiplyVector(right).normalized,+ WindowW * side, WindowH * side * Mathf.Min(1f, shape.y * 2f)));+ }+ }+ }++ /// <summary>The windows as one mesh of quads with one unlit, warm material under <paramref name="root"/>; returns+ /// the action that destroys all three.</summary>+ static Action Emit(Transform root, List<Window> windows)+ {+ var vertices = new List<Vector3>(windows.Count * 4); var triangles = new List<int>(windows.Count * 6);+ foreach (var w in windows)+ {+ int i = vertices.Count;+ var r = w.Right * (w.Width * 0.5f); var u = Vector3.up * (w.Height * 0.5f);+ vertices.Add(w.Centre - r - u); vertices.Add(w.Centre - r + u); vertices.Add(w.Centre + r + u); vertices.Add(w.Centre + r - u);+ // Wound to face along the window's normal.+ bool front = Vector3.Dot(Vector3.Cross(2f * u, 2f * r), w.Normal) > 0f;+ if (front) triangles.AddRange(new[] { i, i + 1, i + 2, i, i + 2, i + 3 });+ else triangles.AddRange(new[] { i, i + 2, i + 1, i, i + 3, i + 2 });+ }+ var mesh = new Mesh { name = WindowsName, indexFormat = IndexFormat.UInt32 };+ mesh.SetVertices(vertices); mesh.SetTriangles(triangles, 0); mesh.RecalculateBounds();+ // The shipped unlit template (HexMaterials: Shader.Find returns null in players), opaque warm light.+ var material = HexMaterials.New(HexMaterials.Edges);+ material.name = WindowsName;+ material.SetColor("_BaseColor", WindowColour);+ var go = new GameObject(WindowsName, typeof(MeshFilter), typeof(MeshRenderer));+ go.transform.SetParent(root, false);+ go.GetComponent<MeshFilter>().sharedMesh = mesh;+ var renderer = go.GetComponent<MeshRenderer>();+ renderer.sharedMaterial = material;+ renderer.shadowCastingMode = ShadowCastingMode.Off; renderer.receiveShadows = false;+ return () => { Destroy(go); Destroy(mesh); Destroy(material); };+ }++ static void Destroy(Object? o) { if (o == null) return; if (Application.isPlaying) Object.Destroy(o); else Object.DestroyImmediate(o); }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexTimeOfDay.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Core/HexTimeOfDay.cs.metanew file mode 100644index 000000000..93a7f05a5--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexTimeOfDay.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 906b51d28e634acabea7ab9545c46928\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.csnew file mode 100644index 000000000..a04c73caa--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs@@ -0,0 +1,385 @@+#nullable enable+using System;+using System.Collections.Generic;+using UnityEngine;+using UnityEngine.Rendering;+using Object = UnityEngine.Object;++namespace Statecraft.HexTiles+{+ /// <summary>The "under attack" look for a hex (a city or the unit on it): presentation only. It is a visual state+ /// the simulation can drive later (show it on a hex, hide it); nothing here reads or writes the simulation, and it is+ /// never saved in a board or its overrides. Movement and combat rules are the owner's (docs/gdd/military-combat.md).+ /// Kept calm, not cinematic: a few grey smoke columns drifting east on the prevailing west wind, a low warm glow+ /// where each rises, and a muted red border that pulses slowly. Three meshes and three materials, all made by and+ /// destroyed with the look's object (HexUnderAttackLook).</summary>+ public static class HexUnderAttack+ {+ public static string Name(int q, int r) => $"under attack {q},{r}";++ /// <summary>The look's material templates (Resources/HexTiles/Materials): smoke, fire glow, border.</summary>+ public static readonly string[] Materials = { HexMaterials.AttackSmoke, HexMaterials.AttackGlow, HexMaterials.AttackBorder };++ /// <summary>The border's pulse: slow, a steady signal rather than a flash.</summary>+ public const float PulsePeriodS = 2.4f;+ /// <summary>Smoke columns per hex: "a few points", outside the unit spot.</summary>+ public const int Columns = 3;++ /// <summary>Shows the look on hex (q, r) of the board under <paramref name="boardRoot"/> (board space, as+ /// HexBoardBuilder builds it), on <paramref name="surface"/>. Showing it again replaces it. Returns its object;+ /// Hide (or destroying the object) removes it and everything it made.</summary>+ public static GameObject Show(Transform boardRoot, IHexSurface surface, int q, int r, float sizeM = HexScale.HexM)+ {+ Hide(boardRoot, q, r);+ var go = new GameObject(Name(q, r));+ go.transform.SetParent(boardRoot, false);+ var c = HexGeometry.Centre(q, r, sizeM);+ go.transform.localPosition = new Vector3(c.x, surface.Height(c), c.z);+ go.AddComponent<HexUnderAttackLook>().Build(surface, q, r, sizeM);+ return go;+ }++ /// <summary>Removes the look from hex (q, r); false when it was not shown.</summary>+ public static bool Hide(Transform boardRoot, int q, int r)+ {+ var t = boardRoot.Find(Name(q, r));+ if (t == null) return false;+ t.SetParent(null, false);+ if (Application.isPlaying) Object.Destroy(t.gameObject); else Object.DestroyImmediate(t.gameObject);+ return true;+ }++ public static bool IsShown(Transform boardRoot, int q, int r) => boardRoot.Find(Name(q, r)) != null;++ /// <summary>The border's strength at time <paramref name="t"/> (seconds), 0 to 1: a smooth sine, the same for+ /// every hex so several attacked hexes pulse together.</summary>+ public static float Pulse(float t) => 0.5f - 0.5f * Mathf.Cos(Frac(t / PulsePeriodS) * 2f * Mathf.PI);++ /// <summary>Where the smoke columns rise, relative to the hex centre (y = 0), seeded by (q, r). They keep out of the+ /// unit spot and out of the hex's south half, so a column (seen from the south, as the board camera sees it)+ /// does not stand in front of the unit or the city's centre; and far enough in that the drifting top stays inside.</summary>+ public static Vector3[] SmokeBases(int q, int r, float sizeM)+ {+ var rng = new System.Random(unchecked(q * 73856093 ^ r * 19349663 ^ 0x5EED));+ var bases = new Vector3[Columns];+ // Spread over the north half only (2 to 170 degrees from east): the camera looks from the south, so a column+ // north of a figure or a building stands behind it, never in front.+ float a0 = 12f + (float)rng.NextDouble() * 16f;+ for (int i = 0; i < Columns; i++)+ {+ float a = (a0 + i * 66f + ((float)rng.NextDouble() - 0.5f) * 20f) * Mathf.Deg2Rad;+ // Beyond the squad's formation (its figures stand up to ~0.38 S out).+ float d = sizeM * (0.40f + (float)rng.NextDouble() * 0.12f);+ var p = new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a)) * d;+ // Pull in until the whole column (glow at the foot, the top drifted downwind) fits the hex.+ while (d > sizeM * 0.32f && !(HexGeometry.InHex(p, Vector3.zero, sizeM, Smoke.GlowM * sizeM * 1.2f + 60f)+ && HexGeometry.InHex(p + Smoke.Wind * Smoke.DriftM * sizeM, Vector3.zero, sizeM, (Smoke.TopRadius * 1.2f * Smoke.QuadScale * 1.09f + 0.02f) * sizeM + 60f)))+ { d -= sizeM * 0.02f; p = p.normalized * d; }+ bases[i] = p;+ }+ return bases;+ }++ internal static float Frac(float x) => x - Mathf.Floor(x);++ /// <summary>Smoke and glow shape, in shares of the hex size S (units are ~0.2 S tall, buildings ~0.15 S across).</summary>+ internal static class Smoke+ {+ /// <summary>Prevailing west wind: the smoke leans east, a little north.</summary>+ public static readonly Vector3 Wind = new Vector3(0.94f, 0f, 0.34f);+ public const int Puffs = 14;+ public const float LifeS = 13f, HeightShare = 0.62f, DriftM = 0.2f, BaseRadius = 0.04f, TopRadius = 0.11f;+ /// <summary>A puff's drawn size over its radius: the soft texture fades well inside its rim.</summary>+ public const float QuadScale = 1.5f;+ /// <summary>Where the smoke starts: above the flames, so they show at its foot.</summary>+ public const float FootShare = 0.04f;+ public const float Alpha = 0.92f, GlowM = 0.11f;+ }+ }++ /// <summary>Animates one shown look, in edit mode and in play: Time(t) samples the smoke, the glow's flicker and the+ /// border's pulse at t seconds, as a pure function of t and the hex (seeded by q, r), so captures and tests are+ /// deterministic. Set Hold to keep a sampled time (Update then leaves it). Destroys its meshes and materials with+ /// its object.</summary>+ [ExecuteAlways]+ public sealed class HexUnderAttackLook : MonoBehaviour+ {+ public int Q, R;+ /// <summary>Keep the last sampled time: Update does not advance it.</summary>+ public bool Hold;+ public float SampledT { get; private set; } = float.NaN;++ readonly List<Object> owned = new List<Object>();+ Mesh smoke = null!, glow = null!;+ Material border = null!;+ float sizeM;+ Vector3[] bases = Array.Empty<Vector3>();+ float[] phase = Array.Empty<float>();+ // Smoke: one soft camera-facing octagon per puff. Time(t) samples each puff's centre, size, spin and colour;+ // Face(right, up) writes them for a view (the board camera's by default, each rendering camera's in turn).+ Vector3[] puffAt = Array.Empty<Vector3>(); float[] puffRadius = Array.Empty<float>(), puffSpin = Array.Empty<float>();+ Vector3[] smokeV = Array.Empty<Vector3>(), smokeN = Array.Empty<Vector3>(); Color32[] smokeC = Array.Empty<Color32>();+ /// <summary>A puff is an octagon round the soft disc (its corners hug the disc, unlike a quad's).</summary>+ const int PuffSides = 8;+ /// <summary>The octagon's rim in the puff's (right, up) plane, circumscribing the unit disc.</summary>+ static readonly Vector2[] PuffRim = Rim();+ static Vector2[] Rim()+ {+ var rim = new Vector2[PuffSides];+ float r = 1f / Mathf.Cos(Mathf.PI / PuffSides);+ for (int k = 0; k < PuffSides; k++) { float a = (k + 0.5f) * 2f * Mathf.PI / PuffSides; rim[k] = new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * r; }+ return rim;+ }+ /// <summary>The board camera's view (HexBoardCapture and the game rig: pitch 50 degrees, facing north).</summary>+ static readonly Quaternion BoardView = Quaternion.Euler(50f, 0f, 0f);+ // Glow: fixed vertices (discs on the ground, small flame cones), per-vertex base colour scaled by the flicker.+ Vector3[] glowRest = Array.Empty<Vector3>(), glowV = Array.Empty<Vector3>(); Color[] glowBase = Array.Empty<Color>(); Color32[] glowC = Array.Empty<Color32>();+ int[] glowColumn = Array.Empty<int>(); bool[] glowFlameTip = Array.Empty<bool>();++ static readonly Color SmokeLow = new Color(0.13f, 0.12f, 0.115f), SmokeHigh = new Color(0.40f, 0.395f, 0.385f);+ static readonly Color GlowCore = new Color(1f, 0.34f, 0.08f), FlameCore = new Color(1f, 0.62f, 0.22f);+ static readonly Color BorderColour = new Color(0.78f, 0.13f, 0.10f);+ const float BorderLowAlpha = 0.3f, BorderHighAlpha = 0.88f;++ internal void Build(IHexSurface surface, int q, int r, float size)+ {+ Q = q; R = r; sizeM = size;+ var centre = transform.localPosition;+ float Ground(Vector3 local) { var p = centre + local; return Mathf.Max(surface.Height(new Vector3(p.x, 0f, p.z)), 0f) - centre.y; }+ bases = HexUnderAttack.SmokeBases(q, r, size);+ phase = new float[bases.Length];+ var rng = new System.Random(unchecked(q * 83492791 ^ r * 2654435 ^ 0xF17E));+ for (int i = 0; i < bases.Length; i++) { bases[i].y = Ground(bases[i]); phase[i] = (float)rng.NextDouble(); }+ Array.Sort(bases, phase, Comparer<Vector3>.Create((a, b) => b.z.CompareTo(a.z))); // far (north) first++ smoke = Own(new Mesh { name = "under-attack-smoke" }); smoke.MarkDynamic();+ int n = bases.Length * HexUnderAttack.Smoke.Puffs;+ puffAt = new Vector3[n]; puffRadius = new float[n]; puffSpin = new float[n];+ const int V = PuffSides + 1;+ smokeV = new Vector3[n * V]; smokeN = new Vector3[n * V]; smokeC = new Color32[n * V];+ var uv = new Vector2[n * V]; var tris = new int[n * PuffSides * 3];+ for (int p = 0; p < n; p++)+ {+ int o = p * V;+ uv[o] = new Vector2(0.5f, 0.5f);+ for (int k = 0; k < PuffSides; k++)+ {+ uv[o + 1 + k] = new Vector2(0.5f + 0.5f * PuffRim[k].x, 0.5f + 0.5f * PuffRim[k].y);+ // Clockwise as the viewer sees it (rim counter-clockwise in right/up): centre, next, this.+ tris[(p * PuffSides + k) * 3] = o; tris[(p * PuffSides + k) * 3 + 1] = o + 1 + (k + 1) % PuffSides; tris[(p * PuffSides + k) * 3 + 2] = o + 1 + k;+ }+ }+ smoke.vertices = smokeV; smoke.normals = smokeN; smoke.colors32 = smokeC; smoke.uv = uv; smoke.triangles = tris;+ Part("Smoke", smoke, HexMaterials.AttackSmoke).SetTexture("_BaseMap", Own(PuffTexture()));++ glow = Own(BuildGlow(Ground)); glow.MarkDynamic();+ Part("Glow", glow, HexMaterials.AttackGlow);++ var ring = Own(BuildBorder(Ground));+ border = Part("Border", ring, HexMaterials.AttackBorder);+ Time(0f);+ }++ T Own<T>(T o) where T : Object { owned.Add(o); return o; }++ Material Part(string name, Mesh mesh, string material)+ {+ var go = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer));+ go.transform.SetParent(transform, false);+ go.GetComponent<MeshFilter>().sharedMesh = mesh;+ var m = Own(HexMaterials.New(material));+ var r = go.GetComponent<MeshRenderer>(); r.sharedMaterial = m;+ r.shadowCastingMode = ShadowCastingMode.Off; r.receiveShadows = false;+ r.lightProbeUsage = LightProbeUsage.Off; r.reflectionProbeUsage = ReflectionProbeUsage.Off;+ return m;+ }++ /// <summary>Samples the look at <paramref name="t"/> seconds: the same t gives the same meshes and colours.</summary>+ public void Time(float t)+ {+ SampledT = t;+ int P = HexUnderAttack.Smoke.Puffs;+ float S = sizeM, top = HexUnderAttack.Smoke.HeightShare * S;+ int slot = 0;+ var order = new (float u, int i)[P];+ for (int c = 0; c < bases.Length; c++)+ {+ for (int i = 0; i < P; i++) order[i] = (HexUnderAttack.Frac(t / HexUnderAttack.Smoke.LifeS + (i + phase[c]) / P), i);+ Array.Sort(order, (a, b) => a.u.CompareTo(b.u)); // low first: the camera is above, so higher puffs are nearer+ foreach (var (u, i) in order)+ {+ float seed = c * 7.31f + i * 1.93f, own = HexUnderAttack.Frac(Mathf.Sin(seed * 12.9898f) * 43758.547f);+ // Each puff its own size and offset, so a column reads as smoke rather than a stack of beads.+ float radius = Mathf.Lerp(HexUnderAttack.Smoke.BaseRadius, HexUnderAttack.Smoke.TopRadius, Mathf.Sqrt(u)) * S * (0.8f + 0.4f * own);+ // Fade in just above the fire, thin out towards the top; the top puffs also shrink as they disperse.+ float alpha = HexUnderAttack.Smoke.Alpha * Mathf.SmoothStep(0f, 1f, u / 0.06f) * (1f - Mathf.SmoothStep(0f, 1f, (u - 0.55f) / 0.45f));+ radius *= 1f - 0.25f * Mathf.SmoothStep(0f, 1f, (u - 0.75f) / 0.25f);+ var wobble = new Vector3(Mathf.Sin(seed * 3.1f + u * 5f), 0f, Mathf.Cos(seed * 2.3f + u * 4f)) * (0.02f * S * Mathf.Sqrt(u));+ var at = bases[c] + new Vector3(0f, HexUnderAttack.Smoke.FootShare * S + radius * 0.5f + u * top, 0f)+ + HexUnderAttack.Smoke.Wind * (HexUnderAttack.Smoke.DriftM * S * Mathf.Pow(u, 1.4f)) + wobble;+ var colour = Color.Lerp(SmokeLow, SmokeHigh, Mathf.SmoothStep(0f, 1f, u / 0.7f)); colour.a = alpha;+ Color32 c32 = colour;+ puffAt[slot] = at; puffRadius[slot] = radius; puffSpin[slot] = (own - 0.5f) * 0.7f + u * 0.6f;+ for (int v = 0; v <= PuffSides; v++) smokeC[slot * (PuffSides + 1) + v] = c32;+ slot++;+ }+ }+ smoke.colors32 = smokeC;+ Face(BoardView * Vector3.right, BoardView * Vector3.up);++ for (int v = 0; v < glowRest.Length; v++)+ {+ float f = Flicker(t, phase[glowColumn[v]]);+ var col = glowBase[v]; col.a *= f;+ glowC[v] = col;+ var p = glowRest[v];+ if (glowFlameTip[v]) p.y = bases[glowColumn[v]].y + (p.y - bases[glowColumn[v]].y) * (0.8f + 0.35f * Flicker(t * 1.7f, phase[glowColumn[v]] + v * 0.13f));+ glowV[v] = p;+ }+ glow.vertices = glowV; glow.colors32 = glowC; glow.RecalculateBounds();++ var b = BorderColour; b.a = Mathf.Lerp(BorderLowAlpha, BorderHighAlpha, HexUnderAttack.Pulse(t));+ border.SetColor("_BaseColor", b);+ }++ /// <summary>Writes the smoke puffs to face a view with these world right and up axes (the puffs are round, so+ /// only the view matters, not the time).</summary>+ void Face(Vector3 right, Vector3 up)+ {+ right = transform.InverseTransformDirection(right); up = transform.InverseTransformDirection(up);+ var normal = Vector3.Cross(up, right).normalized; // towards the viewer (Unity's cross is left-handed)+ for (int p = 0; p < puffAt.Length; p++)+ {+ float cs = Mathf.Cos(puffSpin[p]), sn = Mathf.Sin(puffSpin[p]);+ float h = puffRadius[p] * HexUnderAttack.Smoke.QuadScale;+ Vector3 x = (right * cs + up * sn) * h, y = (up * cs - right * sn) * h;+ var c = puffAt[p];+ int o = p * (PuffSides + 1);+ smokeV[o] = c; smokeN[o] = normal;+ for (int k = 0; k < PuffSides; k++) { smokeV[o + 1 + k] = c + x * PuffRim[k].x + y * PuffRim[k].y; smokeN[o + 1 + k] = normal; }+ }+ smoke.vertices = smokeV; smoke.normals = smokeN; smoke.RecalculateBounds();+ }++ /// <summary>A soft, slightly lumpy puff (white, alpha falling to the rim; a little darker below, as smoke+ /// shades itself). Pure arithmetic, so every look draws the same texture.</summary>+ static Texture2D PuffTexture()+ {+ const int N = 64;+ var t = new Texture2D(N, N, TextureFormat.RGBA32, true) { name = "under-attack-puff", wrapMode = TextureWrapMode.Clamp };+ var px = new Color32[N * N];+ for (int j = 0; j < N; j++)+ for (int i = 0; i < N; i++)+ {+ float x = (i + 0.5f) / N * 2f - 1f, y = (j + 0.5f) / N * 2f - 1f, a = Mathf.Atan2(y, x);+ float rim = 0.86f + 0.07f * Mathf.Sin(a * 3f + 0.6f) + 0.05f * Mathf.Sin(a * 5f + 2.1f);+ float d = Mathf.Sqrt(x * x + y * y) / rim;+ float alpha = Mathf.Pow(Mathf.Clamp01(1f - d * d), 0.7f);+ float shade = Mathf.Lerp(0.72f, 1f, (y + 1f) * 0.5f);+ px[j * N + i] = new Color(shade, shade, shade, alpha);+ }+ t.SetPixels32(px); t.Apply(true, false);+ return t;+ }++ void OnEnable() => RenderPipelineManager.beginCameraRendering += FaceCamera;+ void OnDisable() => RenderPipelineManager.beginCameraRendering -= FaceCamera;+ void FaceCamera(ScriptableRenderContext context, Camera cam)+ {+ if (smoke != null && puffAt.Length > 0) Face(cam.transform.right, cam.transform.up);+ }++ /// <summary>A slow, irregular flicker between about 0.65 and 1 (two sines), offset per column.</summary>+ static float Flicker(float t, float phase) =>+ 0.82f + 0.11f * Mathf.Sin(2f * Mathf.PI * (t * 0.7f + phase)) + 0.07f * Mathf.Sin(2f * Mathf.PI * (t * 1.9f + phase * 2.3f));++ /// <summary>Per column: a soft warm disc on the ground (centre bright, rim clear) and a few small flame cones.</summary>+ Mesh BuildGlow(Func<Vector3, float> ground)+ {+ const int Rim = 18, Flames = 3, Sides = 5; const float LiftM = 22f;+ var v = new List<Vector3>(); var col = new List<Color>(); var cols = new List<int>(); var tip = new List<bool>(); var tris = new List<int>();+ var rng = new System.Random(unchecked(Q * 19349663 ^ R * 83492791 ^ 0x6A0));+ for (int c = 0; c < bases.Length; c++)+ {+ var b = bases[c]; float rad = HexUnderAttack.Smoke.GlowM * sizeM;+ int o = v.Count;+ v.Add(new Vector3(b.x, b.y + LiftM, b.z)); col.Add(new Color(GlowCore.r, GlowCore.g, GlowCore.b, 0.85f));+ for (int k = 0; k < Rim; k++)+ {+ float a = k * 2f * Mathf.PI / Rim;+ // An irregular rim, so the patch reads as burning ground rather than a decal.+ float rr = rad * (0.8f + 0.35f * (float)rng.NextDouble());+ var p = b + new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a)) * rr; p.y = ground(p) + LiftM;+ v.Add(p); col.Add(new Color(GlowCore.r, GlowCore.g * 0.8f, GlowCore.b, 0f));+ tris.AddRange(new[] { o, o + 1 + (k + 1) % Rim, o + 1 + k });+ }+ for (int k = 0; k <= Rim; k++) { cols.Add(c); tip.Add(false); }+ for (int f = 0; f < Flames; f++)+ {+ float a = (float)rng.NextDouble() * 2f * Mathf.PI, d = (float)rng.NextDouble() * rad * 0.4f;+ var foot = b + new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a)) * d; foot.y = ground(foot) + LiftM * 0.5f;+ float h = sizeM * (0.045f + 0.03f * (float)rng.NextDouble()), w = sizeM * (0.016f + 0.008f * (float)rng.NextDouble());+ int o2 = v.Count;+ for (int s = 0; s < Sides; s++)+ {+ float sa = s * 2f * Mathf.PI / Sides + a;+ v.Add(foot + new Vector3(Mathf.Cos(sa), 0f, Mathf.Sin(sa)) * w); col.Add(new Color(GlowCore.r, GlowCore.g, GlowCore.b, 0.8f));+ cols.Add(c); tip.Add(false);+ }+ v.Add(foot + Vector3.up * h); col.Add(new Color(FlameCore.r, FlameCore.g, FlameCore.b, 0.15f)); cols.Add(c); tip.Add(true);+ for (int s = 0; s < Sides; s++) tris.AddRange(new[] { o2 + s, o2 + Sides, o2 + (s + 1) % Sides });+ }+ }+ glowRest = v.ToArray(); glowV = (Vector3[])glowRest.Clone(); glowBase = col.ToArray(); glowC = new Color32[glowRest.Length];+ glowColumn = cols.ToArray(); glowFlameTip = tip.ToArray();+ var mesh = new Mesh { name = "under-attack-glow" };+ mesh.vertices = glowV; mesh.colors32 = glowC; mesh.triangles = tris.ToArray(); mesh.RecalculateNormals();+ return mesh;+ }++ /// <summary>A band just inside the hex edge: a solid outer strip, then a soft inner fade, following the ground.+ /// Its colour and pulse come from the material (_BaseColor), so pulsing costs no mesh upload.</summary>+ Mesh BuildBorder(Func<Vector3, float> ground)+ {+ const int Segments = 12; const float LiftM = 24f;+ float outer = 0.975f, solid = 0.035f, fade = 0.07f; // corner-radius shares of S+ var rings = new[] { (outer, 1f), (outer - solid, 0.8f), (outer - solid - fade, 0f) };+ var corners = HexGeometry.Corners(Vector3.zero, sizeM);+ var v = new List<Vector3>(); var col = new List<Color>(); var tris = new List<int>();+ int perRing = 6 * Segments;+ foreach (var (share, alpha) in rings)+ for (int e = 0; e < 6; e++)+ for (int s = 0; s < Segments; s++)+ {+ var p = Vector3.Lerp(corners[e], corners[(e + 1) % 6], s / (float)Segments) * share;+ p.y = ground(p) + LiftM;+ v.Add(p); col.Add(new Color(1f, 1f, 1f, alpha));+ }+ for (int ring = 0; ring < 2; ring++)+ for (int i = 0; i < perRing; i++)+ {+ int a = ring * perRing + i, b = ring * perRing + (i + 1) % perRing, c = a + perRing, d = b + perRing;+ tris.AddRange(new[] { a, b, c, b, d, c });+ }+ var mesh = new Mesh { name = "under-attack-border" };+ mesh.SetVertices(v); mesh.SetColors(col); mesh.SetTriangles(tris, 0); mesh.RecalculateNormals(); mesh.RecalculateBounds();+ return mesh;+ }++ void Update()+ {+ if (Hold || smoke == null) return;+ Time(Application.isPlaying ? UnityEngine.Time.time : (float)UnityEngine.Time.realtimeSinceStartupAsDouble);+#if UNITY_EDITOR+ // Edit mode only updates on a change: ask for the next frame so the smoke and the pulse keep moving.+ if (!Application.isPlaying) UnityEditor.EditorApplication.QueuePlayerLoopUpdate();+#endif+ }++ void OnDestroy()+ {+ foreach (var o in owned) if (o != null) { if (Application.isPlaying) Destroy(o); else DestroyImmediate(o); }+ owned.Clear();+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs.metanew file mode 100644index 000000000..020ae88a1--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: e6fd1f2f9a1f4e96b823aaa3e5a1404f\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.csindex 0b1c69207..1689f8be7 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.cs@@ -57,16 +57,17 @@ namespace Statecraft.HexTilespublic static IHexUnitType Create(string id) =>All.TryGetValue(id, out var t) ? (IHexUnitType)Activator.CreateInstance(t)! : throw new KeyNotFoundException($"no hex unit type '{id}' (known: {string.Join(", ", All.Keys)})");- /// <summary>A formation of <paramref name="models"/> cycled over HexUnitScale.Characters figures: rows of 3, 2, 3- /// (a wedge), spaced HexUnitScale.FigureSpacing, all facing forward.</summary>- public static HexUnit Squad(string title, params string[] models)+ /// <summary>HexUnitScale.Characters figures of one <paramref name="model"/> (Tal, 19 October 2026: a character unit is+ /// one character type, never a mix): rows of 3, 2, 3 (a wedge), spaced HexUnitScale.FigureSpacing, all facing+ /// forward.</summary>+ public static HexUnit Squad(string title, string model){var unit = new HexUnit { Title = title };var slots = new[] { (-1f, 1f), (0f, 1.15f), (1f, 1f), (-0.5f, 0f), (0.5f, 0f), (-1f, -1f), (0f, -0.85f), (1f, -1f) };for (int i = 0; i < HexUnitScale.Characters; i++)unit.Members.Add(new HexUnitMember{- Model = models[i % models.Length], StandIn = StandIn.Figure,+ Model = model, StandIn = StandIn.Figure,Offset = new Vector2(slots[i].Item1, slots[i].Item2) * HexUnitScale.FigureSpacing,HeightShare = HexUnitScale.FigureHeight, CycleShare = HexUnitScale.FigureHeight * HexUnitScale.StridePerHeight,});diff --git a/unity/Assets/Scripts/Map/HexTiles/HexTilesLook.cs b/unity/Assets/Scripts/Map/HexTiles/HexTilesLook.csindex 5da7303cf..d9aa0bd92 100644--- a/unity/Assets/Scripts/Map/HexTiles/HexTilesLook.cs+++ b/unity/Assets/Scripts/Map/HexTiles/HexTilesLook.cs@@ -8,7 +8,8 @@ namespace Statecraft.HexTiles{/// <summary>The hex-tile map (docs/hex-tiles/README.md), opt-in while it covers only central Israel and its models/// are local: Web ?hex-tiles or ?hex-tiles=1, desktop -hex-tiles; a board id picks another board (Web- /// ?hex-tiles=tel_aviv_crop, desktop -hex-tiles tel_aviv_crop). Puts the board on the real map (HexRealMap) under one+ /// ?hex-tiles=tel_aviv_crop, desktop -hex-tiles tel_aviv_crop), with a time of day over it (HexTimeOfDay: Web+ /// &hex-time=dusk|night, desktop -hex-time dusk|night; without the board it does nothing). Puts the board on the real map (HexRealMap) under one/// "HexTiles" root beside the map's own; off with nothing applied touches nothing, so the shipped map is unchanged./// Presentation only: no simulation state is read or written.</summary>public static class HexTilesLook@@ -63,11 +64,17 @@ namespace Statecraft.HexTiles// over them; both come back when the board is removed. Off before the board is placed, so what the kits// switch shows is already settled when the board hides the map's markers on its land.SetDressing(false);- var (root, _) = HexRealMap.Place(map, HexBoard.Load(id), HexBoard.GroundFromResources, holder,+ var board = HexBoard.Load(id);+ var (root, _) = HexRealMap.Place(map, board, HexBoard.GroundFromResources, holder,restoreDressing: () => SetDressing(true));- // Civ's warm, saturated diorama light while the board is up.+ // Civ's warm, saturated diorama light while the board is up, then the time of day asked for over it (day, the+ // default, changes nothing). Teardown runs last registered first, so the time's undo runs before HexLook's.var rig = Camera.main != null ? Camera.main.GetComponent<CameraRig>() : null;- root.GetComponent<HexBoardAssets>().OnTeardown(HexLook.Apply(rig != null && rig.Volume != null ? rig.Volume.profile : null, MapLighting.FindSun()));+ var profile = rig != null && rig.Volume != null ? rig.Volume.profile : null;+ var sun = MapLighting.FindSun();+ var assets = root.GetComponent<HexBoardAssets>();+ assets.OnTeardown(HexLook.Apply(profile, sun));+ assets.OnTeardown(HexTimeOfDay.Apply(HexTimeOfDay.Requested(), profile, sun, root, board));}static void SetDressing(bool on)diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ArabVillage.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ArabVillage.csindex 0054a62b8..d8bd42431 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ArabVillage.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ArabVillage.cs@@ -19,13 +19,13 @@ namespace Statecraft.HexTiles.Prototypes////// The minaret and the prickly pear have no models (tiles:arab_village/...), so they draw stand-ins: Pine, a slim spire,/// for the minaret and a low Tree for the prickly pear.</summary>- [HexPrototype("arab_village")]+ [HexPrototype("arab_village", Kind = "village")]public sealed class ArabVillage : IHexPrototype{public string Title => "Arab stone village on a hill (1948)";public HexTerrain Terrain => HexTerrain.Hills;public string Ground => "hills";- public int TriangleBudget => 60000;+ public int TriangleBudget => 125000; // the shipped b*-v2 buildings at full detail (Tal, 19 Oct 2026): measured 113k on the israel board and the test hex// Explicit house ids, not wildcards: kit_jerusalem* and kit_stone_village* both include b17, kept for the mosque.static readonly string[] Houses = { "sandbox:kit_jerusalem", "sandbox:kit_jerusalem_2", "sandbox:kit_jerusalem_3", "sandbox:kit_stone_village_2" };diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchard.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchard.csindex c5f0ab64b..346ed0d64 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchard.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchard.cs@@ -13,68 +13,116 @@ namespace Statecraft.HexTiles.Prototypes/// stands south of it.////// Triangle estimate (per-instance counts of the local models): at most 21 citrus x 1600 + 6 cypress x 1600 + truck- /// 7000 + packing house up to 1400 = 51,600, plus one flat, against 60,000. Stand-ins draw fewer.</summary>- [HexPrototype("citrus_orchard")]- public sealed class CitrusOrchard : IHexPrototype+ /// 7000 + packing house up to 1400 = 51,600, plus one flat, against 60,000. Stand-ins draw fewer.+ ///+ /// The regional variants (CitrusOrchard<Region><A|B>) subclass it through the protected virtual members:+ /// the grid, the blocks, the grove trees, the windbreaks and the yard. Their defaults are this tile's own, so+ /// citrus_orchard itself builds exactly as before (HexVariantTests).</summary>+ [HexPrototype("citrus_orchard", Kind = "farm")]+ public class CitrusOrchard : IHexPrototype{- public string Title => "Jaffa orange groves (1948)";- public HexTerrain Terrain => HexTerrain.Flat;- public string Ground => "grass";- public int TriangleBudget => HexScale.BudgetForest;+ public virtual string Title => "Jaffa orange groves (1948)";+ public virtual HexTerrain Terrain => HexTerrain.Flat;+ public virtual string Ground => "grass";+ public virtual int TriangleBudget => HexScale.BudgetForest;// Models: the EZ-Tree trees and the Tripo kit and truck are local-only; without them the stand-ins draw.- const string Citrus = "sandbox:citrus_lite", Cypress = "sandbox:cypress_lite", House = "sandbox:kit_moshava*",+ protected const string Citrus = "sandbox:citrus_lite", Cypress = "sandbox:cypress_lite", House = "sandbox:kit_moshava*",Truck = "proto:vehicle-citrus-truck-v1";- static readonly Color Leaf = new Color(0.16f, 0.34f, 0.14f), CypressLeaf = new Color(0.12f, 0.26f, 0.13f),+ protected static readonly Color Leaf = new Color(0.16f, 0.34f, 0.14f), CypressLeaf = new Color(0.12f, 0.26f, 0.13f),Plaster = new Color(0.88f, 0.80f, 0.68f), Lorry = new Color(0.42f, 0.48f, 0.52f), Water = new Color(0.30f, 0.52f, 0.66f);+ /// <summary>A grove block: the first tree at (x0, z0) on the grid, in shares of S, and cols x rows trees.</summary>+ protected readonly struct Block+ {+ public readonly float X0, Z0; public readonly int Cols, Rows;+ public Block(float x0, float z0, int cols, int rows) { X0 = x0; Z0 = z0; Cols = cols; Rows = rows; }+ }++ static readonly Block[] BaseBlocks = { new Block(-0.44f, 0.18f, 3, 3), new Block(0.18f, 0.18f, 3, 2), new Block(-0.44f, -0.33f, 3, 2) };++ /// <summary>The orchard grid's turn in degrees, and the tree spacing along its rows as a share of S.</summary>+ protected virtual float GridYaw(HexTileContext ctx) => 15f;+ protected virtual float Row => 0.13f;+ /// <summary>The grove blocks: north-west 9 trees, north-east 6, south-west 6.</summary>+ protected virtual Block[] Blocks => BaseBlocks;+ /// <summary>The soil painted under a block.</summary>+ protected virtual string BlockSoil => "ploughed";+ /// <summary>The tree at column i, row j of block b (no randomness, so the sequence holds); null leaves a gap.</summary>+ protected virtual (string model, StandIn standIn, Color? tint)? GroveTree(int b, int i, int j) => (Citrus, StandIn.Tree, Leaf);+ /// <summary>A grove tree's height range, as shares of S.</summary>+ protected virtual (float min, float max) TreeHeight => (0.12f, 0.15f);++ /// <summary>A point on the orchard grid, in shares of S.</summary>+ protected static Vector3 Grid(HexTileContext ctx, float yaw, float x, float z) => ctx.Centre + Quaternion.Euler(0f, yaw, 0f) * new Vector3(x * ctx.S, 0f, z * ctx.S);+public void Build(HexTileContext ctx){- float s = ctx.S, gridYaw = 15f, row = 0.13f;- var turn = Quaternion.Euler(0f, gridYaw, 0f);- // A point on the orchard grid, in shares of S.- Vector3 Grid(float x, float z) => ctx.Centre + turn * new Vector3(x * s, 0f, z * s);+ float gridYaw = GridYaw(ctx), row = Row;+ Vector3 G(float x, float z) => Grid(ctx, gridYaw, x, z);- // 1. Dirt tracks painted into the ground: the main track (grid north-south) and the cross track, clipped to the hex.- ctx.PaintStroke("dirt", Grid(0f, -0.95f), Grid(0f, 0.95f), 0.045f * s, 0.9f);- ctx.PaintStroke("dirt", Grid(-0.95f, 0f), Grid(0.95f, 0f), 0.04f * s, 0.9f);+ // 1. Tracks painted into the ground.+ Tracks(ctx, gridYaw);// 2. Grove blocks: tilled soil painted under each, then the trees in straight rows (no position jitter, so rows// read). (x0, z0) is the first tree, cols x rows trees at the row spacing; trees in the unit spot are left out.- Grove(ctx, Grid, gridYaw, row, -0.44f, 0.18f, 3, 3); // north-west, 9- Grove(ctx, Grid, gridYaw, row, 0.18f, 0.18f, 3, 2); // north-east, 6- Grove(ctx, Grid, gridYaw, row, -0.44f, -0.33f, 3, 2); // south-west, 6+ var blocks = Blocks;+ for (int b = 0; b < blocks.Length; b++) Grove(ctx, G, gridYaw, row, b, blocks[b]);++ // 3. Windbreaks, 4. the packing house and its yard, 5. the pool.+ Windbreaks(ctx, gridYaw);+ Yard(ctx, gridYaw);+ Dress(ctx, gridYaw);+ }- // 3. Cypress windbreaks: tight rows along the north edge of the north-west block and the west edge of the- // south-west block.+ /// <summary>The main track (grid north-south) and the cross track, clipped to the hex.</summary>+ protected virtual void Tracks(HexTileContext ctx, float gridYaw)+ {+ float s = ctx.S;+ ctx.PaintStroke("dirt", Grid(ctx, gridYaw, 0f, -0.95f), Grid(ctx, gridYaw, 0f, 0.95f), 0.045f * s, 0.9f);+ ctx.PaintStroke("dirt", Grid(ctx, gridYaw, -0.95f, 0f), Grid(ctx, gridYaw, 0.95f, 0f), 0.04f * s, 0.9f);+ }++ /// <summary>Cypress windbreaks: tight rows along the north edge of the north-west block and the west edge of the+ /// south-west block.</summary>+ protected virtual void Windbreaks(HexTileContext ctx, float gridYaw)+ {+ float s = ctx.S;for (int k = 0; k < 3; k++){- ctx.PlaceByHeight(Cypress, Grid(-0.41f + 0.1f * k, 0.56f), ctx.Range(0f, 360f), ctx.Range(0.17f, 0.19f) * s, StandIn.Pine, CypressLeaf, 0.3f);- ctx.PlaceByHeight(Cypress, Grid(-0.57f, -0.365f + 0.1f * k), ctx.Range(0f, 360f), ctx.Range(0.17f, 0.19f) * s, StandIn.Pine, CypressLeaf, 0.3f);+ ctx.PlaceByHeight(Cypress, Grid(ctx, gridYaw, -0.41f + 0.1f * k, 0.56f), ctx.Range(0f, 360f), ctx.Range(0.17f, 0.19f) * s, StandIn.Pine, CypressLeaf, 0.3f);+ ctx.PlaceByHeight(Cypress, Grid(ctx, gridYaw, -0.57f, -0.365f + 0.1f * k), ctx.Range(0f, 360f), ctx.Range(0.17f, 0.19f) * s, StandIn.Pine, CypressLeaf, 0.3f);}+ }- // 4. The packing house on its painted yard, beside the main track in the south-east quarter and south of the- // unit spot, and the truck beside it.- ctx.PaintGround("dirt", Grid(0.12f, -0.44f), gridYaw, 0.17f * s, 0.36f * s, 0.2f, 0.8f);- ctx.PlaceByWidth(House, Grid(0.11f, -0.36f), gridYaw + 180f * ctx.Rng.Next(2), 0.14f * s, StandIn.Box, Plaster);- ctx.PlaceByWidth(Truck, Grid(0.115f, -0.54f), gridYaw, 0.14f * s, StandIn.Box, Lorry);-- // 5. The square irrigation pool, on the grass east of the yard.- ctx.PlaceFlat(Grid(0.38f, -0.40f), gridYaw, 0.12f * s, 0.12f * s, Water);+ /// <summary>The packing house on its painted yard, beside the main track in the south-east quarter and south of the+ /// unit spot, the truck beside it, and the square irrigation pool on the grass east of the yard.</summary>+ protected virtual void Yard(HexTileContext ctx, float gridYaw)+ {+ float s = ctx.S;+ ctx.PaintGround("dirt", Grid(ctx, gridYaw, 0.12f, -0.44f), gridYaw, 0.17f * s, 0.36f * s, 0.2f, 0.8f);+ ctx.PlaceByWidth(House, Grid(ctx, gridYaw, 0.11f, -0.36f), gridYaw + 180f * ctx.Rng.Next(2), 0.14f * s, StandIn.Box, Plaster);+ ctx.PlaceByWidth(Truck, Grid(ctx, gridYaw, 0.115f, -0.54f), gridYaw, 0.14f * s, StandIn.Box, Lorry);+ ctx.PlaceFlat(Grid(ctx, gridYaw, 0.38f, -0.40f), gridYaw, 0.12f * s, 0.12f * s, Water);}- static void Grove(HexTileContext ctx, System.Func<float, float, Vector3> grid, float gridYaw, float row,- float x0, float z0, int cols, int rows)+ /// <summary>Anything a variant adds last: nothing here.</summary>+ protected virtual void Dress(HexTileContext ctx, float gridYaw) { }++ void Grove(HexTileContext ctx, System.Func<float, float, Vector3> grid, float gridYaw, float row, int b, Block k){- float w = (cols - 1) * row + 0.10f, d = (rows - 1) * row + 0.10f;- ctx.PaintGround("ploughed", grid(x0 + (cols - 1) * row * 0.5f, z0 + (rows - 1) * row * 0.5f), gridYaw, w * ctx.S, d * ctx.S, 0.2f, 0.7f);- for (int i = 0; i < cols; i++)- for (int j = 0; j < rows; j++)+ float w = (k.Cols - 1) * row + 0.10f, d = (k.Rows - 1) * row + 0.10f;+ ctx.PaintGround(BlockSoil, grid(k.X0 + (k.Cols - 1) * row * 0.5f, k.Z0 + (k.Rows - 1) * row * 0.5f), gridYaw, w * ctx.S, d * ctx.S, 0.2f, 0.7f);+ var (hMin, hMax) = TreeHeight;+ for (int i = 0; i < k.Cols; i++)+ for (int j = 0; j < k.Rows; j++){- var at = grid(x0 + i * row, z0 + j * row);- float yaw = ctx.Range(0f, 360f), height = ctx.Range(0.12f, 0.15f) * ctx.S; // drawn even when skipped, so the sequence holds+ var at = grid(k.X0 + i * row, k.Z0 + j * row);+ float yaw = ctx.Range(0f, 360f), height = ctx.Range(hMin, hMax) * ctx.S; // drawn even when skipped, so the sequence holdsif (ctx.InUnitSpot(at, 0.04f * ctx.S)) continue;- ctx.PlaceByHeight(Citrus, at, yaw, height, StandIn.Tree, Leaf, 0.6f);+ var tree = GroveTree(b, i, j);+ if (tree == null) continue;+ ctx.PlaceByHeight(tree.Value.model, at, yaw, height, tree.Value.standIn, tree.Value.tint, 0.6f);}}}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreA.csnew file mode 100644index 000000000..89933be4c--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreA.cs@@ -0,0 +1,24 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, a: three citrus blocks on the coastal plain, the north-east one enlarged, on a grid turned about 35+ /// degrees, sandy tracks between them, and cypress windbreaks along the west and north edges. Caps: at most 24+ /// citrus x ~1,600 = 38,400, 6 cypresses x ~1,600 = 9,600, truck ~7,000 and the house at most 1,400 = 56,400 of+ /// 60,000.</summary>+ [HexPrototype("citrus_orchard_centre_a", Kind = "farm", Region = "centre")]+ public sealed class CitrusOrchardCentreA : CitrusOrchard+ {+ public override string Title => "Citrus groves, centre (a): four blocks, sandy tracks";+ protected override float GridYaw(HexTileContext ctx) => 35f;+ static readonly Block[] Layout = { new Block(-0.44f, 0.18f, 3, 3), new Block(0.18f, 0.18f, 3, 3), new Block(-0.44f, -0.33f, 3, 2) };+ protected override Block[] Blocks => Layout;+ protected override void Tracks(HexTileContext ctx, float gridYaw)+ {+ float s = ctx.S;+ ctx.PaintStroke("beach", Grid(ctx, gridYaw, 0f, -0.95f), Grid(ctx, gridYaw, 0f, 0.95f), 0.05f * s, 0.9f);+ ctx.PaintStroke("beach", Grid(ctx, gridYaw, -0.95f, 0f), Grid(ctx, gridYaw, 0.95f, 0f), 0.045f * s, 0.9f);+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreA.cs.metanew file mode 100644index 000000000..3f0487964--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 0dbe63d0f973949c9b75f87d9c5c74e1\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreB.csnew file mode 100644index 000000000..2a903230f--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreB.cs@@ -0,0 +1,34 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, b: three wide-spaced citrus blocks on a grid turned about -40 degrees, a row of date palms down the main+ /// track, and a cypress windbreak along the north edge only. Caps: at most 15 citrus x ~1,600 = 24,000, 3 cypresses+ /// x ~1,600 = 4,800, 12 palms x ~280 = 3,360, truck ~7,000 and the house at most 1,400 = 40,560 of 60,000.</summary>+ [HexPrototype("citrus_orchard_centre_b", Kind = "farm", Region = "centre")]+ public sealed class CitrusOrchardCentreB : CitrusOrchard+ {+ public override string Title => "Citrus groves, centre (b): wide rows, palm-lined track";+ protected override float GridYaw(HexTileContext ctx) => -40f;+ protected override float Row => 0.15f;+ static readonly Block[] Layout = { new Block(-0.50f, 0.20f, 3, 2), new Block(0.20f, 0.22f, 3, 2), new Block(-0.50f, -0.42f, 2, 2) };+ protected override Block[] Blocks => Layout;+ static readonly Color CypressDark = new Color(0.12f, 0.26f, 0.13f);+ protected override void Windbreaks(HexTileContext ctx, float gridYaw)+ {+ for (int k = 0; k < 3; k++)+ ctx.PlaceByHeight(Cypress, Grid(ctx, gridYaw, -0.47f + 0.15f * k, 0.48f), ctx.Range(0f, 360f), ctx.Range(0.17f, 0.19f) * ctx.S, StandIn.Pine, CypressDark, 0.3f);+ }+ protected override void Dress(HexTileContext ctx, float gridYaw)+ {+ for (int k = 0; k < 12; k++)+ {+ float z = -0.85f + 0.155f * k;+ var at = Grid(ctx, gridYaw, 0.06f, z);+ if (ctx.InUnitSpot(at, 0.04f * ctx.S) || Mathf.Abs(z + 0.45f) < 0.12f) continue;+ ctx.PlaceByHeight("sandbox:date_palm", at, ctx.Range(0f, 360f), ctx.Range(0.14f, 0.17f) * ctx.S, StandIn.Palm, null, 0.3f);+ }+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreB.cs.metanew file mode 100644index 000000000..444c21871--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardCentreB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 1d20cd58f95454d958068615a0543ad0\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthA.csnew file mode 100644index 000000000..76795659b--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthA.cs@@ -0,0 +1,28 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, a: three dense citrus blocks on a grid turned about -25 degrees, a green-crop field beside the packing+ /// house, and an oak and pine windbreak along the north edge. Caps: at most 24 citrus x ~1,600 = 38,400, 6+ /// windbreak trees at most 9,600, truck ~7,000 and the house at most 1,400 = 56,400 of 60,000.</summary>+ [HexPrototype("citrus_orchard_north_a", Kind = "farm", Region = "north")]+ public sealed class CitrusOrchardNorthA : CitrusOrchard+ {+ public override string Title => "Citrus groves, north (a): dense blocks, oak and pine windbreak";+ protected override float GridYaw(HexTileContext ctx) => -25f;+ static readonly Block[] Layout = { new Block(-0.44f, 0.18f, 3, 3), new Block(0.18f, 0.18f, 3, 3), new Block(-0.44f, -0.33f, 3, 2) };+ protected override Block[] Blocks => Layout;+ static readonly Color OakLeaf = new Color(0.30f, 0.42f, 0.20f), PineGreen = new Color(0.20f, 0.33f, 0.18f);+ protected override void Windbreaks(HexTileContext ctx, float gridYaw)+ {+ for (int k = 0; k < 6; k++)+ {+ bool pine = k % 2 == 0;+ ctx.PlaceByHeight(pine ? "sandbox:aleppo_pine_lite" : "sandbox:tabor_oak_lite", Grid(ctx, gridYaw, -0.46f + 0.13f * k, 0.56f), ctx.Range(0f, 360f), ctx.Range(0.15f, 0.18f) * ctx.S, pine ? StandIn.Pine : StandIn.Tree, pine ? PineGreen : OakLeaf, 0.35f);+ }+ }+ protected override void Dress(HexTileContext ctx, float gridYaw) =>+ ctx.PaintGround("green_crop", Grid(ctx, gridYaw, 0.42f, -0.40f), gridYaw + 90f, 0.30f * ctx.S, 0.22f * ctx.S, 0.12f, 0.9f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthA.cs.metanew file mode 100644index 000000000..a39711d98--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ee2cd08ffce97492da7cc4a999a4689f\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthB.csnew file mode 100644index 000000000..4041924db--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthB.cs@@ -0,0 +1,29 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, b: two long citrus blocks in tight rows on a grid turned about 50 degrees, the eastern half in green+ /// crops, and a carob windbreak along the west edge. Caps: at most 20 citrus x ~1,600 = 32,000, 5 carobs x ~650 =+ /// 3,250, truck ~7,000 and the house at most 1,400 = 43,650 of 60,000.</summary>+ [HexPrototype("citrus_orchard_north_b", Kind = "farm", Region = "north")]+ public sealed class CitrusOrchardNorthB : CitrusOrchard+ {+ public override string Title => "Citrus groves, north (b): long blocks, green fields, carobs";+ protected override float GridYaw(HexTileContext ctx) => 50f;+ protected override float Row => 0.11f;+ static readonly Block[] Layout = { new Block(-0.50f, 0.14f, 4, 3), new Block(-0.50f, -0.38f, 4, 2) };+ protected override Block[] Blocks => Layout;+ static readonly Color CarobLeaf = new Color(0.27f, 0.39f, 0.20f);+ protected override void Windbreaks(HexTileContext ctx, float gridYaw)+ {+ for (int k = 0; k < 5; k++)+ ctx.PlaceByHeight("sandbox:carob_lite", Grid(ctx, gridYaw, -0.64f, -0.40f + 0.16f * k), ctx.Range(0f, 360f), ctx.Range(0.13f, 0.15f) * ctx.S, StandIn.Tree, CarobLeaf, 0.45f);+ }+ protected override void Dress(HexTileContext ctx, float gridYaw)+ {+ ctx.PaintGround("green_crop", Grid(ctx, gridYaw, 0.48f, 0.30f), gridYaw, 0.30f * ctx.S, 0.40f * ctx.S, 0.1f, 0.9f);+ ctx.PaintGround("green_crop", Grid(ctx, gridYaw, 0.50f, -0.10f), gridYaw + 90f, 0.26f * ctx.S, 0.22f * ctx.S, 0.1f, 0.9f);+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthB.cs.metanew file mode 100644index 000000000..c5d0032a3--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardNorthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 6ba667d8e7928423f8371030d76f27ae\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthA.csnew file mode 100644index 000000000..37bc36c07--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthA.cs@@ -0,0 +1,32 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, a: a sparse young grove, every other tree missing so the blocks show as a chequer on pale soil, an acacia+ /// windbreak, and bare sand around the blocks. Caps: at most 11 citrus x ~1,600 = 17,600, 6 acacias x ~1,160 =+ /// 6,960, truck ~7,000 and the house at most 1,400 = 32,960 of 60,000.</summary>+ [HexPrototype("citrus_orchard_south_a", Kind = "farm", Region = "south")]+ public sealed class CitrusOrchardSouthA : CitrusOrchard+ {+ public override string Title => "Citrus groves, south (a): sparse young grove, acacias";+ protected override float GridYaw(HexTileContext ctx) => 0f;+ protected override string BlockSoil => "dirt";+ protected override (string model, StandIn standIn, Color? tint)? GroveTree(int b, int i, int j) =>+ (i + j) % 2 == 1 ? null : base.GroveTree(b, i, j);+ static readonly Color AcaciaLeaf = new Color(0.45f, 0.47f, 0.28f);+ protected override void Windbreaks(HexTileContext ctx, float gridYaw)+ {+ for (int k = 0; k < 3; k++)+ {+ ctx.PlaceByHeight("sandbox:acacia_lite", Grid(ctx, gridYaw, -0.41f + 0.14f * k, 0.58f), ctx.Range(0f, 360f), ctx.Range(0.12f, 0.14f) * ctx.S, StandIn.Tree, AcaciaLeaf, 0.5f);+ ctx.PlaceByHeight("sandbox:acacia_lite", Grid(ctx, gridYaw, -0.60f, -0.38f + 0.14f * k), ctx.Range(0f, 360f), ctx.Range(0.12f, 0.14f) * ctx.S, StandIn.Tree, AcaciaLeaf, 0.5f);+ }+ }+ protected override void Dress(HexTileContext ctx, float gridYaw)+ {+ ctx.PaintGround("desert", Grid(ctx, gridYaw, 0.48f, -0.12f), gridYaw, 0.26f * ctx.S, 0.20f * ctx.S, 0.3f, 0.7f);+ ctx.PaintGround("desert", Grid(ctx, gridYaw, -0.10f, -0.70f), gridYaw, 0.40f * ctx.S, 0.20f * ctx.S, 0.3f, 0.7f);+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthA.cs.metanew file mode 100644index 000000000..aeff603a4--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f13e2616a287f4d9b89386ba3bcb0808\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthB.csnew file mode 100644index 000000000..413333120--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthB.cs@@ -0,0 +1,25 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, b: two small citrus blocks and a block of date palms on a grid turned about -30 degrees, ploughed fields+ /// between, and no windbreak. Caps: at most 12 citrus x ~1,600 = 19,200, 9 palms x ~280 = 2,520, truck ~7,000 and+ /// the house at most 1,400 = 30,120 of 60,000.</summary>+ [HexPrototype("citrus_orchard_south_b", Kind = "farm", Region = "south")]+ public sealed class CitrusOrchardSouthB : CitrusOrchard+ {+ public override string Title => "Citrus groves, south (b): small blocks and date palms";+ protected override float GridYaw(HexTileContext ctx) => -30f;+ static readonly Block[] Layout = { new Block(-0.44f, 0.20f, 3, 2), new Block(0.20f, 0.24f, 3, 2), new Block(-0.50f, -0.40f, 3, 3) };+ protected override Block[] Blocks => Layout;+ protected override (string model, StandIn standIn, Color? tint)? GroveTree(int b, int i, int j) =>+ b == 2 ? ("sandbox:date_palm", StandIn.Palm, null) : base.GroveTree(b, i, j);+ protected override void Windbreaks(HexTileContext ctx, float gridYaw) { }+ protected override void Dress(HexTileContext ctx, float gridYaw)+ {+ ctx.PaintGround("ploughed", Grid(ctx, gridYaw, 0.45f, -0.05f), gridYaw, 0.32f * ctx.S, 0.22f * ctx.S, 0.12f, 0.85f);+ ctx.PaintGround("wheat", Grid(ctx, gridYaw, -0.05f, 0.62f), gridYaw + 90f, 0.22f * ctx.S, 0.50f * ctx.S, 0.12f, 0.85f);+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthB.cs.metanew file mode 100644index 000000000..1b45941fc--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CitrusOrchardSouthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 36fd84adc4f4a44ec95273b73daada8f\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CoastalDunes.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CoastalDunes.csindex f68b58f4c..975677e11 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/CoastalDunes.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/CoastalDunes.cs@@ -14,7 +14,7 @@ namespace Statecraft.HexTiles.Prototypes/// 740. 12 flats x 12 = 144. Total about 15,500 of 20,000 with the boat.////// The scrub has no model (tiles:coastal_dunes/scrub), so it draws the Tree stand-in tinted pale sage.</summary>- [HexPrototype("coastal_dunes")]+ [HexPrototype("coastal_dunes", Kind = "nature")]public sealed class CoastalDunes : IHexPrototype{public string Title => "Coastal dunes (1948)";diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/DesertEdge.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/DesertEdge.csindex b36a9da99..7511ebaf2 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/DesertEdge.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/DesertEdge.cs@@ -16,7 +16,7 @@ namespace Statecraft.HexTiles.Prototypes////// Triangle budget by arithmetic (caps below, with measured per-model counts): 6 acacias x ~1,160 = 6,960. 9 rocks x/// ~700 = 6,300. 9 tent boxes x under 50 = under 450. Total under 13,800 of 25,000.</summary>- [HexPrototype("desert_edge")]+ [HexPrototype("desert_edge", Kind = "nature")]public sealed class DesertEdge : IHexPrototype{public string Title => "Desert edge: wadi, acacias, Bedouin tents (1948)";diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreA.csnew file mode 100644index 000000000..3b2f3ee8c--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreA.cs@@ -0,0 +1,22 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, a: a planted wood of Aleppo pines and cypresses mixed, rows turned 50 to 70 degrees, carobs filling the+ /// canopy, grassy clearings. Caps: 20 conifers x ~1,600 = 32,000, 26 carobs x ~650 = 16,900, 9 margin trees x ~650+ /// = 5,850 and 3 rocks x ~700 = 2,100 = 56,850 of 60,000.</summary>+ [HexPrototype("forest_centre_a", Kind = "forest", Region = "centre")]+ public sealed class ForestCentreA : PineForest+ {+ public override string Title => "Forest, centre (a): pine and cypress";+ protected override int MaxPines => 20;+ static readonly Color CypressDark = new Color(0.12f, 0.26f, 0.13f);+ protected override Tree StandTree(HexTileContext ctx) =>+ ctx.Rng.Next(3) == 0 ? new Tree("sandbox:cypress_lite", StandIn.Pine, CypressDark, 0.17f, 0.20f, 0.3f) : base.StandTree(ctx);+ protected override Tree FillTree(HexTileContext ctx) => new Tree(Carob, StandIn.Tree, CarobGreen, 0.13f, 0.15f, 0.45f);+ protected override (float min, float max) RowYaw => (50f, 70f);+ protected override float TrackBearing => 20f;+ protected override string ClearingLayer => "grass";+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreA.cs.metanew file mode 100644index 000000000..eb1753bb1--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: a9b853b80854f43ac94847431a287637\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreB.csnew file mode 100644index 000000000..54e635748--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreB.cs@@ -0,0 +1,25 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, b: open Shephelah woodland, carobs and olives widely spaced on dry grass with large clearings, rows+ /// turned -70 to -50 degrees. Caps: 24 carobs x ~650 = 15,600, 8 olives x ~1,600 = 12,800, 9 margin trees x ~650 =+ /// 5,850 and 3 rocks x ~700 = 2,100 = 36,350 of 60,000.</summary>+ [HexPrototype("forest_centre_b", Kind = "forest", Region = "centre")]+ public sealed class ForestCentreB : PineForest+ {+ public override string Title => "Forest, centre (b): open carob woodland";+ protected override int MaxPines => 24;+ protected override int MaxFill => 8;+ static readonly Color OliveLeaf = new Color(0.38f, 0.44f, 0.28f);+ protected override Tree StandTree(HexTileContext ctx) => new Tree(Carob, StandIn.Tree, CarobGreen, 0.13f, 0.16f, 0.45f);+ protected override Tree FillTree(HexTileContext ctx) => new Tree("sandbox:olive_lite", StandIn.Tree, OliveLeaf, 0.12f, 0.14f, 0.5f);+ protected override (float min, float max) RowYaw => (-70f, -50f);+ protected override float RowGap => 0.19f;+ protected override float TreeGap => 0.20f;+ protected override float Jitter => 0.05f;+ protected override (float big, float small) ClearingRadii => (0.20f, 0.15f);+ protected override string ClearingLayer => "plains";+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreB.cs.metanew file mode 100644index 000000000..0d81cd438--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestCentreB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: a5d1e52f7ab024487b27f09fed24b277\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthA.csnew file mode 100644index 000000000..4dda13ac5--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthA.cs@@ -0,0 +1,24 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, a: an oak woodland, Tabor oaks closing the canopy with a few Aleppo pines and carobs at the margins, its+ /// rows turned 60 to 80 degrees. Caps: 30 oaks x ~650 = 19,500, 6 pines x ~1,600 = 9,600, 9 margin trees x ~650 =+ /// 5,850 and 3 rocks x ~700 = 2,100 = 37,050 of 60,000.</summary>+ [HexPrototype("forest_north_a", Kind = "forest", Region = "north")]+ public sealed class ForestNorthA : PineForest+ {+ public override string Title => "Forest, north (a): oak woodland";+ protected override int MaxPines => 30;+ protected override int MaxFill => 6;+ protected override Tree StandTree(HexTileContext ctx) => new Tree(Oak, StandIn.Tree, OakGreen, 0.14f, 0.18f, 0.45f);+ protected override Tree FillTree(HexTileContext ctx) => new Tree(Pine, StandIn.Pine, PineGreen, 0.17f, 0.20f, 0.3f);+ protected override Tree MarginTree(HexTileContext ctx) => new Tree(Carob, StandIn.Tree, CarobGreen, 0.13f, 0.16f, 0.45f);+ protected override (float min, float max) RowYaw => (60f, 80f);+ protected override float RowGap => 0.15f;+ protected override float TreeGap => 0.15f;+ protected override float Jitter => 0.045f;+ protected override string ClearingLayer => "grass";+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthA.cs.metanew file mode 100644index 000000000..79771f419--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 1e85ef1b5df1347a6aaa7a8127ae6ad7\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthB.csnew file mode 100644index 000000000..a433d8617--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthB.cs@@ -0,0 +1,22 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, b: a dense Aleppo pine wood in tight rows turned -40 to -20 degrees, small clearings, and oaks filling+ /// the gaps. Caps: 26 pines x ~1,600 = 41,600, 10 oaks x ~650 = 6,500, 9 margin trees x ~650 = 5,850 and 3 rocks x+ /// ~700 = 2,100 = 56,050 of 60,000.</summary>+ [HexPrototype("forest_north_b", Kind = "forest", Region = "north")]+ public sealed class ForestNorthB : PineForest+ {+ public override string Title => "Forest, north (b): dense pine wood";+ protected override int MaxPines => 26;+ protected override int MaxFill => 10;+ protected override (float min, float max) RowYaw => (-40f, -20f);+ protected override float RowGap => 0.14f;+ protected override float TreeGap => 0.14f;+ protected override float Jitter => 0.02f;+ protected override (float big, float small) ClearingRadii => (0.11f, 0.08f);+ protected override string ClearingLayer => "grass";+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthB.cs.metanew file mode 100644index 000000000..3dd51b91f--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestNorthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 3581e7777126d46aaa49dd943112202b\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthA.csnew file mode 100644index 000000000..3122a1217--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthA.cs@@ -0,0 +1,29 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, a: an acacia grove on sand, the trees wide apart and loosely set, a few date palms among them, desert+ /// rock in bare clearings. Caps: 18 acacias x ~1,160 = 20,880, 10 palms x ~280 = 2,800, 9 margin acacias x ~1,160 =+ /// 10,440 and 3 rocks x ~700 = 2,100 = 36,220 of 60,000.</summary>+ [HexPrototype("forest_south_a", Kind = "forest", Region = "south")]+ public sealed class ForestSouthA : PineForest+ {+ public override string Title => "Forest, south (a): acacia grove";+ public override HexTerrain Terrain => HexTerrain.Flat;+ public override string Ground => "desert";+ const string Acacia = "sandbox:acacia_lite", Palm = "sandbox:date_palm";+ static readonly Color AcaciaLeaf = new Color(0.45f, 0.47f, 0.28f);+ protected override int MaxPines => 18;+ protected override int MaxFill => 10;+ protected override Tree StandTree(HexTileContext ctx) => new Tree(Acacia, StandIn.Tree, AcaciaLeaf, 0.12f, 0.15f, 0.5f);+ protected override Tree FillTree(HexTileContext ctx) => new Tree(Palm, StandIn.Palm, Color.white, 0.13f, 0.16f, 0.3f);+ protected override Tree MarginTree(HexTileContext ctx) => new Tree(Acacia, StandIn.Tree, AcaciaLeaf, 0.11f, 0.13f, 0.5f);+ protected override (float min, float max) RowYaw => (0f, 90f);+ protected override float RowGap => 0.21f;+ protected override float TreeGap => 0.22f;+ protected override float Jitter => 0.06f;+ protected override string ClearingLayer => "desert";+ protected override string? OutcropModel => "sandbox:desert_rock*";+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthA.cs.metanew file mode 100644index 000000000..095b0ba1c--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 9a50c1832b07c42a099c9d381f45e2c2\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthB.csnew file mode 100644index 000000000..17690cc42--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthB.cs@@ -0,0 +1,30 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, b: a date-palm grove in close rows on green ground, small garden plots in its clearings, acacias round+ /// the edge. Caps: 44 palms x ~280 = 12,320, 6 acacias x ~1,160 = 6,960, 9 margin acacias x ~1,160 = 10,440 and 3+ /// rocks x ~700 = 2,100 = 31,820 of 60,000.</summary>+ [HexPrototype("forest_south_b", Kind = "forest", Region = "south")]+ public sealed class ForestSouthB : PineForest+ {+ public override string Title => "Forest, south (b): date-palm grove";+ public override HexTerrain Terrain => HexTerrain.Flat;+ public override string Ground => "desert";+ const string Acacia = "sandbox:acacia_lite", Palm = "sandbox:date_palm";+ static readonly Color AcaciaLeaf = new Color(0.45f, 0.47f, 0.28f);+ protected override int MaxPines => 44;+ protected override int MaxFill => 6;+ protected override Tree StandTree(HexTileContext ctx) => new Tree(Palm, StandIn.Palm, Color.white, 0.14f, 0.18f, 0.3f);+ protected override Tree FillTree(HexTileContext ctx) => new Tree(Acacia, StandIn.Tree, AcaciaLeaf, 0.12f, 0.14f, 0.5f);+ protected override Tree MarginTree(HexTileContext ctx) => new Tree(Acacia, StandIn.Tree, AcaciaLeaf, 0.12f, 0.14f, 0.5f);+ protected override (float min, float max) RowYaw => (-10f, 10f);+ protected override float RowGap => 0.13f;+ protected override float TreeGap => 0.13f;+ protected override float Jitter => 0.012f;+ protected override (float big, float small) ClearingRadii => (0.13f, 0.10f);+ protected override string ClearingLayer => "green_crop";+ protected override string? OutcropModel => null;+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthB.cs.metanew file mode 100644index 000000000..f24d4cd38--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/ForestSouthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 332f191bbe8f44a73b8441e75dc8d88c\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/JaffaOldCity.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/JaffaOldCity.csindex b2f63c5ff..5d4c454c9 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/JaffaOldCity.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/JaffaOldCity.cs@@ -28,13 +28,13 @@ namespace Statecraft.HexTiles.Prototypes/// - Total about 66,000 of 70,000 with the harbour, about 39,100 without it.////// The clock tower, church, belfry and minaret have no models (tiles:jaffa_old_city/...), so they always draw stand-ins.</summary>- [HexPrototype("jaffa_old_city")]+ [HexPrototype("jaffa_old_city", Kind = "city")]public sealed class JaffaOldCity : IHexPrototype{public string Title => "Jaffa, the old port town (1948)";public HexTerrain Terrain => HexTerrain.Flat;public string Ground => "plains";- public int TriangleBudget => 70000;+ public int TriangleBudget => 125000; // the shipped b*-v2 buildings at full detail (Tal, 19 Oct 2026): measured 113k on the israel board and the test hexconst string House = "sandbox:kit_jaffa*", Cluster = "proto:stone-village-v1", Boat = "proto:vehicle-fishing-boat-1948-v2",Palm = "sandbox:date_palm", ClockTower = "tiles:jaffa_old_city/clock_tower", Church = "tiles:jaffa_old_city/st_peter",diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/JerusalemOldCity.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/JerusalemOldCity.csindex 087cb8c59..cf0503bd2 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/JerusalemOldCity.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/JerusalemOldCity.cs@@ -27,13 +27,13 @@ namespace Statecraft.HexTiles.Prototypes////// The wall, towers, drum, dome and al-Aqsa have no models (tiles:jerusalem_old_city/...), so they always draw stand-ins./// The gold dome is a Tree stand-in whose crown rises out of the drum.</summary>- [HexPrototype("jerusalem_old_city")]+ [HexPrototype("jerusalem_old_city", Kind = "city")]public sealed class JerusalemOldCity : IHexPrototype{public string Title => "Jerusalem, the walled Old City (1948)";public HexTerrain Terrain => HexTerrain.Hills;public string Ground => "hills";- public int TriangleBudget => 90000;+ public int TriangleBudget => 240000; // the shipped b*-v2 buildings at full detail (Tal, 19 Oct 2026): measured 217k on the israel board and the test hexconst string Cluster = "proto:jerusalem-stone-city-v1", House = "sandbox:kit_jerusalem*", Cypress = "sandbox:cypress_lite",Olive = "sandbox:olive_lite", Wall = "tiles:jerusalem_old_city/wall", Tower = "tiles:jerusalem_old_city/tower",diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/JudeanHighlands.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/JudeanHighlands.csindex ccb24f6b7..f41143836 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/JudeanHighlands.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/JudeanHighlands.cs@@ -21,7 +21,7 @@ namespace Statecraft.HexTiles.Prototypes/// under 2,400. Total under 31,400 of 40,000 (still under 36,000 if the limestone variants run twice as heavy).////// The garrigue has no model (tiles:judean_highlands/garrigue), so it draws the Tree stand-in tinted dusty green.</summary>- [HexPrototype("judean_highlands")]+ [HexPrototype("judean_highlands", Kind = "nature")]public sealed class JudeanHighlands : IHexPrototype{public string Title => "Judean highlands: limestone crags, terraced olives (1948)";diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/Kibbutz.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/Kibbutz.csindex 470cce60c..aa48c1e40 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/Kibbutz.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/Kibbutz.cs@@ -19,13 +19,13 @@ namespace Statecraft.HexTiles.Prototypes/// quarters kit_kibbutz (b09a) x 700 = 4,200. Three barns kit_kibbutz_3 (b24) x 1,400 = 4,200. Water tower/// kit_kibbutz_4 (b28) 1,400. Buildings 15,344. 13 cypress x 1,596 = 20,748. 4 tabor oaks x 648 = 2,592. 3 pond flats/// x 12 = 36. Total about 38,700 (40,800 with quads) of 60,000.</summary>- [HexPrototype("kibbutz")]+ [HexPrototype("kibbutz", Kind = "village")]public sealed class Kibbutz : IHexPrototype{public string Title => "Kibbutz compound and its fields (1940s)";public HexTerrain Terrain => HexTerrain.Flat;public string Ground => "plains";- public int TriangleBudget => 60000;+ public int TriangleBudget => 85000; // the shipped b*-v2 buildings at full detail (Tal, 19 Oct 2026): measured 75k on the israel board and the test hex// Explicit kit ids, not "kit_kibbutz*": the wildcard would mix the dining hall, barn and water tower into the rows.const string Core = "proto:kibbutz-compound-v2", Quarters = "sandbox:kit_kibbutz", DiningHall = "sandbox:kit_kibbutz_2",diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarm.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarm.csnew file mode 100644index 000000000..8a67eeaa9--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarm.cs@@ -0,0 +1,136 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Context tile: a mixed family farm on the plain. A patchwork of painted crop parcels of uneven size (wheat,+ /// green crops, fresh ploughing, a fallow strip) in strips across one grid, a small orchard block on tilled soil, a+ /// hedgerow along the farm track, and a farmhouse with its barn on a yard by the track. Where wheat_fields is one even+ /// grid of large fields, this reads as many small, uneven ones.+ ///+ /// Everything but the trees and the two buildings is painted into the ground. Tall pieces keep out of the unit spot.+ ///+ /// Triangle estimate at the caps, with measured per-model counts: an orchard of at most 9 citrus x ~1,600 = 14,400,+ /// at most 13 hedgerow carobs x ~650 = 8,450, and the two kit_moshava buildings at most 2 x 1,400 = 2,800. Total at+ /// most 25,650 of 30,000. Stand-ins draw fewer.+ ///+ /// The regional variants (MixedFarm<Region><A|B>) subclass it through the protected virtual members: the+ /// grid's turn, the parcel sizes and crops, the orchard, the hedgerow and the farmstead.</summary>+ [HexPrototype("mixed_farm", Kind = "farm")]+ public class MixedFarm : IHexPrototype+ {+ public virtual string Title => "Mixed farm: crop patchwork, orchard and farmstead";+ public virtual HexTerrain Terrain => HexTerrain.Flat;+ public virtual string Ground => "plains";+ public virtual int TriangleBudget => HexScale.BudgetFields + 25000; // its farmstead at full detail: 38k measured++ // Models: the EZ-Tree trees and the Tripo kit are local-only; without them the stand-ins draw.+ protected const string Citrus = "sandbox:citrus_lite", Olive = "sandbox:olive_lite", Carob = "sandbox:carob_lite",+ Oak = "sandbox:tabor_oak_lite", Pine = "sandbox:aleppo_pine_lite", Cypress = "sandbox:cypress_lite",+ Palm = "sandbox:date_palm", Acacia = "sandbox:acacia_lite", House = "sandbox:kit_moshava_2", Barn = "sandbox:kit_moshava_3";+ protected static readonly Color CitrusLeaf = new Color(0.16f, 0.34f, 0.14f), OliveLeaf = new Color(0.38f, 0.44f, 0.28f),+ BroadLeaf = new Color(0.27f, 0.39f, 0.20f), PineGreen = new Color(0.20f, 0.33f, 0.18f), DryLeaf = new Color(0.45f, 0.47f, 0.28f),+ Plaster = new Color(0.88f, 0.80f, 0.68f);++ static readonly string[] BaseCrops = { "wheat", "green_crop", "ploughed", "green_crop", "wheat", "plains" };++ /// <summary>The grid's turn is drawn in YawCentre ± YawSpread degrees.</summary>+ protected virtual float YawCentre => 0f;+ protected virtual float YawSpread => 20f;+ /// <summary>Strip widths across the grid, and parcel lengths along a strip, as share-of-S ranges.</summary>+ protected virtual (float min, float max) StripWidth => (0.16f, 0.30f);+ protected virtual (float min, float max) ParcelLength => (0.18f, 0.42f);+ /// <summary>The crop layers a parcel draws from (repeat a layer to weight it).</summary>+ protected virtual string[] Crops => BaseCrops;+ /// <summary>One parcel in this many is left fallow (Fallow paints it, or the ground shows).</summary>+ protected virtual int FallowOneIn => 8;+ protected virtual void Fallow(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) { }++ /// <summary>The orchard block: its centre on the grid (shares of S), cols x rows trees at Spacing.</summary>+ protected virtual Vector2 OrchardAt => new Vector2(-0.42f, 0.30f);+ protected virtual int OrchardCols => 3;+ protected virtual int OrchardRows => 3;+ protected virtual float OrchardSpacing => 0.11f;+ protected virtual (string model, StandIn standIn, Color tint, float height) OrchardTree => (Citrus, StandIn.Tree, CitrusLeaf, 0.12f);++ /// <summary>The farm track runs along the grid at TrackX (share of S); the hedgerow stands HedgeOffset beside it,+ /// a slot every HedgeStep, one slot in HedgeGapOneIn empty, at most MaxHedge trees (0 for none).</summary>+ protected virtual float TrackX => 0.28f;+ protected virtual string TrackLayer => "dirt";+ protected virtual float HedgeOffset => -0.06f;+ protected virtual float HedgeStep => 0.14f;+ protected virtual int HedgeGapOneIn => 3;+ protected virtual int MaxHedge => 13;+ protected virtual (string model, StandIn standIn, Color tint, float height) HedgeTree(HexTileContext ctx) => (Carob, StandIn.Tree, BroadLeaf, 0.12f);++ /// <summary>The yard's centre on the grid (shares of S), out of the unit spot by the track.</summary>+ protected virtual Vector2 YardAt => new Vector2(0.50f, -0.22f);+ protected virtual string HouseModel => House;+ protected virtual string BarnModel => Barn;++ /// <summary>A point on the farm grid, in shares of S.</summary>+ protected static Vector3 Grid(HexTileContext ctx, float yaw, float x, float z) => ctx.Centre + Quaternion.Euler(0f, yaw, 0f) * new Vector3(x * ctx.S, 0f, z * ctx.S);++ public void Build(HexTileContext ctx)+ {+ float s = ctx.S, yaw = ctx.Range(YawCentre - YawSpread, YawCentre + YawSpread), gap = 0.03f;+ Vector3 G(float x, float z) => Grid(ctx, yaw, x, z);++ // 1. The patchwork: strips across the grid, each cut into parcels of uneven length, one crop each, a few+ // left fallow. Parcels whose centre is far outside the hex are not painted (the paint is clipped anyway).+ var (wMin, wMax) = StripWidth; var (lMin, lMax) = ParcelLength;+ string[] crops = Crops;+ for (float x = -0.95f; x < 0.95f;)+ {+ float w = ctx.Range(wMin, wMax);+ for (float z = -0.95f + ctx.Range(0f, 0.12f); z < 0.95f;)+ {+ float d = ctx.Range(lMin, lMax);+ var at = G(x + w * 0.5f, z + d * 0.5f);+ string crop = crops[ctx.Rng.Next(crops.Length)];+ bool across = ctx.Rng.Next(2) == 0, fallow = ctx.Rng.Next(FallowOneIn) == 0;+ z += d;+ if (!ctx.Inside(at, -0.25f * s)) continue;+ float pw = (w - gap) * s, pd = (d - gap) * s;+ if (fallow) { Fallow(ctx, at, yaw, pw, pd); continue; }+ ctx.PaintGround(crop, at, yaw + (across ? 90f : 0f), across ? pd : pw, across ? pw : pd, 0.1f, 0.95f);+ }+ x += w;+ }++ // 2. The orchard block on tilled soil, trees in straight rows; any in the unit spot are left out.+ int cols = OrchardCols, rows = OrchardRows; float sp = OrchardSpacing; var o = OrchardAt; var tree = OrchardTree;+ float x0 = o.x - (cols - 1) * sp * 0.5f, z0 = o.y - (rows - 1) * sp * 0.5f;+ ctx.PaintGround("ploughed", G(o.x, o.y), yaw, ((cols - 1) * sp + 0.10f) * s, ((rows - 1) * sp + 0.10f) * s, 0.2f, 0.8f);+ for (int i = 0; i < cols; i++)+ for (int j = 0; j < rows; j++)+ {+ var at = G(x0 + i * sp, z0 + j * sp);+ float ty = ctx.Range(0f, 360f), h = tree.height * ctx.Range(0.95f, 1.1f) * s; // drawn even when skipped+ if (ctx.InUnitSpot(at, 0.04f * s)) continue;+ ctx.PlaceByHeight(tree.model, at, ty, h, tree.standIn, tree.tint, 0.6f);+ }++ // 3. The farm track along the grid, and the hedgerow beside it.+ ctx.PaintStroke(TrackLayer, G(TrackX, -0.95f), G(TrackX, 0.95f), 0.035f * s, 0.9f);+ int hedge = 0, maxHedge = MaxHedge;+ for (float z = -0.9f; z <= 0.9f && hedge < maxHedge; z += HedgeStep)+ {+ var at = G(TrackX + HedgeOffset, z);+ if (ctx.Rng.Next(HedgeGapOneIn) == 0 || ctx.InUnitSpot(at, 0.05f * s)) continue;+ var t = HedgeTree(ctx);+ if (ctx.PlaceByHeight(t.model, at, ctx.Range(0f, 360f), t.height * s, t.standIn, t.tint, 0.5f)) hedge++;+ }++ // 4. The farmstead: a painted yard by the track, the farmhouse and the barn at right angles.+ var y = YardAt;+ ctx.PaintGround("dirt", G(y.x, y.y), yaw, 0.30f * s, 0.24f * s, 0.3f, 0.9f);+ ctx.PlaceByWidth(HouseModel, G(y.x - 0.06f, y.y + 0.02f), yaw + 180f, 0.13f * s, StandIn.Box, Plaster);+ ctx.PlaceByWidth(BarnModel, G(y.x + 0.08f, y.y - 0.02f), yaw + 90f, 0.12f * s, StandIn.Box, Plaster);+ Dress(ctx, yaw);+ }++ /// <summary>Anything a variant adds last (palms by the yard, scattered trees): nothing here.</summary>+ protected virtual void Dress(HexTileContext ctx, float yaw) { }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarm.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarm.cs.metanew file mode 100644index 000000000..00cde8269--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarm.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 39e06ff79e03c4079ad39126c54a8f05\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreA.csnew file mode 100644index 000000000..318019154--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreA.cs@@ -0,0 +1,27 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, a: narrow vegetable strips of green crops and ploughing on a grid turned about 20 degrees, a citrus+ /// block of four rows, a cypress windbreak by the sandy track. Caps: 12 citrus x ~1,600 = 19,200 (fewer by the unit+ /// spot), 4 cypresses x ~1,600 = 6,400 and the farmstead at most 2,800 = 28,400 of 30,000.</summary>+ [HexPrototype("mixed_farm_centre_a", Kind = "farm", Region = "centre")]+ public sealed class MixedFarmCentreA : MixedFarm+ {+ public override string Title => "Mixed farm, centre (a): vegetable strips, citrus, cypresses";+ protected override float YawCentre => 20f;+ protected override float YawSpread => 6f;+ protected override (float min, float max) StripWidth => (0.09f, 0.15f);+ protected override (float min, float max) ParcelLength => (0.30f, 0.60f);+ static readonly string[] Mix = { "green_crop", "ploughed", "green_crop", "wheat", "green_crop" };+ protected override string[] Crops => Mix;+ protected override int OrchardRows => 4;+ protected override Vector2 OrchardAt => new Vector2(-0.44f, 0.34f);+ protected override string TrackLayer => "beach";+ protected override int MaxHedge => 4;+ protected override int HedgeGapOneIn => 2;+ static readonly Color CypressDark = new Color(0.12f, 0.26f, 0.13f);+ protected override (string model, StandIn standIn, Color tint, float height) HedgeTree(HexTileContext ctx) => (Cypress, StandIn.Pine, CypressDark, 0.17f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreA.cs.metanew file mode 100644index 000000000..2d15dc8fb--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 97513d03416f3452fa31d5528d8f4e55\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreB.csnew file mode 100644index 000000000..836661ccf--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreB.cs@@ -0,0 +1,33 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, b: broad parcels of wheat and green crops on sand and grass, a grid turned about -45 degrees, a citrus+ /// block and a row of date palms by the farmstead, no hedgerow. Caps: 6 citrus x ~1,600 = 9,600, 5 palms x ~280 =+ /// 1,400 and the farmstead at most 2,800 = 13,800 of 30,000.</summary>+ [HexPrototype("mixed_farm_centre_b", Kind = "farm", Region = "centre")]+ public sealed class MixedFarmCentreB : MixedFarm+ {+ public override string Title => "Mixed farm, centre (b): broad parcels, palms by the yard";+ protected override float YawCentre => -45f;+ protected override float YawSpread => 6f;+ protected override (float min, float max) StripWidth => (0.28f, 0.42f);+ protected override (float min, float max) ParcelLength => (0.22f, 0.40f);+ static readonly string[] Mix = { "wheat", "green_crop", "wheat", "ploughed", "beach" };+ protected override string[] Crops => Mix;+ protected override int OrchardRows => 2;+ protected override Vector2 OrchardAt => new Vector2(-0.30f, -0.48f);+ protected override int MaxHedge => 0;+ protected override void Dress(HexTileContext ctx, float yaw)+ {+ var y = YardAt;+ for (int k = 0; k < 5; k++)+ {+ var at = Grid(ctx, yaw, y.x - 0.16f + 0.08f * k, y.y + 0.17f);+ float ty = ctx.Range(0f, 360f), h = ctx.Range(0.14f, 0.17f) * ctx.S;+ if (!ctx.InUnitSpot(at, 0.04f * ctx.S)) ctx.PlaceByHeight(Palm, at, ty, h, StandIn.Palm, null, 0.3f);+ }+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreB.cs.metanew file mode 100644index 000000000..d2aa74d3e--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmCentreB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: a689d576ca84d48d5ac6cd36a483c4e2\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthA.csnew file mode 100644index 000000000..acf1a6bb0--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthA.cs@@ -0,0 +1,23 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, a: small parcels mostly in green crops on a grid turned about 30 degrees, an olive block, and an oak+ /// hedgerow along the track. Caps: 6 olives x ~1,600 = 9,600, 13 oaks x ~650 = 8,450 and the farmstead at most+ /// 2,800 = 20,850 of 30,000.</summary>+ [HexPrototype("mixed_farm_north_a", Kind = "farm", Region = "north")]+ public sealed class MixedFarmNorthA : MixedFarm+ {+ public override string Title => "Mixed farm, north (a): small green parcels, oak hedge";+ protected override float YawCentre => 30f;+ protected override float YawSpread => 8f;+ protected override (float min, float max) StripWidth => (0.12f, 0.22f);+ protected override (float min, float max) ParcelLength => (0.14f, 0.30f);+ static readonly string[] Mix = { "green_crop", "green_crop", "green_crop", "wheat", "ploughed", "grass" };+ protected override string[] Crops => Mix;+ protected override int OrchardRows => 2;+ protected override (string model, StandIn standIn, Color tint, float height) OrchardTree => (Olive, StandIn.Tree, OliveLeaf, 0.12f);+ protected override (string model, StandIn standIn, Color tint, float height) HedgeTree(HexTileContext ctx) => (Oak, StandIn.Tree, BroadLeaf, 0.13f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthA.cs.metanew file mode 100644index 000000000..37e6c0ca6--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 91e94dd95f35b47ed8c8dd54810ff02d\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthB.csnew file mode 100644index 000000000..541abd481--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthB.cs@@ -0,0 +1,26 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, b: larger parcels of green crops and wheat on a grid turned about -40 degrees, a long citrus block, and a+ /// sparse line of Aleppo pines by the track. Caps: 8 citrus x ~1,600 = 12,800, 7 pines x ~1,600 = 11,200 and the+ /// farmstead at most 2,800 = 26,800 of 30,000.</summary>+ [HexPrototype("mixed_farm_north_b", Kind = "farm", Region = "north")]+ public sealed class MixedFarmNorthB : MixedFarm+ {+ public override string Title => "Mixed farm, north (b): large parcels, pine line";+ protected override float YawCentre => -40f;+ protected override float YawSpread => 8f;+ protected override (float min, float max) StripWidth => (0.24f, 0.38f);+ protected override (float min, float max) ParcelLength => (0.26f, 0.50f);+ static readonly string[] Mix = { "green_crop", "wheat", "green_crop", "ploughed", "green_crop" };+ protected override string[] Crops => Mix;+ protected override Vector2 OrchardAt => new Vector2(-0.40f, -0.40f);+ protected override int OrchardCols => 4;+ protected override int OrchardRows => 2;+ protected override int MaxHedge => 7;+ protected override int HedgeGapOneIn => 2;+ protected override (string model, StandIn standIn, Color tint, float height) HedgeTree(HexTileContext ctx) => (Pine, StandIn.Pine, PineGreen, 0.16f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthB.cs.metanew file mode 100644index 000000000..5ea93d030--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmNorthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f25677c64ce194dbea6897741b93bf83\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthA.csnew file mode 100644index 000000000..5a13b647b--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthA.cs@@ -0,0 +1,26 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, a: broad parcels of wheat and fresh ploughing with fallow sand between, a grid turned about 15 degrees, a+ /// block of date palms, and no hedgerow. Caps: 9 palms x ~280 = 2,520 and the farmstead at most 2,800 = 5,320 of+ /// 30,000.</summary>+ [HexPrototype("mixed_farm_south_a", Kind = "farm", Region = "south")]+ public sealed class MixedFarmSouthA : MixedFarm+ {+ public override string Title => "Mixed farm, south (a): dry parcels, date-palm block";+ protected override float YawCentre => 15f;+ protected override float YawSpread => 10f;+ protected override (float min, float max) StripWidth => (0.30f, 0.45f);+ protected override (float min, float max) ParcelLength => (0.30f, 0.50f);+ static readonly string[] Mix = { "wheat", "ploughed", "wheat", "ploughed", "plains" };+ protected override string[] Crops => Mix;+ protected override int FallowOneIn => 3;+ protected override void Fallow(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) =>+ ctx.PaintGround("desert", at, yaw, width, depth, 0.2f, 0.85f);+ protected override float OrchardSpacing => 0.12f;+ protected override (string model, StandIn standIn, Color tint, float height) OrchardTree => (Palm, StandIn.Palm, Color.white, 0.15f);+ protected override int MaxHedge => 0;+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthA.cs.metanew file mode 100644index 000000000..c508c0441--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 2946e1378a5274781be27ae5364940d5\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthB.csnew file mode 100644index 000000000..45c365a36--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthB.cs@@ -0,0 +1,29 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, b: long narrow ploughed and wheat strips on a grid turned about -25 degrees, a small olive block, sand+ /// along the strip ends, and a few acacias by the track. Caps: 4 olives x ~1,600 = 6,400, 5 acacias x ~1,160 =+ /// 5,800 and the farmstead at most 2,800 = 15,000 of 30,000.</summary>+ [HexPrototype("mixed_farm_south_b", Kind = "farm", Region = "south")]+ public sealed class MixedFarmSouthB : MixedFarm+ {+ public override string Title => "Mixed farm, south (b): long dry strips, acacias";+ protected override float YawCentre => -25f;+ protected override float YawSpread => 10f;+ protected override (float min, float max) StripWidth => (0.13f, 0.20f);+ protected override (float min, float max) ParcelLength => (0.50f, 0.80f);+ static readonly string[] Mix = { "ploughed", "wheat", "ploughed", "ploughed", "wheat" };+ protected override string[] Crops => Mix;+ protected override int FallowOneIn => 4;+ protected override void Fallow(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) =>+ ctx.PaintGround("desert", at, yaw, width, depth, 0.2f, 0.85f);+ protected override int OrchardCols => 2;+ protected override int OrchardRows => 2;+ protected override (string model, StandIn standIn, Color tint, float height) OrchardTree => (Olive, StandIn.Tree, OliveLeaf, 0.12f);+ protected override int MaxHedge => 5;+ protected override int HedgeGapOneIn => 2;+ protected override (string model, StandIn standIn, Color tint, float height) HedgeTree(HexTileContext ctx) => (Acacia, StandIn.Tree, DryLeaf, 0.13f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthB.cs.metanew file mode 100644index 000000000..59b6ec0ef--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MixedFarmSouthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 1cd8be620631c47bb9d32a43ef9622f0\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MoshavaVillage.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MoshavaVillage.csindex f2546dc80..7f8365b07 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MoshavaVillage.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MoshavaVillage.cs@@ -17,13 +17,13 @@ namespace Statecraft.HexTiles.Prototypes////// The water tower is the kibbutz tile's b28 tower (sandbox:kit_kibbutz_4); where it is missing, the Palm stand-in/// draws instead, its silhouette (a thin shaft under a wide crown) the nearest to a tank on a column.</summary>- [HexPrototype("moshava_village")]+ [HexPrototype("moshava_village", Kind = "town")]public sealed class MoshavaVillage : IHexPrototype{public string Title => "Moshava farming colony (1948)";public HexTerrain Terrain => HexTerrain.Flat;public string Ground => "plains";- public int TriangleBudget => 60000;+ public int TriangleBudget => 120000; // the shipped b*-v2 buildings at full detail (Tal, 19 Oct 2026): measured 106k on the israel board and the test hex// Explicit kit ids, not "kit_moshava*": the wildcard would also pick kit_moshava_3, which is the barn.const string Farmhouse = "sandbox:kit_moshava", TwoStorey = "sandbox:kit_moshava_2", Barn = "sandbox:kit_moshava_3",diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MountainPeaks.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MountainPeaks.csindex c5d11fd6c..45c246e3a 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/MountainPeaks.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/MountainPeaks.cs@@ -3,7 +3,7 @@namespace Statecraft.HexTiles.Prototypes{/// <summary>Built-in context tile for a mountain hex: two to four great rock masses (Poly Haven scans, stand-in rocks).</summary>- [HexPrototype("mountain_peaks")]+ [HexPrototype("mountain_peaks", Kind = "nature")]public sealed class MountainPeaks : IHexPrototype{public string Title => "Mountain peaks";diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerraces.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerraces.csindex 943460b31..7f332bfb3 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerraces.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerraces.cs@@ -15,29 +15,61 @@ namespace Statecraft.HexTiles.Prototypes////// Triangle estimate at the maximum counts (capped by counters; FlatSurface refuses nothing), with measured per-model/// counts: at most 22 olives x 1,602 = 35,244, at most 4 carobs x 648 = 2,592, at most 12 limestone x 700 = 8,400, and- /// the hut kit_stone_village_2 x 700. Total at most 46,936 of 50,000.</summary>- [HexPrototype("olive_terraces")]- public sealed class OliveTerraces : IHexPrototype+ /// the hut kit_stone_village_2 x 700. Total at most 46,936 of 50,000.+ ///+ /// The regional variants (OliveTerraces<Region><A|B>) subclass it through the protected virtual members: the+ /// bands and risers, their layers, the trees per ring, the species and the caps. Their defaults are this tile's own,+ /// so olive_terraces itself builds exactly as before (HexVariantTests).</summary>+ [HexPrototype("olive_terraces", Kind = "farm")]+ public class OliveTerraces : IHexPrototype{- public string Title => "Olive terraces on a hillside (1948)";- public HexTerrain Terrain => HexTerrain.Hills;- public string Ground => "hills";- public int TriangleBudget => 50000;+ public virtual string Title => "Olive terraces on a hillside (1948)";+ public virtual HexTerrain Terrain => HexTerrain.Hills;+ public virtual string Ground => "hills";+ public virtual int TriangleBudget => 60000; // its farmhouse at full detail: 51k measured// The hut is explicit, not "kit_stone_village*": the wildcard would also pick b17, the village mosque.- const string Olive = "sandbox:olive_lite", Carob = "sandbox:carob_lite", Stone = "sandbox:limestone*",+ protected const string Olive = "sandbox:olive_lite", Carob = "sandbox:carob_lite", Stone = "sandbox:limestone*",Hut = "sandbox:kit_stone_village_2";- const int MaxOlives = 22, MaxCarobs = 4, StoneRuns = 4, StonesPerRun = 3, Segments = 24;+ const int Segments = 24;- static readonly Color OliveLeaf = new Color(0.38f, 0.44f, 0.28f), CarobLeaf = new Color(0.18f, 0.32f, 0.15f),+ protected static readonly Color OliveLeaf = new Color(0.38f, 0.44f, 0.28f), CarobLeaf = new Color(0.18f, 0.32f, 0.15f),Limestone = new Color(0.80f, 0.76f, 0.66f), HutStone = new Color(0.76f, 0.70f, 0.58f);- static readonly float[] Bands = { 0.42f, 0.60f, 0.78f }; // terrace soil (tree rows on the inner two, corners on the outer)- static readonly float[] Risers = { 0.33f, 0.51f, 0.69f, 0.87f }; // dry-stone walls, downhill of each band+ static readonly float[] BaseBands = { 0.42f, 0.60f, 0.78f }; // terrace soil (tree rows on the inner two, corners on the outer)+ static readonly float[] BaseRisers = { 0.33f, 0.51f, 0.69f, 0.87f }; // dry-stone walls, downhill of each band++ /// <summary>Terrace bands and the dry-stone risers downhill of them, as shares of S from the centre. The tree rows+ /// stand on Bands[0], Bands[1] and Bands[2]; the stone runs on Risers[1] and Risers[2].</summary>+ protected virtual float[] Bands => BaseBands;+ protected virtual float[] Risers => BaseRisers;+ protected virtual string BandLayer => "ploughed";+ protected virtual float BandWidth => 0.12f;+ protected virtual string RiserLayer => "mountain";+ /// <summary>Trees on the middle band, the upper band and the outer band's corners.</summary>+ protected virtual int MiddleRow => 13;+ protected virtual int UpperRow => 9;+ protected virtual int OuterCorners => 6;+ protected virtual int MaxOlives => 22;+ protected virtual int MaxCarobs => 4;+ protected virtual int StoneRuns => 4;+ /// <summary>A tree slot rolls 0 to 9: below GapRolls it stays empty, the next CarobRolls take the second tree.</summary>+ protected virtual int GapRolls => 1;+ protected virtual int CarobRolls => 1;+ /// <summary>The main row tree (an olive) and the second tree (a carob), with their height ranges in shares of S.</summary>+ protected virtual (string model, StandIn standIn, Color tint, float min, float max) RowTree => (Olive, StandIn.Tree, OliveLeaf, 0.12f, 0.13f);+ protected virtual (string model, StandIn standIn, Color tint, float min, float max) SecondTree => (Carob, StandIn.Tree, CarobLeaf, 0.14f, 0.16f);+ /// <summary>Whether the field hut stands on the middle terrace.</summary>+ protected virtual bool HasHut => true;++ const int StonesPerRun = 3;public void Build(HexTileContext ctx){float s = ctx.S;+ float[] bands = Bands, risers = Risers;+ int maxOlives = MaxOlives, maxCarobs = MaxCarobs, gapRolls = GapRolls, carobRolls = CarobRolls;+ var rowTree = RowTree; var second = SecondTree;// One contour shape for every ring: two low harmonics, so the terraces swell and pinch together.float phase1 = ctx.Range(0f, 360f), phase2 = ctx.Range(0f, 360f);float Wobble(float b) => 1f + 0.05f * Mathf.Sin((b + phase1) * Mathf.Deg2Rad) + 0.03f * Mathf.Sin((2f * b + phase2) * Mathf.Deg2Rad);@@ -45,40 +77,43 @@ namespace Statecraft.HexTiles.Prototypesfloat trackB = ctx.Range(160f, 200f); // the track up from the southfloat hutB = trackB + (ctx.Rng.Next(2) == 0 ? -1f : 1f) * ctx.Range(70f, 110f); // the hut, off the track- var hut = On(Bands[1], hutB);+ var hut = On(bands[1], hutB);// 1. Ground: the terrace bands, then the risers, then the track, the hut's path and its yard.- foreach (float r in Bands) Ring("ploughed", r, 0.12f, 0.85f);- foreach (float r in Risers) Ring("mountain", r, 0.022f, 0.8f);+ foreach (float r in bands) Ring(BandLayer, r, BandWidth, 0.85f);+ foreach (float r in risers) Ring(RiserLayer, r, 0.022f, 0.8f);ctx.PaintStroke("dirt", ctx.At(trackB, 0.97f), ctx.Centre, 0.03f * s, 0.9f);- ctx.PaintStroke("dirt", hut, ctx.At(hutB, 0.97f), 0.02f * s, 0.85f);- ctx.PaintGround("dirt", hut, hutB, 0.15f * s, 0.15f * s, 0.3f, 0.8f);+ if (HasHut)+ {+ ctx.PaintStroke("dirt", hut, ctx.At(hutB, 0.97f), 0.02f * s, 0.85f);+ ctx.PaintGround("dirt", hut, hutB, 0.15f * s, 0.15f * s, 0.3f, 0.8f);- // 2. The field hut, its front down the slope.- if (!ctx.InUnitSpot(hut, 0.07f * s)) ctx.PlaceByWidth(Hut, hut, hutB, 0.10f * s, StandIn.Box, HutStone);+ // 2. The field hut, its front down the slope.+ if (!ctx.InUnitSpot(hut, 0.07f * s)) ctx.PlaceByWidth(Hut, hut, hutB, 0.10f * s, StandIn.Box, HutStone);+ }// 3. Trees in rows along the bands: the middle terrace first (the most seen), then the upper, then one at each// corner of the outer terrace, where the hexagon has room. Gaps where the track and the hut's path cross.- int olives = 0, carobs = 0;- float o1 = ctx.Range(0f, 360f / 13f), o0 = ctx.Range(0f, 40f);- for (int k = 0; k < 13; k++)+ int olives = 0, carobs = 0, middle = MiddleRow, upper = UpperRow, corners = OuterCorners;+ float o1 = ctx.Range(0f, 360f / middle), o0 = ctx.Range(0f, 360f / upper);+ for (int k = 0; k < middle; k++){- float b = o1 + k * 360f / 13f;- if (Mathf.Abs(Mathf.DeltaAngle(b, hutB)) < 16f) continue;- Tree(Bands[1], b);+ float b = o1 + k * 360f / middle;+ if (HasHut && Mathf.Abs(Mathf.DeltaAngle(b, hutB)) < 16f) continue;+ Tree(bands[1], b);}- for (int k = 0; k < 9; k++) Tree(Bands[0], o0 + k * 40f);- for (int k = 0; k < 6; k++)+ for (int k = 0; k < upper; k++) Tree(bands[0], o0 + k * (360f / upper));+ for (int k = 0; k < corners; k++){- float b = k * 60f + ctx.Range(-5f, 5f);- if (Mathf.Abs(Mathf.DeltaAngle(b, hutB)) < 10f) continue;- Tree(Bands[2], b);+ float b = k * (360f / corners) + ctx.Range(-5f, 5f);+ if (HasHut && Mathf.Abs(Mathf.DeltaAngle(b, hutB)) < 10f) continue;+ Tree(bands[2], b);}// 4. Short runs of limestone where the risers show between the rows.for (int run = 0; run < StoneRuns; run++){- float r = Risers[1 + ctx.Rng.Next(2)], b0 = ctx.Range(0f, 360f);+ float r = risers[1 + ctx.Rng.Next(2)], b0 = ctx.Range(0f, 360f);if (Mathf.Abs(Mathf.DeltaAngle(b0, trackB)) < 12f) continue;for (int i = 0; i < StonesPerRun; i++){@@ -87,6 +122,7 @@ namespace Statecraft.HexTiles.Prototypesctx.PlaceByWidth(Stone, p, ctx.Range(0f, 360f), ctx.Range(0.035f, 0.05f) * s, StandIn.Rock, Limestone);}}+ Dress(ctx);// A closed contour ring of one ground layer, as a polyline with a little irregularity at each vertex.void Ring(string layer, float r, float widthShare, float strength)@@ -96,22 +132,25 @@ namespace Statecraft.HexTiles.Prototypesfor (int k = 0; k < Segments; k++) ctx.PaintStroke(layer, pts[k], pts[(k + 1) % Segments], widthShare * s, strength);}- // One tree slot on a band: now and then a gap or a carob, otherwise an olive, up to the caps.+ // One tree slot on a band: now and then a gap or the second tree, otherwise the row tree, up to the caps.void Tree(float r, float b){if (Mathf.Abs(Mathf.DeltaAngle(b, trackB)) < 10f) return;var p = On(r, b);if (ctx.InUnitSpot(p, 0.07f * s)) return;int roll = ctx.Rng.Next(10);- if (roll == 0) return;- if (roll == 1 && carobs < MaxCarobs)+ if (roll < gapRolls) return;+ if (roll < gapRolls + carobRolls && carobs < maxCarobs){- if (ctx.PlaceByHeight(Carob, p, ctx.Range(0f, 360f), ctx.Range(0.14f, 0.16f) * s, StandIn.Tree, CarobLeaf, 0.5f)) carobs++;+ if (ctx.PlaceByHeight(second.model, p, ctx.Range(0f, 360f), ctx.Range(second.min, second.max) * s, second.standIn, second.tint, 0.5f)) carobs++;return;}- if (olives >= MaxOlives) return;- if (ctx.PlaceByHeight(Olive, p, ctx.Range(0f, 360f), ctx.Range(0.12f, 0.13f) * s, StandIn.Tree, OliveLeaf, 0.5f)) olives++;+ if (olives >= maxOlives) return;+ if (ctx.PlaceByHeight(rowTree.model, p, ctx.Range(0f, 360f), ctx.Range(rowTree.min, rowTree.max) * s, rowTree.standIn, rowTree.tint, 0.5f)) olives++;}}++ /// <summary>Anything a variant adds last: nothing here.</summary>+ protected virtual void Dress(HexTileContext ctx) { }}}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreA.csnew file mode 100644index 000000000..ff875ca43--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreA.cs@@ -0,0 +1,20 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, a: thin pale terraces of bare earth on the Shephelah slopes, olives spaced wider along them, carobs+ /// more common. Caps: at most 22 olives x ~1,600 = 35,200, 6 carobs x ~650 = 3,900, 12 limestone x ~700 = 8,400 and+ /// the hut ~700 = 48,200 of 50,000.</summary>+ [HexPrototype("olive_terraces_centre_a", Kind = "farm", Region = "centre")]+ public sealed class OliveTerracesCentreA : OliveTerraces+ {+ public override string Title => "Olive terraces, centre (a): thin pale terraces, carobs";+ protected override string BandLayer => "dirt";+ protected override float BandWidth => 0.08f;+ protected override int MiddleRow => 11;+ protected override int UpperRow => 7;+ protected override int MaxCarobs => 6;+ protected override int CarobRolls => 3;+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreA.cs.metanew file mode 100644index 000000000..de1575916--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 697d3cbbb7c984e669458df76c457e0b\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreB.csnew file mode 100644index 000000000..6a99c7ff5--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreB.cs@@ -0,0 +1,25 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, b: three broad ploughed terraces with no field hut, the olives close together in full rows. Caps: at+ /// most 26 olives x ~1,600 = 41,600, 4 carobs x ~650 = 2,600 and 12 limestone x ~700 = 8,400 = 52,600; budget+ /// 60,000.</summary>+ [HexPrototype("olive_terraces_centre_b", Kind = "farm", Region = "centre")]+ public sealed class OliveTerracesCentreB : OliveTerraces+ {+ public override string Title => "Olive terraces, centre (b): broad terraces, full rows";+ public override int TriangleBudget => 60000;+ static readonly float[] Broad = { 0.45f, 0.65f, 0.83f };+ static readonly float[] BroadRisers = { 0.34f, 0.55f, 0.75f, 0.92f };+ protected override float[] Bands => Broad;+ protected override float[] Risers => BroadRisers;+ protected override float BandWidth => 0.16f;+ protected override bool HasHut => false;+ protected override int MiddleRow => 18;+ protected override int UpperRow => 12;+ protected override int MaxOlives => 26;+ protected override int GapRolls => 0;+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreB.cs.metanew file mode 100644index 000000000..6645d0eec--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesCentreB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: edb1bed69f31c4461adfa4aa5a1be0c2\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthA.csnew file mode 100644index 000000000..a9885f8e1--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthA.cs@@ -0,0 +1,21 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, a: terraces sown in green crops between the olive rows, more trees to a ring, and Tabor oaks among the+ /// olives. Caps: at most 22 olives x ~1,600 = 35,200, 6 oaks x ~650 = 3,900, 12 limestone x ~700 = 8,400 and the+ /// hut ~700 = 48,200 of 50,000.</summary>+ [HexPrototype("olive_terraces_north_a", Kind = "farm", Region = "north")]+ public sealed class OliveTerracesNorthA : OliveTerraces+ {+ public override string Title => "Olive terraces, north (a): green terraces, oaks";+ protected override string BandLayer => "green_crop";+ protected override int MiddleRow => 15;+ protected override int UpperRow => 10;+ protected override int MaxCarobs => 6;+ protected override int CarobRolls => 2;+ static readonly Color OakLeaf = new Color(0.30f, 0.42f, 0.20f);+ protected override (string model, StandIn standIn, Color tint, float min, float max) SecondTree => ("sandbox:tabor_oak_lite", StandIn.Tree, OakLeaf, 0.14f, 0.17f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthA.cs.metanew file mode 100644index 000000000..0d5c7039f--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 24b97a3c6fe3e44f7b5ab0e7350ca381\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthB.csnew file mode 100644index 000000000..4d063a07d--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthB.cs@@ -0,0 +1,27 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, b: four narrower ploughed terraces, the trees in denser rows, with Aleppo pines among the olives. Caps:+ /// at most 24 olives x ~1,600 = 38,400, 4 pines x ~1,600 = 6,400, 12 limestone x ~700 = 8,400 and the hut ~700 =+ /// 53,900; budget 70,000 (the farmhouse is drawn at full detail).</summary>+ [HexPrototype("olive_terraces_north_b", Kind = "farm", Region = "north")]+ public sealed class OliveTerracesNorthB : OliveTerraces+ {+ public override string Title => "Olive terraces, north (b): narrow terraces, pines";+ public override int TriangleBudget => 70000; // 59k measured with the farmhouse at full detail+ static readonly float[] Narrow = { 0.40f, 0.54f, 0.68f, 0.82f };+ static readonly float[] NarrowRisers = { 0.33f, 0.47f, 0.61f, 0.75f, 0.89f };+ protected override float[] Bands => Narrow;+ protected override float[] Risers => NarrowRisers;+ protected override float BandWidth => 0.085f;+ protected override string BandLayer => "ploughed";+ protected override int MiddleRow => 16;+ protected override int UpperRow => 11;+ protected override int OuterCorners => 12;+ protected override int MaxOlives => 24;+ static readonly Color PineGreen = new Color(0.20f, 0.33f, 0.18f);+ protected override (string model, StandIn standIn, Color tint, float min, float max) SecondTree => ("sandbox:aleppo_pine_lite", StandIn.Pine, PineGreen, 0.16f, 0.19f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthB.cs.metanew file mode 100644index 000000000..c18a3f219--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesNorthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: d5ecddd2b230249eb9439463bf2f5d47\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthA.csnew file mode 100644index 000000000..cfe17bb92--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthA.cs@@ -0,0 +1,21 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, a: dry terraces with sandy risers, few olives with wide gaps, and acacias among them. Caps: at most 14+ /// olives x ~1,600 = 22,400, 4 acacias x ~1,160 = 4,640, 12 limestone x ~700 = 8,400 and the hut ~700 = 36,140 of+ /// 50,000.</summary>+ [HexPrototype("olive_terraces_south_a", Kind = "farm", Region = "south")]+ public sealed class OliveTerracesSouthA : OliveTerraces+ {+ public override string Title => "Olive terraces, south (a): dry terraces, acacias";+ protected override string RiserLayer => "desert";+ protected override int MiddleRow => 10;+ protected override int UpperRow => 7;+ protected override int MaxOlives => 14;+ protected override int GapRolls => 3;+ static readonly Color AcaciaLeaf = new Color(0.45f, 0.47f, 0.28f);+ protected override (string model, StandIn standIn, Color tint, float min, float max) SecondTree => ("sandbox:acacia_lite", StandIn.Tree, AcaciaLeaf, 0.12f, 0.14f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthA.cs.metanew file mode 100644index 000000000..4e847a00b--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 7fe89d1c418824a398d12e72b81875ca\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthB.csnew file mode 100644index 000000000..48d1f808d--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthB.cs@@ -0,0 +1,20 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, b: terraces sown in wheat, a thin row of olives on the middle terrace only and bare corners. Caps: at+ /// most 12 olives x ~1,600 = 19,200, 4 carobs x ~650 = 2,600, 12 limestone x ~700 = 8,400 and the hut ~700 = 30,900+ /// of 50,000.</summary>+ [HexPrototype("olive_terraces_south_b", Kind = "farm", Region = "south")]+ public sealed class OliveTerracesSouthB : OliveTerraces+ {+ public override string Title => "Olive terraces, south (b): wheat terraces, few olives";+ protected override string BandLayer => "wheat";+ protected override int MiddleRow => 9;+ protected override int UpperRow => 5;+ protected override int OuterCorners => 0;+ protected override int MaxOlives => 12;+ protected override int GapRolls => 2;+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthB.cs.metanew file mode 100644index 000000000..25dc6270d--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/OliveTerracesSouthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: d7bd76e701f3044de91c2a36a6a702fd\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/PineForest.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/PineForest.csindex f3e867cf8..927118595 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/PineForest.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/PineForest.cs@@ -11,58 +11,99 @@ namespace Statecraft.HexTiles.Prototypes/// east (Tel Aviv side to the hills). The clearings and the track are painted into the ground (no flats), and tall/// pieces keep out of the unit spot (ctx.InUnitSpot)./// Triangle budget by arithmetic (caps below): 27 pines x ~1600 + 9 broadleaf x ~650 + 3 rocks x ~700 = 51,150, and- /// no flats; about 51k of 60k.</summary>- [HexPrototype("pine_forest")]- public sealed class PineForest : IHexPrototype+ /// no flats; about 51k of 60k.+ ///+ /// The regional forest variants (Forest<Region><A|B>) subclass it through the protected virtual members: the+ /// stand's tree, the fill and margin trees, the caps, the row grid, the track and the clearings' ground. Their defaults+ /// are this tile's own, so pine_forest itself builds exactly as before (HexVariantTests).</summary>+ [HexPrototype("pine_forest", Kind = "forest")]+ public class PineForest : IHexPrototype{- public string Title => "JNF pine forest, foothills east of Tel Aviv (1948)";- public HexTerrain Terrain => HexTerrain.Hills;- public string Ground => "hills";- public int TriangleBudget => HexScale.BudgetForest;+ public virtual string Title => "JNF pine forest, foothills east of Tel Aviv (1948)";+ public virtual HexTerrain Terrain => HexTerrain.Hills;+ public virtual string Ground => "hills";+ public virtual int TriangleBudget => HexScale.BudgetForest;// Models: EZ-Tree trees and Poly Haven rocks are local-only for now; the stand-ins draw without them.- const string Pine = "sandbox:aleppo_pine_lite", Oak = "sandbox:tabor_oak_lite", Carob = "sandbox:carob_lite", Rock = "sandbox:limestone*";- // Caps that keep the tile inside its budget whatever the models' exact counts.- const int MaxPines = 22, MaxBroadleaf = 9, MaxFill = 26;+ protected const string Pine = "sandbox:aleppo_pine_lite", Oak = "sandbox:tabor_oak_lite", Carob = "sandbox:carob_lite", Rock = "sandbox:limestone*";- static readonly Color PineGreen = new Color(0.20f, 0.33f, 0.18f), OakGreen = new Color(0.36f, 0.44f, 0.23f),+ protected static readonly Color PineGreen = new Color(0.20f, 0.33f, 0.18f), OakGreen = new Color(0.36f, 0.44f, 0.23f),CarobGreen = new Color(0.27f, 0.39f, 0.20f), Limestone = new Color(0.86f, 0.83f, 0.74f);+ /// <summary>One tree to place: model, stand-in, tint, height range (shares of S) and footprint share.</summary>+ protected readonly struct Tree+ {+ public readonly string Model; public readonly StandIn StandIn; public readonly Color Tint; public readonly float Min, Max, Footprint;+ public Tree(string model, StandIn standIn, Color tint, float min, float max, float footprint)+ { Model = model; StandIn = standIn; Tint = tint; Min = min; Max = max; Footprint = footprint; }+ }++ // Caps that keep the tile inside its budget whatever the models' exact counts.+ protected virtual int MaxPines => 22;+ protected virtual int MaxBroadleaf => 9;+ protected virtual int MaxFill => 26;+ /// <summary>The planted stand's tree (the first MaxPines cells, in a seeded order).</summary>+ protected virtual Tree StandTree(HexTileContext ctx) => new Tree(Pine, StandIn.Pine, PineGreen, 0.16f, 0.20f, 0.3f);+ /// <summary>The rest of the stand closes into canopy with round-crowned native trees (light: ~650 triangles each).</summary>+ protected virtual Tree FillTree(HexTileContext ctx) => new Tree(ctx.Rng.Next(3) == 0 ? Carob : Oak, StandIn.Tree, OakGreen, 0.13f, 0.16f, 0.45f);+ /// <summary>A margin tree: Tabor oak about two in three, carob the rest.</summary>+ protected virtual Tree MarginTree(HexTileContext ctx)+ {+ bool oak = ctx.Rng.Next(3) != 0;+ return new Tree(oak ? Oak : Carob, StandIn.Tree, oak ? OakGreen : CarobGreen, 0.14f, 0.17f, 0.45f);+ }+ /// <summary>The track's bearing, drawn in TrackBearing ± 15 degrees.</summary>+ protected virtual float TrackBearing => 80f;+ protected virtual string TrackLayer => "dirt";+ /// <summary>The clearings' painted ground, and their radii as shares of S.</summary>+ protected virtual string ClearingLayer => "plains";+ protected virtual (float big, float small) ClearingRadii => (0.16f, 0.12f);+ /// <summary>The rows' turn, drawn in this range, and the gaps between rows and between trees, as shares of S.</summary>+ protected virtual (float min, float max) RowYaw => (15f, 40f);+ protected virtual float RowGap => 0.17f;+ protected virtual float TreeGap => 0.16f;+ /// <summary>Position jitter of a stand cell, as a share of S.</summary>+ protected virtual float Jitter => 0.03f;+ /// <summary>Whether the clearings carry limestone outcrops.</summary>+ protected virtual string? OutcropModel => Rock;+public void Build(HexTileContext ctx){float s = ctx.S;// 1. The track: a sine-wiggled line across the hex, roughly west (Tel Aviv) to east, painted as dirt strokes.- float trackBearing = 80f + ctx.Range(-15f, 15f), amp = ctx.Range(0.10f, 0.15f) * s, phase = ctx.Range(0f, 6.283f);+ float trackBearing = TrackBearing + ctx.Range(-15f, 15f), amp = ctx.Range(0.10f, 0.15f) * s, phase = ctx.Range(0f, 6.283f);var along = new Vector3(Mathf.Sin(trackBearing * Mathf.Deg2Rad), 0f, Mathf.Cos(trackBearing * Mathf.Deg2Rad));var side = new Vector3(along.z, 0f, -along.x);Vector3 TrackAt(float t) => ctx.Centre + along * (t * s) + side * (amp * Mathf.Sin(2.6f * t + phase));var track = new List<Vector3>();for (int k = 0; k <= 16; k++) track.Add(TrackAt(-0.95f + k * (1.9f / 16f)));- for (int k = 0; k < track.Count - 1; k++) ctx.PaintStroke("dirt", track[k], track[k + 1], 0.035f * s, 0.85f);+ for (int k = 0; k < track.Count - 1; k++) ctx.PaintStroke(TrackLayer, track[k], track[k + 1], 0.035f * s, 0.85f);// 2. Two clearings, one each side of the track, pulled inwards until they sit in the hex, painted as dry grass.+ var (bigR, smallR) = ClearingRadii;var clearings = new[]{- (centre: TrackAt(ctx.Range(-0.40f, -0.15f)) + side * (0.22f * s), radius: 0.16f * s),- (centre: TrackAt(ctx.Range(0.20f, 0.42f)) - side * (0.20f * s), radius: 0.12f * s),+ (centre: TrackAt(ctx.Range(-0.40f, -0.15f)) + side * (0.22f * s), radius: bigR * s),+ (centre: TrackAt(ctx.Range(0.20f, 0.42f)) - side * (0.20f * s), radius: smallR * s),};for (int c = 0; c < clearings.Length; c++){var at = clearings[c].centre;for (int i = 0; i < 6 && !ctx.Inside(at, clearings[c].radius * 0.6f); i++) at = Vector3.Lerp(at, ctx.Centre, 0.3f);clearings[c].centre = at;- ctx.PaintGround("plains", at, ctx.Range(0f, 90f), 1.3f * clearings[c].radius, 1.3f * clearings[c].radius, 0.4f, 0.8f);+ ctx.PaintGround(ClearingLayer, at, ctx.Range(0f, 90f), 1.3f * clearings[c].radius, 1.3f * clearings[c].radius, 0.4f, 0.8f);}- // 3. Limestone outcrops in the clearings: two in the larger, one in the smaller (none in the unit spot).+ // 3. Outcrops in the clearings: two in the larger, one in the smaller (none in the unit spot).+ string? outcrop = OutcropModel;for (int c = 0; c < clearings.Length; c++)for (int k = 0; k < 2 - c; k++){var at = clearings[c].centre + Quaternion.Euler(0f, ctx.Range(0f, 360f), 0f) * new Vector3(0f, 0f, ctx.Range(0.2f, 0.5f) * clearings[c].radius);float yaw = ctx.Range(0f, 360f), width = ctx.Range(0.06f, 0.09f) * s; // drawn even when skipped, so the sequence holds- if (ctx.InUnitSpot(at, 0.04f * s)) continue;- ctx.PlaceByWidth(Rock, at, yaw, width, StandIn.Rock, Limestone, 40f);+ if (outcrop == null || ctx.InUnitSpot(at, 0.04f * s)) continue;+ ctx.PlaceByWidth(outcrop, at, yaw, width, StandIn.Rock, Limestone, 40f);}bool InClearing(Vector3 p, float extra)@@ -77,7 +118,7 @@ namespace Statecraft.HexTiles.Prototypes}// 4a. Spots for the native broadleaf at the margins: around the clearings' rims and the forest edge. Chosen- // before the rows, so no pine is planted on them.+ // before the rows, so no stand tree is planted on them.var margins = new List<Vector3>();foreach (var c in clearings){@@ -92,9 +133,10 @@ namespace Statecraft.HexTiles.Prototypesreturn false;}- // 4b. The planted stands: staggered contour rows, each cell jittered; cells in the unit spot stay empty. Pines- // go in a seeded order until the cap.- float rowYaw = ctx.Range(15f, 40f), rowGap = 0.17f * s, treeGap = 0.16f * s;+ // 4b. The planted stands: staggered contour rows, each cell jittered; cells in the unit spot stay empty. Stand+ // trees go in a seeded order until the cap.+ var (yawMin, yawMax) = RowYaw;+ float rowYaw = ctx.Range(yawMin, yawMax), rowGap = RowGap * s, treeGap = TreeGap * s, jitter = Jitter;var turn = Quaternion.Euler(0f, rowYaw, 0f);var cells = new List<(Vector3 at, double key)>();for (int j = -5; j <= 5; j++)@@ -102,41 +144,48 @@ namespace Statecraft.HexTiles.Prototypes{float x = (i + (j & 1) * 0.5f) * treeGap, z = j * rowGap;var at = ctx.Centre + turn * new Vector3(x, 0f, z)- + new Vector3(ctx.Range(-0.03f, 0.03f) * s, 0f, ctx.Range(-0.03f, 0.03f) * s);+ + new Vector3(ctx.Range(-jitter, jitter) * s, 0f, ctx.Range(-jitter, jitter) * s);double key = ctx.Rng.NextDouble();if (!ctx.Inside(at, 0.04f * s) || ctx.InUnitSpot(at, 0.04f * s) || InClearing(at, 0.06f * s) || NearTrack(at, 0.075f * s)) continue;- bool shaded = !NearMargin(at); // a broadleaf spot keeps its floor but takes no pine+ bool shaded = !NearMargin(at); // a broadleaf spot keeps its floor but takes no stand treecells.Add((at, shaded ? key : 2.0));}var order = new int[cells.Count];for (int k = 0; k < order.Length; k++) order[k] = k;Array.Sort(order, (a, b) => cells[a].key != cells[b].key ? cells[a].key.CompareTo(cells[b].key) : a.CompareTo(b));- int pines = 0, fill = 0;+ int pines = 0, fill = 0, maxPines = MaxPines, maxFill = MaxFill;foreach (int k in order){if (cells[k].key > 1.0) break;- if (pines < MaxPines)+ if (pines < maxPines){- if (ctx.PlaceByHeight(Pine, cells[k].at, ctx.Range(0f, 360f), ctx.Range(0.16f, 0.20f) * s, StandIn.Pine, PineGreen, 0.3f)) pines++;+ var t = StandTree(ctx);+ if (ctx.PlaceByHeight(t.Model, cells[k].at, ctx.Range(0f, 360f), ctx.Range(t.Min, t.Max) * s, t.StandIn, t.Tint, t.Footprint)) pines++;+ }+ else if (fill < maxFill)+ {+ var t = FillTree(ctx);+ if (ctx.PlaceByHeight(t.Model, cells[k].at, ctx.Range(0f, 360f), ctx.Range(t.Min, t.Max) * s, t.StandIn, t.Tint, t.Footprint)) fill++;}- // The rest of the stand closes into canopy with round-crowned native trees (light: ~650 triangles each).- else if (fill < MaxFill && ctx.PlaceByHeight(ctx.Rng.Next(3) == 0 ? Carob : Oak, cells[k].at, ctx.Range(0f, 360f), ctx.Range(0.13f, 0.16f) * s, StandIn.Tree, OakGreen, 0.45f))- fill++;}- // 5. Native broadleaf at the margins (spots chosen in step 4a): oak or carob.- int broadleaf = 0;+ // 5. Native trees at the margins (spots chosen in step 4a).+ int broadleaf = 0, maxBroadleaf = MaxBroadleaf;foreach (var at in margins){- if (broadleaf >= MaxBroadleaf) break;+ if (broadleaf >= maxBroadleaf) break;if (NearTrack(at, 0.05f * s) || ctx.InUnitSpot(at, 0.04f * s)) continue;- bool oak = ctx.Rng.Next(3) != 0; // Tabor oak about two in three, carob the rest- if (ctx.PlaceByHeight(oak ? Oak : Carob, at, ctx.Range(0f, 360f), ctx.Range(0.14f, 0.17f) * s, StandIn.Tree, oak ? OakGreen : CarobGreen, 0.45f))+ var t = MarginTree(ctx);+ if (ctx.PlaceByHeight(t.Model, at, ctx.Range(0f, 360f), ctx.Range(t.Min, t.Max) * s, t.StandIn, t.Tint, t.Footprint))broadleaf++;}+ Dress(ctx);}+ /// <summary>Anything a variant adds last: nothing here.</summary>+ protected virtual void Dress(HexTileContext ctx) { }+static Vector3 Flat(Vector3 v) => new Vector3(v.x, 0f, v.z);static float DistToSegment(Vector3 p, Vector3 a, Vector3 b)diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCity.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCity.csindex 0033dfaba..32afba2d4 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCity.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCity.cs@@ -9,14 +9,15 @@ namespace Statecraft.HexTiles.Prototypes/// facing the square and an outer ring on the city's grid (-20 degrees, turned to the coast), garden trees between,/// townspeople on the square, a horse wagon on an avenue, and a palm promenade along the shore. Models are the/// 13 October Tripo set (local, pending rights); every piece has a stand-in.- /// Budget: this showcase tile is drawn at full quality (about 110k triangles); LODs come before any map rollout.</summary>- [HexPrototype("tel_aviv_city")]+ /// Budget: this showcase tile is drawn at full quality (about 150k triangles with the shipped b*-v2 buildings at full+ /// detail); a lighter level that keeps its UV seams comes before any map rollout.</summary>+ [HexPrototype("tel_aviv_city", Kind = "city")]public class TelAvivCity : IHexPrototype{public virtual string Title => "Tel Aviv, White City (1948)";public HexTerrain Terrain => HexTerrain.Flat;public string Ground => "plains";- public int TriangleBudget => 120000;+ public int TriangleBudget => 165000; // the shipped b*-v2 buildings at full detail (Tal, 19 Oct 2026): measured 149k on the israel board and the test hexconst string Hero = "sandbox:hq_white_city_hero", Building = "sandbox:hq_white_city*", Palm = "sandbox:date_palm",GardenTree = "sandbox:carob_lite", Wagon = "proto:figure-vehicle-horse-wagon-1948-v2";diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCityMixed.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCityMixed.csindex 1198e1944..cc7a369a8 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCityMixed.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/TelAvivCityMixed.cs@@ -6,7 +6,7 @@ namespace Statecraft.HexTiles.Prototypes/// from the first (10 October, faceted low-poly) Tripo batch, drawn as a cluster of houses at a building's footprint, so detail/// stays realistic at the square and the edge reads denser. Render it on the city's hex with/// -prototype tel_aviv_city_mixed -on tel_aviv_city.</summary>- [HexPrototype("tel_aviv_city_mixed")]+ [HexPrototype("tel_aviv_city_mixed", Kind = "city")]public sealed class TelAvivCityMixed : TelAvivCity{public override string Title => "Tel Aviv, White City (1948), mixed with the first batch";diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFields.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFields.csindex 5b371bcf2..d0a145cf6 100644--- a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFields.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFields.cs@@ -5,50 +5,100 @@ namespace Statecraft.HexTiles.Prototypes{/// <summary>Context tile: a farmed plain, Civ's farm improvement. A patchwork of large fields on one grid (wheat,/// green fodder, fresh ploughing) with tracks between, olive hedgerows along a few edges, and one farmhouse with its- /// barn (13 October Tripo modules) by the main track. Light, so many hexes can wear it.</summary>- [HexPrototype("wheat_fields")]- public sealed class WheatFields : IHexPrototype+ /// barn (13 October Tripo modules) by the main track. Light, so many hexes can wear it.+ ///+ /// The regional variants (WheatFields<Region><A|B>) subclass it: the grid's turn, the parcel size, the crop+ /// mix, the hedgerows and the farmstead are the protected virtual members below. Their defaults are this tile's own+ /// values, so wheat_fields itself builds exactly as before (HexVariantTests).</summary>+ [HexPrototype("wheat_fields", Kind = "farm")]+ public class WheatFields : IHexPrototype{- public string Title => "Wheat fields and a farmstead";- public HexTerrain Terrain => HexTerrain.Flat;- public string Ground => "plains";- public int TriangleBudget => HexScale.BudgetFields + 10000;+ public virtual string Title => "Wheat fields and a farmstead";+ public virtual HexTerrain Terrain => HexTerrain.Flat;+ public virtual string Ground => "plains";+ public virtual int TriangleBudget => HexScale.BudgetFields + 20000; // its farmstead at full detail: 31k measured++ static readonly string[] BaseCrops = { "wheat", "wheat", "green_crop", "ploughed", "wheat", "green_crop" };+ static readonly float[] BaseHedges = { -0.5f, 0.5f };+ /// <summary>The grid's turn is drawn in YawCentre ± YawSpread degrees.</summary>+ protected virtual float YawCentre => 0f;+ protected virtual float YawSpread => 25f;+ /// <summary>A parcel's side across (x) and along (z) the grid, as shares of S.</summary>+ protected virtual float CellAcross => 0.36f;+ protected virtual float CellAlong => CellAcross;+ /// <summary>The grid runs from -GridHalf to GridHalf parcels each way.</summary>+ protected virtual int GridHalf => 2;+ /// <summary>The crop layers a parcel draws from, one per parcel (repeat a layer to weight it).</summary>+ protected virtual string[] Crops => BaseCrops;+ /// <summary>One parcel in this many is left as the hex's own ground (pasture).</summary>+ protected virtual int PastureOneIn => 7;+ /// <summary>A parcel left as pasture, at its spot and size: nothing by default (the ground shows).</summary>+ protected virtual void Pasture(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) { }+ /// <summary>The farm track runs along the grid at this many parcels across, and reaches this far each way.</summary>+ protected virtual float TrackAcross => 0.5f;+ protected virtual float TrackReach => 2.6f;+ protected virtual string TrackLayer => "dirt";+ /// <summary>Hedgerow lines, in parcels across the grid; a tree every half parcel along them, one slot in+ /// HedgeGapOneIn left empty.</summary>+ protected virtual float[] HedgeLines => BaseHedges;+ protected virtual int HedgeGapOneIn => 3;+ /// <summary>One hedgerow tree: model, stand-in, tint and height as a share of S. Drawn after the gap roll.</summary>+ protected virtual (string model, StandIn standIn, Color? tint, float height) HedgeTree(HexTileContext ctx) =>+ ("sandbox:olive_lite", StandIn.Tree, null, 0.12f);public void Build(HexTileContext ctx){- float s = ctx.S, yaw = ctx.Range(-25f, 25f), cell = 0.36f * s, gap = 0.035f * s;+ float s = ctx.S, yaw = ctx.Range(YawCentre - YawSpread, YawCentre + YawSpread), cx = CellAcross * s, cz = CellAlong * s, gap = 0.035f * s;var turn = Quaternion.Euler(0f, yaw, 0f);- // Fields: a 5 x 5 grid of parcels painted into the ground as crop rows (wheat, green crops, fresh ploughing),+ // Fields: a grid of parcels painted into the ground as crop rows (wheat, green crops, fresh ploughing),// a few left as pasture, with soft edges so they read as fields, not boards, from far away.- string[] crops = { "wheat", "wheat", "green_crop", "ploughed", "wheat", "green_crop" };- for (int i = -2; i <= 2; i++)- for (int j = -2; j <= 2; j++)+ string[] crops = Crops;+ int n = GridHalf;+ for (int i = -n; i <= n; i++)+ for (int j = -n; j <= n; j++){- var at = ctx.Centre + turn * new Vector3(i * cell, 0f, j * cell);+ var at = ctx.Centre + turn * new Vector3(i * cx, 0f, j * cz);string crop = crops[ctx.Rng.Next(crops.Length)];bool across = ctx.Rng.Next(2) == 0;- if (ctx.Rng.Next(7) == 0) continue; // pasture- ctx.PaintGround(crop, at, yaw + (across ? 90f : 0f), cell - gap, cell - gap, 0.08f, 0.95f);+ float w = cx - gap, d = cz - gap;+ if (ctx.Rng.Next(PastureOneIn) == 0) { Pasture(ctx, at, yaw, w, d); continue; }+ ctx.PaintGround(crop, at, yaw + (across ? 90f : 0f), across ? d : w, across ? w : d, 0.08f, 0.95f);}- // The farm track: one straight dirt track along the grid through the hex, the farmstead on it.- ctx.PaintStroke("dirt", ctx.Centre + turn * new Vector3(0.5f * cell, 0f, -2.6f * cell), ctx.Centre + turn * new Vector3(0.5f * cell, 0f, 2.6f * cell), 0.035f * s);- // Hedgerows: olives down two parcel edges.- for (int k = -4; k <= 4; k++)- foreach (float x in new[] { -0.5f, 0.5f })- if (ctx.Rng.Next(3) != 0 && !ctx.InUnitSpot(ctx.Centre + turn * new Vector3(x * cell, 0f, k * cell * 0.5f), 0.05f * s))- ctx.PlaceByHeight("sandbox:olive_lite", ctx.Centre + turn * new Vector3(x * cell, 0f, k * cell * 0.5f), ctx.Range(0f, 360f), 0.12f * s, StandIn.Tree, null, 0.5f);- // The farmstead on a yard by the centre track: a two-storey farmhouse and a barn.+ // The farm track: one straight track along the grid through the hex, the farmstead on it.+ ctx.PaintStroke(TrackLayer, ctx.Centre + turn * new Vector3(TrackAcross * cx, 0f, -TrackReach * cz), ctx.Centre + turn * new Vector3(TrackAcross * cx, 0f, TrackReach * cz), 0.035f * s);+ // Hedgerows: trees down a few parcel edges.+ for (int k = -2 * n; k <= 2 * n; k++)+ foreach (float x in HedgeLines)+ {+ var at = ctx.Centre + turn * new Vector3(x * cx, 0f, k * cz * 0.5f);+ if (ctx.Rng.Next(HedgeGapOneIn) != 0 && !ctx.InUnitSpot(at, 0.05f * s))+ {+ var t = HedgeTree(ctx);+ ctx.PlaceByHeight(t.model, at, ctx.Range(0f, 360f), t.height * s, t.standIn, t.tint, 0.5f);+ }+ }+ Farmstead(ctx, turn, yaw);+ Dress(ctx, turn, yaw);+ }++ /// <summary>The farmstead on a yard by the centre track: a two-storey farmhouse and a barn.</summary>+ protected virtual void Farmstead(HexTileContext ctx, Quaternion turn, float yaw)+ {+ float s = ctx.S;var yard = ctx.Centre + turn * new Vector3(0.48f * s, 0f, -0.18f * s); // out of the unit spotctx.PaintGround("dirt", yard, yaw, 0.3f * s, 0.24f * s, 0.3f, 0.9f);ctx.PlaceByWidth("sandbox:kit_moshava", yard + turn * new Vector3(-0.06f * s, 0f, 0f), yaw + 180f, 0.13f * s, StandIn.Box);ctx.PlaceByWidth("sandbox:kit_moshava_3", yard + turn * new Vector3(0.08f * s, 0f, 0.02f * s), yaw + 90f, 0.12f * s, StandIn.Box);}++ /// <summary>Anything a variant adds last (scattered trees, a palm by the yard): nothing here.</summary>+ protected virtual void Dress(HexTileContext ctx, Quaternion turn, float yaw) { }}/// <summary>Context tile: open grazing land in the coastal plain and foothills. Scattered olive and carob trees, a few/// rock outcrops, and a flock of sheep with a donkey and their shepherd's track (13 October Tripo animals).</summary>- [HexPrototype("grazing_land")]+ [HexPrototype("grazing_land", Kind = "farm")]public sealed class GrazingLand : IHexPrototype{public string Title => "Grazing land with a flock";diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreA.csnew file mode 100644index 000000000..8cf67119e--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreA.cs@@ -0,0 +1,27 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, a: large square fields of wheat and fresh ploughing on the coastal plain, the grid turned about 10+ /// degrees, a sandy farm track, and a single cypress windbreak. Caps: one line of at most 9 cypresses x ~1,600 =+ /// 14,400 + the farmstead at most 2,800 = 17,200 of 30,000.</summary>+ [HexPrototype("wheat_fields_centre_a", Kind = "farm", Region = "centre")]+ public sealed class WheatFieldsCentreA : WheatFields+ {+ public override string Title => "Wheat fields, centre (a): large fields, cypress windbreak";+ protected override float YawCentre => 10f;+ protected override float YawSpread => 6f;+ protected override float CellAcross => 0.44f;+ static readonly string[] Mix = { "wheat", "wheat", "ploughed", "wheat", "green_crop" };+ protected override string[] Crops => Mix;+ protected override int PastureOneIn => 9;+ static readonly float[] Lines = { -1.0f };+ protected override float[] HedgeLines => Lines;+ protected override int HedgeGapOneIn => 4;+ protected override string TrackLayer => "beach";+ static readonly Color CypressLeaf = new Color(0.12f, 0.26f, 0.13f);+ protected override (string model, StandIn standIn, Color? tint, float height) HedgeTree(HexTileContext ctx) =>+ ("sandbox:cypress_lite", StandIn.Pine, CypressLeaf, 0.17f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreA.cs.metanew file mode 100644index 000000000..37458204c--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: e176b3a2b0e444087bf369bf0b24a4ef\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreB.csnew file mode 100644index 000000000..3a7c0c2d1--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreB.cs@@ -0,0 +1,31 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>Centre, b: narrow strip fields in alternating wheat, green crops and ploughing on a grid turned about -50+ /// degrees, on sand and grass ground, with carob trees along two strip edges. Caps: two lines of at most 17 carobs+ /// x ~650 = 22,100 + the farmstead at most 2,800 = 24,900 of 30,000.</summary>+ [HexPrototype("wheat_fields_centre_b", Kind = "farm", Region = "centre")]+ public sealed class WheatFieldsCentreB : WheatFields+ {+ public override string Title => "Wheat fields, centre (b): strip fields, carob rows";+ protected override float YawCentre => -50f;+ protected override float YawSpread => 8f;+ protected override float CellAcross => 0.18f;+ protected override float CellAlong => 0.40f;+ protected override int GridHalf => 4;+ static readonly string[] Mix = { "wheat", "green_crop", "ploughed", "wheat", "green_crop", "wheat" };+ protected override string[] Crops => Mix;+ protected override int PastureOneIn => 6;+ protected override void Pasture(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) =>+ ctx.PaintGround("beach", at, yaw, width, depth, 0.2f, 0.6f);+ static readonly float[] Lines = { -3.5f, -0.5f };+ protected override float[] HedgeLines => Lines;+ protected override float TrackAcross => 1.5f;+ protected override float TrackReach => 2.3f;+ static readonly Color CarobLeaf = new Color(0.27f, 0.39f, 0.20f);+ protected override (string model, StandIn standIn, Color? tint, float height) HedgeTree(HexTileContext ctx) =>+ ("sandbox:carob_lite", StandIn.Tree, CarobLeaf, 0.12f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreB.cs.metanew file mode 100644index 000000000..421570301--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsCentreB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f5a9e7c8b92564f58be15262dffa8795\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthA.csnew file mode 100644index 000000000..357c0d8a6--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthA.cs@@ -0,0 +1,29 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, a: green, wetter fields on a grid turned about 40 degrees, smaller square parcels mostly in green crops,+ /// the gaps left as grass, and oak and carob hedgerows down three parcel edges. Caps: at most 39 hedgerow trees x+ /// ~650 + the farmstead's two buildings at most 2,800 = 28,150 of 30,000.</summary>+ [HexPrototype("wheat_fields_north_a", Kind = "farm", Region = "north")]+ public sealed class WheatFieldsNorthA : WheatFields+ {+ public override string Title => "Wheat fields, north (a): green crops, oak hedgerows";+ protected override float YawCentre => 40f;+ protected override float YawSpread => 8f;+ protected override float CellAcross => 0.30f;+ protected override int GridHalf => 3;+ static readonly string[] Mix = { "green_crop", "green_crop", "green_crop", "wheat", "wheat", "ploughed" };+ protected override string[] Crops => Mix;+ protected override int PastureOneIn => 5;+ protected override void Pasture(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) =>+ ctx.PaintGround("grass", at, yaw, width, depth, 0.15f, 0.9f);+ static readonly float[] Lines = { -1.5f, 0.5f, 2.5f };+ protected override float[] HedgeLines => Lines;+ protected override float TrackReach => 3.6f;+ static readonly Color OakLeaf = new Color(0.30f, 0.42f, 0.20f);+ protected override (string model, StandIn standIn, Color? tint, float height) HedgeTree(HexTileContext ctx) =>+ ctx.Rng.Next(3) == 0 ? ("sandbox:carob_lite", StandIn.Tree, OakLeaf, 0.12f) : ("sandbox:tabor_oak_lite", StandIn.Tree, OakLeaf, 0.13f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthA.cs.metanew file mode 100644index 000000000..fd8e06529--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 0d403b75cf6f247b19a882fd2812f787\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthB.csnew file mode 100644index 000000000..fef5000bb--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthB.cs@@ -0,0 +1,32 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>North, b: long narrow strips of green crops and wheat on a grid turned about -35 degrees, with one Aleppo pine+ /// windbreak along a strip edge. Caps: one line of at most 13 pines x ~1,600 = 20,800 + the farmstead at most 2,800+ /// = 23,600 of 30,000.</summary>+ [HexPrototype("wheat_fields_north_b", Kind = "farm", Region = "north")]+ public sealed class WheatFieldsNorthB : WheatFields+ {+ public override string Title => "Wheat fields, north (b): green strips, pine windbreak";+ protected override float YawCentre => -35f;+ protected override float YawSpread => 8f;+ protected override float CellAcross => 0.22f;+ protected override float CellAlong => 0.50f;+ protected override int GridHalf => 3;+ static readonly string[] Mix = { "green_crop", "wheat", "green_crop", "ploughed", "green_crop" };+ protected override string[] Crops => Mix;+ protected override int PastureOneIn => 6;+ protected override void Pasture(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) =>+ ctx.PaintGround("grass", at, yaw, width, depth, 0.15f, 0.9f);+ static readonly float[] Lines = { -1.0f };+ protected override float[] HedgeLines => Lines;+ protected override int HedgeGapOneIn => 4;+ protected override float TrackAcross => 1.5f;+ protected override float TrackReach => 2.2f;+ static readonly Color PineGreen = new Color(0.20f, 0.33f, 0.18f);+ protected override (string model, StandIn standIn, Color? tint, float height) HedgeTree(HexTileContext ctx) =>+ ("sandbox:aleppo_pine_lite", StandIn.Pine, PineGreen, 0.16f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthB.cs.metanew file mode 100644index 000000000..dbbed7029--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsNorthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 6aaffcd6f012c4fa3a6e6675e8cd2cb2\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthA.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthA.csnew file mode 100644index 000000000..1b48e93ba--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthA.cs@@ -0,0 +1,35 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, a: dry farming, large square fields of wheat and fresh ploughing with many left fallow as bare sand, no+ /// hedgerows, and a few date palms by the farmstead. Caps: 4 palms x ~280 + the farmstead at most 2,800 = 3,920 of+ /// 30,000.</summary>+ [HexPrototype("wheat_fields_south_a", Kind = "farm", Region = "south")]+ public sealed class WheatFieldsSouthA : WheatFields+ {+ public override string Title => "Wheat fields, south (a): dry wheat and fallow, palms by the farm";+ protected override float YawCentre => 25f;+ protected override float YawSpread => 10f;+ protected override float CellAcross => 0.46f;+ static readonly string[] Mix = { "wheat", "wheat", "wheat", "ploughed", "ploughed" };+ protected override string[] Crops => Mix;+ protected override int PastureOneIn => 3;+ protected override void Pasture(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) =>+ ctx.PaintGround("desert", at, yaw, width, depth, 0.2f, 0.85f);+ static readonly float[] Lines = { };+ protected override float[] HedgeLines => Lines;+ protected override void Dress(HexTileContext ctx, Quaternion turn, float yaw)+ {+ float s = ctx.S;+ var yard = ctx.Centre + turn * new Vector3(0.48f * s, 0f, -0.18f * s);+ for (int k = 0; k < 4; k++)+ {+ var at = yard + turn * new Vector3((-0.12f + 0.08f * k) * s, 0f, -0.16f * s);+ float ty = ctx.Range(0f, 360f), h = ctx.Range(0.13f, 0.16f) * s;+ if (!ctx.InUnitSpot(at, 0.04f * s)) ctx.PlaceByHeight("sandbox:date_palm", at, ty, h, StandIn.Palm, null, 0.3f);+ }+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthA.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthA.cs.metanew file mode 100644index 000000000..aadd71f66--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthA.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f88063661657248d9bc8710c326a8e11\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthB.cs b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthB.csnew file mode 100644index 000000000..514186733--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthB.cs@@ -0,0 +1,29 @@+#nullable enable+using UnityEngine;++namespace Statecraft.HexTiles.Prototypes+{+ /// <summary>South, b: wide ploughed strips with wheat between, running across the hex on a grid turned about -20 degrees,+ /// bare fallow sand between some, and a broken line of acacias along one strip. Caps: one line of at most 9 acacias+ /// x ~1,160 = 10,440 + the farmstead at most 2,800 = 13,240 of 30,000.</summary>+ [HexPrototype("wheat_fields_south_b", Kind = "farm", Region = "south")]+ public sealed class WheatFieldsSouthB : WheatFields+ {+ public override string Title => "Wheat fields, south (b): ploughed strips, acacias";+ protected override float YawCentre => -20f;+ protected override float YawSpread => 10f;+ protected override float CellAcross => 0.50f;+ protected override float CellAlong => 0.26f;+ static readonly string[] Mix = { "ploughed", "ploughed", "wheat", "ploughed", "wheat" };+ protected override string[] Crops => Mix;+ protected override int PastureOneIn => 4;+ protected override void Pasture(HexTileContext ctx, Vector3 at, float yaw, float width, float depth) =>+ ctx.PaintGround("desert", at, yaw, width, depth, 0.2f, 0.85f);+ static readonly float[] Lines = { -0.5f };+ protected override float[] HedgeLines => Lines;+ protected override int HedgeGapOneIn => 2;+ static readonly Color AcaciaLeaf = new Color(0.45f, 0.47f, 0.28f);+ protected override (string model, StandIn standIn, Color? tint, float height) HedgeTree(HexTileContext ctx) =>+ ("sandbox:acacia_lite", StandIn.Tree, AcaciaLeaf, 0.13f);+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthB.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthB.cs.metanew file mode 100644index 000000000..c52bfec15--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Prototypes/WheatFieldsSouthB.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 2594bed5cfc1a40d8a3423c05b4734e2\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/HexTiles/Units/PalmachSquad.cs b/unity/Assets/Scripts/Map/HexTiles/Units/PalmachSquad.csindex c59c17b55..1b03c838b 100644--- a/unity/Assets/Scripts/Map/HexTiles/Units/PalmachSquad.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Units/PalmachSquad.cs@@ -2,13 +2,13 @@namespace Statecraft.HexTiles.Units{- /// <summary>A Palmach squad, 1948: eight fighters in a wedge (HexUnitTypes.Squad), the 13 October Tripo soldiers with- /// walk and idle clips. Only the characters: the land under them stays the tile's (Tal's unit rules).</summary>+ /// <summary>A Palmach squad, 1948: eight Palmach scouts (c12f) in a wedge (HexUnitTypes.Squad; one character type per+ /// unit, Tal, 19 October 2026). Drawn in the editor as the Collection's whole c12f figure (HexModels.FigureAliases).+ /// Only the characters: the land under them stays the tile's (Tal's unit rules).</summary>[HexUnitType("palmach_squad")]public sealed class PalmachSquad : IHexUnitType{public string Title => "Palmach squad (1948)";- public HexUnit Create() => HexUnitTypes.Squad(Title,- "proto:figure-palmach-scout-c12f-1948-v2", "proto:figure-veteran-fighter-c07-1948-v2", "proto:figure-young-recruit-c06-1948-v2");+ public HexUnit Create() => HexUnitTypes.Squad(Title, "proto:figure-palmach-scout-c12f-1948-v2");}}