A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
#nullable enable
using System.Collections.Generic;
using System.Linq;
using UnityEngine.UIElements;
namespace Statecraft.Game.UI
{
/// <summary>Fills the top bar from HudModel and runs End Turn.</summary>
public sealed class HudPresenter : System.IDisposable
{
readonly VisualElement root; readonly SimBridge bridge; readonly UiText text;
readonly Button endTurn; readonly System.Action onEndTurn;
readonly VisualElement bar, hudRoot, nav;
/// <summary>The info panel and the side menu, for the tight HUD's info-panel caps (FitInfoPanel, #40).</summary>
readonly VisualElement? infoPanel, railColumn;
/// <summary>The minimap and its border caption, which a lifted info panel stands above, and "Decision waiting" and the
/// toast at the top of the right column, which it stays under (FitInfoPanel, #40).</summary>
readonly VisualElement? minimap, mapLayer, decisionWaiting, captureWaiting, toast;
readonly System.Collections.Generic.List<VisualElement> meters;
/// <summary>Each meter's element and its caption in the UI's language, for the words in its tooltip (#398).</summary>
readonly System.Collections.Generic.Dictionary<string, (VisualElement element, string caption)> said =
new System.Collections.Generic.Dictionary<string, (VisualElement, string)>();
// Three tiers by the bar's logical width (1080p reference, match 0.5: the panel's scale is the plain mean of the two
// ratios, (w/1920 + h/1080) / 2, so logical width = w / that; TopBarTests logs it). HUD round 2 moved the four screen
// buttons to the left column (#602), about 248 px out of the bar, so every tier starts narrower (part 3). With six
// meters the one-row edge sat between a fullscreen 5:4 and 4:3 (1640; review of #624).
// Social cohesion made seven meters (#380). The owner chose "tighten and re-tier" (16 October 2026): the meters' padding
// is about 6 px narrower, and the edges move to the seven meters' measured widths (widest values, the Hebrew bar the
// widest: one row about 1285 px of meters, stacked about 1055, without icons about 811, each with 5% to spare, beside
// about 484 px of plate, turn box and padding). 16:9 at 1920 keeps the one-row bar; 16:10, 4:3, and 1280x720 and
// 1366x768 (where the text floor raises the captions) take the stacked bar; 5:4 drops the icons; a square window
// takes two rows; a phone's meters wrap to two lines. TopBarTests holds one row at 1865 and the stacked bar at 1855:
// 21:9 ~2217 | 16:9 1920 | NarrowBelowPx 1860 | 16:10 ~1819 | 4:3 ~1646 | CompactBelowPx 1640 | 5:4 ~1585
// | TwoRowBelowPx 1400 | square ~1382 | half a 1080p screen (960x1080) ~1280.
// PromoHudTests.EveryWindowShapeFitsTheBarAfterATurn proves each tier holds the widest late-game values and changes.
/// <summary>Below this width the HUD's root gets NarrowClass: a taller bar (124 px) whose meters stack the change under
/// the value, and the panels below it move down to match (Statecraft.uss .hud-narrow). Above it, the 70 px one-row bar
/// (promo 03's 6.5%) holds seven values and their changes side by side with the icons.</summary>
public const float NarrowBelowPx = 1860f;
public const string NarrowClass = "hud-narrow";
/// <summary>The noncompact stacked tier has room for natural-width resource captions (laptop playtest).</summary>
public const string CaptionLineClass = "top-bar--caption-line";
/// <summary>Below this width the meters also drop their icons (Statecraft.uss .top-bar--compact): a square window does not
/// have the room for them on the stacked bar.</summary>
public const float CompactBelowPx = 1640f;
public const string CompactClass = "top-bar--compact";
/// <summary>Below this width (windows narrower than about square, e.g. a browser snapped to half a 1080p screen, about
/// 1360 logical px, and a square one, about 1382) one row cannot hold the badge, seven meters, New Game and End Turn: the root also gets
/// TwoRowClass, and the bar wraps into two rows, the date and the meters above, the screen buttons and End Turn
/// below (Statecraft.uss .hud-two-row).</summary>
public const float TwoRowBelowPx = 1400f;
public const string TwoRowClass = "hud-two-row";
/// <summary>Below this width (a phone held upright: 390x844 is about 790 logical px) the badge and the meters do not
/// fit one row either: the root also gets ThreeRowClass, and the bar takes three rows, the badge, the meters (seven,
/// wrapped to two lines, #380), then the screen buttons and End Turn (Statecraft.uss .hud-three-row; #210).</summary>
public const float ThreeRowBelowPx = 1100f;
public const string ThreeRowClass = "hud-three-row";
/// <summary>The tight HUD (#40, the UI scale's 125% and 150%): a small logical window (1920x1080 at 150% is 1280x720
/// logical; a 360x800 phone at 150% is about 517 px wide) gives the stacked bar, the icon column and the panels their tight
/// sizes (Statecraft.uss .hud-tight). Small phone windows at 100% reach these bounds too, so the tight HUD changes
/// only layout sizes: the small text keeps the same screen-pixel floor (SmallTextSize) in and out of it.</summary>
public const string TightClass = "hud-tight";
// With the panel's match 0.5, the ratio sum is 2 at 100%, 1.6 at 125%, and 1.33 at 150%.
public const string Scale150Class = "hud-scale-150", CabinetCardsFirstClass = "cabinet-cards-first", CabinetPhone150Class = "cabinet-phone-150";
public const float TightBelowHeightPx = 1200f, TightAndBelowWidthPx = 1700f, TightBelowWidthPx = 960f;
/// <summary>Also tight below this logical height at a scale choice, at any width: 2560x1080 at 125% is 1755x740
/// logical, wider than TightAndBelowWidthPx and too short for a city's info panel, which rose above the window.
/// Some windows at 100% are as short (5120x1440 is 2560x720 logical, 1280x420 is 2424x795), so this applies only
/// at a scale choice: the panel scales by the plain mean of its two ratios to the reference resolution (match
/// 0.5), so at 100% every window's logical width / 1920 + height / 1080 is exactly 2, and at 125% it is 1.6, at
/// 150% 1.33 (Settings sets the reference resolution to 1920x1080 / the scale).</summary>
public const float TightScaledBelowHeightPx = 800f;
/// <summary>Statecraft.uss .hud-tight.hud-three-row .top-bar height: the tight three-row bar's rows.</summary>
public const float TightThreeRowBarPx = 200f;
/// <summary>Statecraft.uss .hud-tight.hud-two-row .top-bar height: a floor the rows can outgrow when the text floor
/// raises the plate (960x600 at 125%: a 109 px plate over End Turn's 64 px row), as the three-row bar's (PlaceUnderBar).</summary>
public const float TightTwoRowBarPx = 172f;
/// <summary>The tight info panel's top keeps this gap below the lower of the bar and the side menu (FitInfoPanel).</summary>
public const float TightInfoGapPx = 4f;
/// <summary>On the tight three-row window the info panel's right edge keeps this far from the window's: the minimap's
/// 222 px (Statecraft.uss .minimap), its 16 px inset and a 32 px gap (FitInfoPanel).</summary>
public const float TightThreeRowMinimapClearPx = 270f;
/// <summary>On the tight three-row window, when that clearance leaves the info panel narrower than this (the hex's sign
/// and a line of its facts; a phone at 125% or 150%, 163 to 280 px), the panel stands above the minimap and its
/// caption instead, as wide as the window less its insets (FitInfoPanel). Phones at 100% keep 422 px or more.</summary>
public const float TightInfoBesideMinPx = 360f;
/// <summary>The lifted info panel's gap above the minimap and its caption (FitInfoPanel).</summary>
public const float TightInfoAbovePx = 12f;
/// <summary>On the one-row bar, when the meters leave enough room, the bar gets RoomyClass: promo-sized icons (38 px)
/// and values (25 px) (Statecraft.uss .top-bar--roomy). It turns on only when the measured spare room covers the
/// predicted growth (RoomyGrowth) plus SpareShare, and off when the spare room falls below SpareShare, so it never
/// flips back and forth.</summary>
public const string RoomyClass = "top-bar--roomy";
/// <summary>The share of the meters' width kept free after them (room for the browser's text measuring wider than the
/// editor's; PromoHudTests.EveryWindowShapeFitsTheBarAfterATurn asserts it).</summary>
public const float SpareShare = 0.05f;
/// <summary>The meters' predicted growth when roomy: each of the <paramref name="icons"/> shown icons 30 -> 38 px (six,
/// or seven with Social cohesion in the GDD loop), values 22 -> 25 px (about 14% wider), and each wrapped caption back
/// to its one-line width (<paramref name="captionGrowth"/>).</summary>
public static float RoomyGrowth(float valueWidths, float captionGrowth = 0f, int icons = 6) => icons * 8f + 0.14f * valueWidths + captionGrowth;
/// <summary>The top bar's static texts and their strings (#193): the screen buttons, New Game and End Turn. The
/// meters' captions are hud.caption.*, the same words their tooltips say.</summary>
static readonly (string name, string key)[] Texts =
{
("nav-cabinet", "hud.nav.cabinet"), ("nav-budget", "hud.nav.budget"), ("nav-defence", "hud.nav.defence"),
("nav-why", "hud.nav.why"), ("nav-timeline", "nav.timeline"), ("nav-encyclopedia", "hud.nav.encyclopedia"),
("nav-objectives", "hud.nav.objectives"), ("nav-settings", "hud.nav.settings"),
("new-game", "hud.new_game"), ("end-turn", "hud.end_turn"),
};
/// <summary>The owner's text floor (#624, 15 October 2026): the bar's small text (the seven captions, Security's level
/// and the attention line, SmallTextPx in the stylesheet) stays at least this many pixels on screen. The panel scales
/// with the window (about 0.67 at 1280x720, 0.62 at 1024x768), so at small windows the text is set larger in panel
/// px (SmallTextSize).</summary>
public const float TextFloorPx = 12f;
/// <summary>The bar's small text in the stylesheet (Statecraft.uss .meter-name, #security-level, #attention).</summary>
public const float SmallTextPx = 15f;
/// <summary>The small text's size in panel px when one panel px is <paramref name="screenPxPerPanelPx"/> pixels on
/// screen: the stylesheet's SmallTextPx, or the whole px that keeps it at TextFloorPx on screen if that is larger.</summary>
public static float SmallTextSize(float screenPxPerPanelPx) => FlooredTextSize(SmallTextPx, screenPxPerPanelPx);
/// <summary>The same rule for any text (the advisors' popup's too): its stylesheet size <paramref name="stylesheetPx"/>,
/// or the whole px that keeps it at TextFloorPx on screen if that is larger.</summary>
public static float FlooredTextSize(float stylesheetPx, float screenPxPerPanelPx) =>
screenPxPerPanelPx > 0f ? UnityEngine.Mathf.Max(stylesheetPx, UnityEngine.Mathf.Ceil(TextFloorPx / screenPxPerPanelPx - 0.01f)) : stylesheetPx;
/// <summary>Screen pixels per panel px on <paramref name="panel"/> (a CSS pixel in the browser: DevicePixelRatio).</summary>
internal static float ScreenPxPerPanelPx(IPanel panel) => panel.scaledPixelsPerPoint / DevicePixelRatio();
readonly List<Label> smallText;
/// <summary>The plate's turn and date line (Statecraft.uss .date-row Label, 15 px): raised with the bar's small text (the
/// owner's second answer, 15 October 2026). The plate keeps its width; the turn and the date take a line each, and the
/// plate grows.</summary>
readonly List<Label> plateText;
readonly VisualElement? dateRow, captionRow;
/// <summary>The exhausted-turn line under the date (Statecraft.uss #exhausted, #812): floored like the date, from its own
/// stylesheet size (ExhaustedPx). 15 px since #2522 (#2340 H4, the audit's 15 px floor); it was 13 px.</summary>
readonly Label? exhaustedLine;
public const float ExhaustedPx = 15f;
float exhaustedSize = ExhaustedPx;
/// <summary>The room before a change that its up or down mark takes (Statecraft.uss .meter-delta.delta-up, 9 px).</summary>
public const float ChangeMarkPadPx = 9f;
readonly List<Label> deltas = new List<Label>();
/// <summary>The plate's padding while the floor raises its text (the stylesheet's is 2 px top and bottom, 10-12 at the
/// sides): PlateSidePx at both sides keeps every line at least 0 px from the 18 px corner zones (TopBarTests), each the
/// corner scrolls' reach (about 14 px in) plus 4, and PlateEdgePx at the top and bottom keeps it inside the frame's
/// inner rule (7 px in). The plate grows to
/// hold them (its height is a minimum), rather than shift its lines.</summary>
public const float PlateSidePx = 18f, PlateEdgePx = 9f;
/// <summary>The stylesheet's side padding of the plate (12 + 10 px, either language); the clearance that replaces it widens
/// the plate by the difference, so the turn and the date keep their one row at the 15 px size.</summary>
const float StylesheetPlatePadPx = 22f;
readonly VisualElement turnBox;
readonly IVisualElementScheduledItem floorCheck;
readonly EventCallback<GeometryChangedEvent> onRootGeometry;
float smallTextSize = SmallTextPx;
bool captionFitWrap;
/// <summary>The left icon column (promo 03): the screens' buttons (ScreenNav.Screens).</summary>
public const string RailName = "left-column";
/// <summary>#1109: the class on a side-menu button whose screen has something the player can do this turn
/// (Statecraft.uss shows the button's BadgeClass dot). Cabinet has one: a vacant seat to fill (SimBridge.Vacancies); Budget
/// another, an edited budget not submitted (BudgetPresenter, SimBridge.BudgetUnsubmitted).</summary>
public const string ActionClass = "nav-action", BadgeClass = "nav-badge";
readonly HoverTip? railTips, barTips;
/// <summary>The meters' explanations under the bar (#1037): their words and the turn's causes.</summary>
readonly MeterTip? meterTip;
/// <summary>Pass the same map names used by Why to the meter causes.</summary>
public IReadOnlyDictionary<string, string>? TownNamesHe
{
get => meterTip?.TownNamesHe;
set { if (meterTip != null) meterTip.TownNamesHe = value; }
}
/// <summary>The panels under the bar (Statecraft.uss: top 456 px under the three-row bar), which PlaceUnderBar moves
/// by what the three-row bar grows past, or shrinks under, its 440 px (#1089).</summary>
readonly List<VisualElement> underBar;
/// <summary>The bar's items, whose rows set the three-row bar's height (RowsHeight).</summary>
readonly List<VisualElement> barItems;
/// <summary>Statecraft.uss .hud-three-row .top-bar height.</summary>
const float ThreeRowBarPx = 440f;
public HudPresenter(VisualElement root, SimBridge bridge, UiText text, System.Action<int>? selectUnit = null)
{
this.root = root; this.bridge = bridge; this.text = text;
endTurn = root.Q<Button>("end-turn");
onEndTurn = () =>
{
var needs = bridge.NeedsOrders;
if (needs.Count > 0) selectUnit?.Invoke(needs[0]);
else bridge.EndTurn();
};
endTurn.clicked += onEndTurn;
endTurn.generateVisualContent += PaintHourglass;
bar = root.Q<VisualElement>("top-bar");
hudRoot = root.Q<VisualElement>("root");
bar.RegisterCallback<GeometryChangedEvent>(OnBarGeometry);
infoPanel = root.Q<VisualElement>("info-panel");
railColumn = root.Q<VisualElement>(RailName);
infoPanel?.RegisterCallback<GeometryChangedEvent>(OnCapGeometry); // shown again after a screen, or resized
railColumn?.RegisterCallback<GeometryChangedEvent>(OnCapGeometry); // moved down by a grown three-row bar
minimap = root.Q<VisualElement>("minimap");
mapLayer = root.Q<VisualElement>("map-layer");
mapLayer?.RegisterCallback<GeometryChangedEvent>(OnCapGeometry); // the border caption shown or hidden
minimap?.RegisterCallback<GeometryChangedEvent>(OnCapGeometry); // moved with the right column
decisionWaiting = root.Q<VisualElement>("event-reopen"); captureWaiting = root.Q<VisualElement>("capture-reopen");
toast = root.Q<VisualElement>("toast");
foreach (var e in new[] { decisionWaiting, captureWaiting, toast }) e?.RegisterCallback<GeometryChangedEvent>(OnCapGeometry); // shown or hidden
meters = root.Q<VisualElement>("meters").Children().ToList();
nav = root.Q<VisualElement>("nav");
foreach (var m in meters) m.RegisterCallback<GeometryChangedEvent>(OnMeterGeometry);
foreach (var (name, key) in Texts) root.Q<TextElement>(name).text = text[key];
// The left column's buttons are icon-only (HUD round 2, #398): their name, kept as their (clear) text, is also
// their tooltip, which HoverTip shows beside the disc on hover and on focus.
var rail = root.Q<VisualElement>(RailName)?.Query<Button>().ToList() ?? new List<Button>();
foreach (var b in rail) b.tooltip = b.text;
if (rail.Count > 0 && root.Q<Label>(HoverTip.TipName) != null) railTips = new HoverTip(root, rail, () => HoverTip.Side.Right);
// New Game in the bar is icon-only too (HUD round 2, part 3); its tip opens toward the bar's middle: left of it,
// or right of it in the mirrored Hebrew bar.
var newGame = root.Q<Button>("new-game");
if (newGame != null)
{
newGame.tooltip = newGame.text;
if (root.Q<Label>(HoverTip.TipName) != null)
barTips = new HoverTip(root, new[] { newGame }, () => hudRoot.ClassListContains(UiLanguage.HebrewClass) ? HoverTip.Side.Right : HoverTip.Side.Left);
}
foreach (var id in HudModel.MeterIds)
{
var meter = root.Q<VisualElement>("meter-" + id); var caption = text["hud.caption." + id];
meter.Q<Label>(className: "meter-name").text = caption; // the bar shows the words its tooltip says
said[id] = (meter, caption);
var delta = root.Q<Label>(id + "-delta"); delta.generateVisualContent += PaintChange; deltas.Add(delta);
}
if (root.Q(MeterTip.TipName) != null) meterTip = new MeterTip(root, bridge, text, said.Values.Select(x => x.element));
// The text floor: checked now and twice a second, since a window resized at the same shape changes the panel's
// scale without changing its layout (no geometry event).
smallText = bar.Query<Label>(className: "meter-name").ToList(); // the seven captions and Security's level
smallText.Add(root.Q<Label>("attention"));
turnBox = bar.Q<VisualElement>(className: "turn-box");
underBar = new[] { "right-column", "left-column", "event-gutter", "event-layer", "screen", "toast" }
.SelectMany(c => root.Query(className: c).ToList()).ToList();
barItems = bar.Children().ToList();
foreach (var k in barItems) k.RegisterCallback<GeometryChangedEvent>(OnRowGeometry); // a row grows inside the fixed bar
dateRow = bar.Q<VisualElement>(className: "date-row");
captionRow = bar.Q(className: "meter-caption-row");
plateText = dateRow?.Query<Label>().ToList() ?? new List<Label>();
exhaustedLine = root.Q<Label>("exhausted");
dateRow?.parent?.RegisterCallback<GeometryChangedEvent>(OnPlateGeometry); // a wider raised plate needs room in the bar
ApplyTextFloor();
floorCheck = root.schedule.Execute(ApplyTextFloor).Every(500);
SetCompact(bar.layout.width); // the bar may already be laid out (the loading screen shows it) and never resize
onRootGeometry = _ => SetTight(); // the window, not only the bar, can cross the tight bounds
hudRoot.RegisterCallback(onRootGeometry);
root.Q(className: "hemicycle-box")?.RegisterCallback<GeometryChangedEvent>(OnCabinetGeometry);
bridge.Changed += Render;
Render();
}
/// <summary>Unsubscribes from the bridge and the button (the owner calls this when it is disabled).</summary>
public void Dispose()
{
railTips?.Dispose(); barTips?.Dispose(); meterTip?.Dispose();
floorCheck.Pause();
foreach (var l in smallText) { l.style.fontSize = StyleKeyword.Null; l.style.whiteSpace = StyleKeyword.Null; l.style.maxWidth = StyleKeyword.Null; }
if (captionRow != null) captionRow.style.flexWrap = StyleKeyword.Null;
turnBox.style.width = StyleKeyword.Null; turnBox.style.minWidth = StyleKeyword.Null;
foreach (var k in barItems) k.UnregisterCallback<GeometryChangedEvent>(OnRowGeometry);
foreach (var e in underBar) e.style.marginTop = StyleKeyword.Null;
bar.style.height = StyleKeyword.Null;
foreach (var l in plateText) { l.style.fontSize = StyleKeyword.Null; l.style.whiteSpace = StyleKeyword.Null; }
if (exhaustedLine != null) { exhaustedLine.style.fontSize = StyleKeyword.Null; exhaustedLine.style.whiteSpace = StyleKeyword.Null; }
// Cleared here, not by PadPlate: it keeps the plate's width and padding while the exhausted line shows (#2522), and
// the line may still show when the presenter goes (review of #2607).
if (dateRow != null)
{
dateRow.style.flexDirection = StyleKeyword.Null;
var plate = dateRow.parent;
if (plate != null)
{
plate.style.width = StyleKeyword.Null; plate.style.minWidth = StyleKeyword.Null;
plate.style.paddingTop = StyleKeyword.Null; plate.style.paddingBottom = StyleKeyword.Null;
plate.style.paddingLeft = StyleKeyword.Null; plate.style.paddingRight = StyleKeyword.Null;
}
}
bridge.Changed -= Render; endTurn.clicked -= onEndTurn; endTurn.generateVisualContent -= PaintHourglass;
foreach (var d in deltas) d.generateVisualContent -= PaintChange;
bar.UnregisterCallback<GeometryChangedEvent>(OnBarGeometry);
hudRoot.UnregisterCallback(onRootGeometry);
root.Q(className: "hemicycle-box")?.UnregisterCallback<GeometryChangedEvent>(OnCabinetGeometry);
hudRoot.RemoveFromClassList(TightClass);
hudRoot.RemoveFromClassList(Scale150Class);
hudRoot.RemoveFromClassList(CabinetPhone150Class);
hudRoot.RemoveFromClassList(CabinetCardsFirstClass);
FitCabinet(root);
SizeTightValues(); // off the tight HUD: the values' sizes go back to the stylesheet's
infoPanel?.UnregisterCallback<GeometryChangedEvent>(OnCapGeometry);
railColumn?.UnregisterCallback<GeometryChangedEvent>(OnCapGeometry);
mapLayer?.UnregisterCallback<GeometryChangedEvent>(OnCapGeometry);
minimap?.UnregisterCallback<GeometryChangedEvent>(OnCapGeometry);
foreach (var e in new[] { decisionWaiting, captureWaiting, toast }) e?.UnregisterCallback<GeometryChangedEvent>(OnCapGeometry);
if (infoPanel != null) { infoPanel.style.maxHeight = StyleKeyword.Null; infoPanel.style.maxWidth = StyleKeyword.Null; infoPanel.style.bottom = StyleKeyword.Null; }
dateRow?.parent?.UnregisterCallback<GeometryChangedEvent>(OnPlateGeometry);
foreach (var m in meters) m.UnregisterCallback<GeometryChangedEvent>(OnMeterGeometry);
bar.RemoveFromClassList(RoomyClass);
bar.RemoveFromClassList(CaptionLineClass);
bar.RemoveFromClassList(CompactClass); hudRoot.RemoveFromClassList(NarrowClass); hudRoot.RemoveFromClassList(TwoRowClass); hudRoot.RemoveFromClassList(ThreeRowClass);
ScreenNav.DisableCovered(hudRoot);
}
// The bar's width does not depend on the class, so this settles in one pass.
void OnBarGeometry(GeometryChangedEvent e) => SetCompact(e.newRect.width);
// The raised plate sizes to its widest line (PadPlate), so the tiers re-read the room it takes (FloorGrowth). The
// plate's width does not depend on the tier, so this settles in one pass.
void OnPlateGeometry(GeometryChangedEvent e) { if (smallTextSize > SmallTextPx && e.oldRect.width != e.newRect.width) SetCompact(bar.layout.width); }
void OnMeterGeometry(GeometryChangedEvent e)
{
UpdateRoomy();
if (smallTextSize > SmallTextPx && bar.ClassListContains(CompactClass)) SetCompact(bar.layout.width);
}
// The rows' height does not depend on the bar's (RowsHeight), so this settles in one pass.
void OnRowGeometry(GeometryChangedEvent e) => PlaceUnderBar();
void OnCapGeometry(GeometryChangedEvent e) => FitInfoPanel();
void OnCabinetGeometry(GeometryChangedEvent e) => FitCabinet(root);
/// <summary>Roomy only on the one-row bar with icons; see RoomyClass.</summary>
void UpdateRoomy()
{
var meters = this.meters.Where(m => m.resolvedStyle.display != DisplayStyle.None).ToList(); // a hidden meter takes no room
if (meters.Count == 0) return;
var oneRow = !hudRoot.ClassListContains(NarrowClass) && !bar.ClassListContains(CompactClass);
// Panel coordinates (logical px), so the meters and the screen buttons compare directly.
float left = meters.Min(m => m.worldBound.xMin), right = meters.Max(m => m.worldBound.xMax);
var rtl = UiLanguage.Within(bar);
var limit = rtl ? nav.worldBound.xMax : nav.worldBound.xMin;
if (!oneRow || float.IsNaN(left) || float.IsNaN(right) || float.IsNaN(limit)) { bar.RemoveFromClassList(RoomyClass); return; }
var used = right - left; var spare = rtl ? left - limit : limit - right;
if (bar.ClassListContains(RoomyClass))
{
if (spare < SpareShare * used) bar.RemoveFromClassList(RoomyClass);
}
else
{
var values = meters.Sum(m => m.Q<Label>(className: "meter-value")?.worldBound.width ?? 0f);
var captions = meters.Sum(m =>
{
var c = m.Q<Label>(className: "meter-name");
if (c == null || string.IsNullOrEmpty(c.text)) return 0f;
var oneLine = c.MeasureTextSize(c.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x;
return UnityEngine.Mathf.Max(0f, oneLine - c.worldBound.width);
});
if (spare - RoomyGrowth(values, captions, meters.Count) >= SpareShare * used + 8f) bar.AddToClassList(RoomyClass);
}
}
/// <summary>Sets the small text to SmallTextSize for the panel's current scale and re-picks the tier, since larger
/// captions need more room (TierWidth).</summary>
void ApplyTextFloor()
{
var p = root.panel;
if (p == null) return;
var scale = ScreenPxPerPanelPx(p);
var size = SmallTextSize(scale);
var exhausted = FlooredTextSize(ExhaustedPx, scale);
if (size == smallTextSize && exhausted == exhaustedSize) return;
smallTextSize = size;
exhaustedSize = exhausted;
SetCompact(bar.layout.width);
}
/// <summary>Whether the floor raises the text at this bar width: at every tier, the three-row bar of a phone held upright
/// (about 0.49 scale, 25 px) included (#642).</summary>
bool FloorRaises(float width) => smallTextSize > SmallTextPx;
/// <summary>The room the raised text takes beyond what the tiers were set for (the 15 px captions, wrapped at their 120 px
/// max-width, and the 150 px turn box): each caption on one line at the larger size (text width scales with font
/// size), and the turn box widened in step. The one-row and icon tiers read the bar's width less this.</summary>
float FloorGrowth()
{
float growth = TurnBoxWidth - TurnBoxPx + (RaisedPlateWidth() - PlateWidthPx);
foreach (var l in smallText)
{
if (l.name == "attention" || string.IsNullOrEmpty(l.text)) continue;
var current = l.resolvedStyle.fontSize;
if (!(current > 0f)) continue;
var oneLine = l.MeasureTextSize(l.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x;
growth += oneLine * smallTextSize / current - UnityEngine.Mathf.Min(oneLine * SmallTextPx / current, CaptionMaxPx);
}
return UnityEngine.Mathf.Max(0f, growth);
}
// Statecraft.uss .turn-box width, .meter .meter-name max-width (170 on the three-row bar, where the tier is fixed), .date-box width.
const float TurnBoxPx = 150f, CaptionMaxPx = 120f, PlateWidthPx = 230f;
// The button keeps its stylesheet font; only the attention line grows with the text floor.
float TurnBoxWidth => UnityEngine.Mathf.Max(bridge.NeedsOrders.Count > 0 ? 230f : TurnBoxPx,
bridge.Content.UsesAttention ? TurnBoxPx * smallTextSize / SmallTextPx : TurnBoxPx);
/// <summary>The widest date line's width per px of font size, with a little to spare: the Hebrew 31 October 1956 is
/// about 7.8 times its size (196 px at 25 px), the English "30 September 1956" 7.2 (TopBarScoreLayoutTests.WorstDate).</summary>
const float DateLinePerPx = 8f;
/// <summary>The raised plate's laid-out width (PadPlate lets it size to its widest line, at least the stylesheet's 230 px;
/// at 23 px, 960x600, the date is wider), or 230 before it is laid out.</summary>
float RaisedPlateWidth()
{
var w = dateRow?.parent?.layout.width ?? float.NaN;
return w > PlateWidthPx ? w : PlateWidthPx;
}
/// <summary>The largest raised small text the 70 px one-row bar holds: the attention line above End Turn is taller with
/// it, and at 19 px (1366x657) the Hebrew turn box leaves the bar (TopBarTests.TheBarFitsEveryWindowInEnglishAndHebrew),
/// so above this the bar takes the stacked tier.</summary>
public const float OneRowSmallMaxPx = 18f;
/// <summary>Inline styles for the floor, only while it raises the text: its size; the captions on one line on the one-row
/// and stacked bars (a wrapped caption at the larger size would leave the bar), where FloorGrowth has made room (the
/// two-row bar keeps the stylesheet's wrapping); and the turn box widened so the attention line fits.</summary>
void StyleSmallText(bool raised)
{
bool oneLine = raised && !hudRoot.ClassListContains(TwoRowClass);
foreach (var l in smallText)
{
l.style.fontSize = raised ? new StyleLength(smallTextSize) : new StyleLength(StyleKeyword.Null);
if (l.name == "attention") continue;
l.style.whiteSpace = oneLine ? new StyleEnum<WhiteSpace>(WhiteSpace.NoWrap) : new StyleEnum<WhiteSpace>(StyleKeyword.Null);
l.style.maxWidth = oneLine || captionFitWrap ? new StyleLength(StyleKeyword.None) : new StyleLength(StyleKeyword.Null);
}
if (captionRow != null) captionRow.style.flexWrap = captionFitWrap
? new StyleEnum<Wrap>(Wrap.Wrap) : new StyleEnum<Wrap>(StyleKeyword.Null);
foreach (var l in plateText)
{
l.style.fontSize = raised ? new StyleLength(smallTextSize) : new StyleLength(StyleKeyword.Null);
// One line each; the plate widens for them (PadPlate).
l.style.whiteSpace = raised ? new StyleEnum<WhiteSpace>(WhiteSpace.NoWrap) : new StyleEnum<WhiteSpace>(StyleKeyword.Null);
}
if (exhaustedLine != null)
{
var up = exhaustedSize > ExhaustedPx;
exhaustedLine.style.fontSize = up ? new StyleLength(exhaustedSize) : new StyleLength(StyleKeyword.Null);
exhaustedLine.style.whiteSpace = up ? new StyleEnum<WhiteSpace>(WhiteSpace.NoWrap) : new StyleEnum<WhiteSpace>(StyleKeyword.Null);
}
// Raised, the turn and the date take a line each (a raised date squeezed beside the turn was clipped in Hebrew),
// and the plate's padding keeps every line inside its gilt frame's inner rule and at least 0 px from the 18 px corner
// zones, which keep 4 px clear of the scrolls (PlateSidePx, PlateEdgePx; reviews of #624 in WebGL); the plate grows
// to hold them.
if (dateRow != null)
{
dateRow.style.flexDirection = raised ? new StyleEnum<FlexDirection>(FlexDirection.Column) : new StyleEnum<FlexDirection>(StyleKeyword.Null);
if (dateRow.parent != null) PadPlate(dateRow.parent, raised);
}
var box = TurnBoxWidth;
turnBox.style.width = raised ? new StyleLength(box) : new StyleLength(StyleKeyword.Null);
turnBox.style.minWidth = raised ? new StyleLength(box) : new StyleLength(StyleKeyword.Null);
}
void PadPlate(VisualElement plate, bool raised)
{
// Raised, the plate sizes to its widest line (the turn and the date, a line each, never wrapped), at least 230 px.
// The exhausted line (#812) is never wrapped either, so it too lets the plate size to it, but only while it shows
// (Render): a hidden line leaves the plate as it was (review of #1961). At 15 px (#2522) it is wider than the 196 px
// plate at every scale, not only when raised, so the plate sizes to it whenever it shows.
var lineUp = exhaustedLine != null && exhaustedLine.style.display == DisplayStyle.Flex;
plate.style.width = raised || lineUp ? new StyleLength(StyleKeyword.Auto) : new StyleLength(StyleKeyword.Null);
// At least the widest date line too, so the plate keeps its width when the month changes (PromoHudTests): at 25 px
// (a phone upright, #642) the Hebrew 31 October 1956 is about 196 px, wider than 230 px less the padding.
plate.style.minWidth = raised ? new StyleLength(UnityEngine.Mathf.Max(PlateWidthPx, DateLinePerPx * smallTextSize + 2f * PlateSidePx + 2f))
: lineUp ? new StyleLength(PlateWidthPx + 2f * PlateSidePx - StylesheetPlatePadPx) : new StyleLength(StyleKeyword.Null);
// The frame clearance holds when the 15 px text is raised or the exhausted line shows (#2522: it widens the plate at any scale).
StyleLength Px(float v) => raised || lineUp ? new StyleLength(v) : new StyleLength(StyleKeyword.Null);
plate.style.paddingTop = Px(PlateEdgePx); plate.style.paddingBottom = Px(PlateEdgePx);
plate.style.paddingLeft = Px(PlateSidePx); plate.style.paddingRight = Px(PlateSidePx);
}
/// <summary>The three-row bar takes its rows' height, so the raised text of a smaller phone fits it when that is more than
/// its 440 px (Statecraft.uss; #642, the owner: "down to 375x667"), and on a phone whose rows come in shorter no empty band
/// is left between the stats and the map (#1089, the owner: "the three-row bar shrinks to fit its rows"). The panels under
/// it move by what it grew or shrank: a top margin (negative when it shrank), not a top, so the stylesheet's other
/// placements (the toast at the bottom beside a wide screen) still apply. Set here, not as height: auto in the stylesheet:
/// there Yoga sized the wrapping bar as if each quarter-width meter took a line of its own (about 1300 px). Its items'
/// geometry events re-run this (OnRowGeometry), and so does SetCompact. The tight two-row bar (#40) grows the same way
/// past its TightTwoRowBarPx when the text floor makes its rows taller, and never shrinks under it.</summary>
void PlaceUnderBar()
{
// A hidden bar (the start screen) moves nothing: the start screen's toast keeps its own top (review of #859).
var threeRow = hudRoot.ClassListContains(ThreeRowClass);
var tight = hudRoot.ClassListContains(TightClass);
// The tight two-row bar only grows past its floor (#40): its rows never came in shorter than its 172 px.
var tightTwoRow = tight && !threeRow && hudRoot.ClassListContains(TwoRowClass);
var basePx = threeRow ? (tight ? TightThreeRowBarPx : ThreeRowBarPx) : TightTwoRowBarPx;
var rows = (threeRow || tightTwoRow) && bar.resolvedStyle.display != DisplayStyle.None ? RowsHeight() : 0f;
if (tightTwoRow && rows < basePx) rows = 0f;
var grown = rows > 0f ? rows - basePx : 0f; // NaN before layout or 0 off these bars: the stylesheet's height
var fit = UnityEngine.Mathf.Abs(grown) > 0.5f;
bar.style.height = fit ? new StyleLength(rows) : new StyleLength(StyleKeyword.Null);
var margin = fit ? new StyleLength(grown) : new StyleLength(StyleKeyword.Null);
// On the tight three-row window a screen takes the window (Statecraft.uss, the mobile-modal pattern): the bar's
// growth does not move it, or it would start part-way down the bar it covers.
var screenTakesWindow = threeRow && hudRoot.ClassListContains(TightClass);
foreach (var e in underBar) e.style.marginTop = screenTakesWindow && e.ClassListContains("screen") ? new StyleLength(StyleKeyword.Null) : margin;
}
/// <summary>The height the bar's rows take: each row's tallest item (its children laid out in the flow, grouped by the
/// rows they share), with the bar's padding and border. It does not depend on the bar's own height (the rows' spacing,
/// align-content, is not counted), so a bar set to it keeps it. NaN before layout.</summary>
float RowsHeight()
{
float total = 0f, top = float.NaN, bottom = float.NaN;
foreach (var k in bar.Children().Where(k => k.resolvedStyle.position == Position.Relative && k.resolvedStyle.display != DisplayStyle.None).OrderBy(k => k.layout.y))
{
float t = k.layout.y - k.resolvedStyle.marginTop, b = k.layout.yMax + k.resolvedStyle.marginBottom;
if (t < bottom) { top = UnityEngine.Mathf.Min(top, t); bottom = UnityEngine.Mathf.Max(bottom, b); continue; } // the same row
if (bottom > top) total += bottom - top;
top = t; bottom = b;
}
if (bottom > top) total += bottom - top;
if (!(total > 0f)) return float.NaN; // no laid-out row yet: not just the padding, which would collapse the bar (#1089)
var s = bar.resolvedStyle;
return total + s.paddingTop + s.paddingBottom + s.borderTopWidth + s.borderBottomWidth;
}
#if UNITY_WEBGL && !UNITY_EDITOR
// The panel scales by the canvas's device pixels, so a screen pixel here is a CSS pixel: the device's pixels / the
// browser's devicePixelRatio (DevicePixelRatio.jslib).
[System.Runtime.InteropServices.DllImport("__Internal")] static extern float StatecraftDevicePixelRatio();
static float DevicePixelRatio() { var r = StatecraftDevicePixelRatio(); return r > 0f ? r : 1f; }
#else
static float DevicePixelRatio() => 1f;
#endif
/// <summary>Tight below the TightClass bounds, read from the root's laid-out size, so it follows the panel's scale
/// by itself. The text floor does not depend on it. The info panel's caps are re-fit on every call, since the
/// window can change size inside one tier.</summary>
void SetTight()
{
var r = root.worldBound;
if (float.IsNaN(r.width) || r.width <= 0f) return;
var scaled = r.width / 1920f + r.height / 1080f < 1.9f; // see TightScaledBelowHeightPx
var tight = r.height < TightBelowHeightPx && r.width < TightAndBelowWidthPx || r.width < TightBelowWidthPx
|| scaled && r.height < TightScaledBelowHeightPx;
var changed = tight != hudRoot.ClassListContains(TightClass);
hudRoot.EnableInClassList(TightClass, tight);
if (changed) ScreenNav.DisableCovered(hudRoot);
var ratioSum = r.width / 1920f + r.height / 1080f;
var scale150 = ratioSum < 1.4f;
hudRoot.EnableInClassList(Scale150Class, scale150);
// Use the existing phone breakpoint at its 100% equivalent width: desktops can enter three rows at 150% too.
hudRoot.EnableInClassList(CabinetPhone150Class, scale150 && r.width * 2f / ratioSum < ThreeRowBelowPx);
hudRoot.EnableInClassList(CabinetCardsFirstClass, tight && scale150 && r.height < TightScaledBelowHeightPx);
FitCabinet(root);
if (changed) PlaceUnderBar(); // the three-row bar's base height and the screens' margin depend on the tight class
SizeTightValues();
FitInfoPanel();
}
// The existing seat ScrollView owns both the cards and (last) the house only at 150% on short windows.
// Moving the same elements preserves the existing card instances and handlers; leaving the mode restores the UXML order.
internal static void FitCabinet(VisualElement root)
{
var hud = root.Q("root") ?? root;
var house = root.Q("cabinet-house");
var main = root.Q("cabinet-main");
var seats = root.Q<ScrollView>("cabinet-seats");
if (house == null || main == null || seats == null) return;
var first = hud.ClassListContains(CabinetCardsFirstClass);
// hierarchy.parent: a ScrollView child's logical parent is the ScrollView, never its content container, so
// comparing .parent re-added the house on every call, and its geometry callback looped the layout.
if (first && house.hierarchy.parent != seats.contentContainer)
{
seats.Add(house); seats.scrollOffset = UnityEngine.Vector2.zero;
}
else if (!first && house.hierarchy.parent != main)
{
main.Insert(0, house); seats.scrollOffset = UnityEngine.Vector2.zero;
}
var box = house.Q(className: "hemicycle-box");
if (box == null) return;
var phone150 = hud.ClassListContains(TightClass) && hud.ClassListContains(ThreeRowClass) && hud.ClassListContains(CabinetPhone150Class);
var width = box.layout.width;
var height = phone150 && width > 0f && !float.IsNaN(width)
? new StyleLength(UnityEngine.Mathf.Min(320f, width) * 168f / 320f) : new StyleLength(StyleKeyword.Null);
if (box.style.height != height) box.style.height = height;
}
/// <summary>The tight three-row bar's values and changes (#40). Statecraft.uss gives them the narrow bar's 22 px and
/// 15 px, for a phone held upright at 100%, where 22 px is 9 to 11 screen px. At 125% and 150% the same phone's
/// quarter-width meter is narrower in panel px, and the Hebrew "IL -123.4m" no longer fit it at 360x800 (TopBarTests).
/// So each takes the size that keeps it at the 12 px screen floor (FlooredTextSize of the tight bar's 16 px and 15 px),
/// no larger than the stylesheet's: 22 px and 15 px on every phone at 100%, values 17 to 21 px at 125% and 150%. The
/// changes stay 15 px at every scale since the tight bar's own changes went from 12 to 15 px (#2522, the 15 px floor).</summary>
void SizeTightValues()
{
var p = root.panel;
var on = p != null && hudRoot.ClassListContains(TightClass) && hudRoot.ClassListContains(ThreeRowClass);
var ratio = p == null ? 0f : ScreenPxPerPanelPx(p);
StyleLength Size(float tightPx, float maxPx) =>
on ? new StyleLength(UnityEngine.Mathf.Min(maxPx, FlooredTextSize(tightPx, ratio))) : new StyleLength(StyleKeyword.Null);
var value = Size(TightValuePx, TightThreeRowValuePx); var delta = Size(TightDeltaPx, TightThreeRowDeltaPx);
foreach (var m in meters)
{
foreach (var l in m.Query<Label>(className: "meter-value").ToList()) if (l.style.fontSize != value) l.style.fontSize = value;
foreach (var l in m.Query<Label>(className: "meter-delta").ToList()) if (l.style.fontSize != delta) l.style.fontSize = delta;
}
}
// Statecraft.uss .hud-tight .meter-value / .meter-delta, and the .hud-tight.hud-three-row sizes.
const float TightValuePx = 16f, TightDeltaPx = 15f, TightThreeRowValuePx = 22f, TightThreeRowDeltaPx = 15f;
/// <summary>The info panel's caps on a tight window (#40). They are set here from laid-out bounds because the USS
/// importer of the pinned Unity 6000.3 has no calc() ("Unknown function calc"). The panel's top stays
/// TightInfoGapPx below the lower of the bar and the side menu (its column, or its rail row on the three-row bar),
/// so a bar or rail the text floor grows lowers the cap with it; on the tight three-row window its right edge also
/// keeps TightThreeRowMinimapClearPx from the window's right edge, or, where that leaves it narrower than
/// TightInfoBesideMinPx, it stands TightInfoAbovePx above the minimap and its border caption, as wide as the window
/// less its insets. The empty panel's hint keeps the stylesheet's place, which already clears the minimap
/// (.hud-three-row .info-panel.info-empty). Taller content scrolls (the panel is a ScrollView). The panel is
/// bottom-anchored, and its bottom is computed here from the minimap's place, not from the panel's own bound, so a
/// re-fit after its own geometry changes sets the same values and settles at once. Off the tight HUD the caps are
/// cleared.</summary>
void FitInfoPanel()
{
if (infoPanel == null) return;
if (!hudRoot.ClassListContains(TightClass))
{
infoPanel.style.maxHeight = StyleKeyword.Null; infoPanel.style.maxWidth = StyleKeyword.Null; infoPanel.style.bottom = StyleKeyword.Null;
return;
}
if (infoPanel.resolvedStyle.display == DisplayStyle.None) return; // hidden (a screen is open): re-fit when shown
var panel = infoPanel.worldBound;
var window = hudRoot.worldBound;
var top = bar.resolvedStyle.display != DisplayStyle.None ? bar.worldBound.yMax : window.yMin;
if (railColumn != null && railColumn.resolvedStyle.display != DisplayStyle.None && railColumn.worldBound.height > 0f)
top = UnityEngine.Mathf.Max(top, railColumn.worldBound.yMax);
if (float.IsNaN(top) || float.IsNaN(panel.yMax) || !(panel.width > 0f) || !(window.width > 0f)) return; // not laid out yet: the geometry callbacks come back
var foot = panel.yMax;
var width = new StyleLength(StyleKeyword.Null);
var bottom = new StyleLength(StyleKeyword.Null);
if (hudRoot.ClassListContains(ThreeRowClass) && !infoPanel.ClassListContains("info-empty"))
{
// From the panel's stylesheet left, not its laid-out edge, so a first pass before the window settles cannot
// decide the place.
var left = window.xMin + infoPanel.resolvedStyle.left;
var beside = window.xMax - TightThreeRowMinimapClearPx - left;
if (beside >= TightInfoBesideMinPx || minimap == null || !(minimap.worldBound.height > 0f)) width = UnityEngine.Mathf.Max(0f, beside);
else
{
var above = minimap.worldBound.yMin;
if (mapLayer != null && mapLayer.resolvedStyle.display != DisplayStyle.None && mapLayer.worldBound.height > 0f)
above = UnityEngine.Mathf.Min(above, mapLayer.worldBound.yMin);
foot = above - TightInfoAbovePx;
bottom = window.yMax - foot;
// At the window's width it reaches under the right column's top: it stays under "Decision waiting" and
// the toast while they show, as the advisor sheet does (AdvisorLayout).
foreach (var e in new[] { decisionWaiting, captureWaiting, toast })
if (e != null && e.resolvedStyle.display != DisplayStyle.None && e.worldBound.height > 0f) top = UnityEngine.Mathf.Max(top, e.worldBound.yMax);
width = UnityEngine.Mathf.Max(0f, window.xMax - EdgeInsetPx - left);
}
}
infoPanel.style.bottom = bottom;
infoPanel.style.maxWidth = width;
infoPanel.style.maxHeight = UnityEngine.Mathf.Max(0f, foot - top - TightInfoGapPx);
}
/// <summary>Statecraft.uss: the panels' inset from the window's edges (.right-column's right, .info-panel's bottom).</summary>
const float EdgeInsetPx = 16f;
// Compact raised captions need their intrinsic group width, not the shrunken meter-body allocation.
// Security and its level share a row; the fit-triggered two-row tier lets that group wrap.
bool CaptionsNeedAnotherRow(float width)
{
float Sides(VisualElement e)
{
var s = e.resolvedStyle;
return s.paddingLeft + s.paddingRight + s.borderLeftWidth + s.borderRightWidth;
}
float Margins(VisualElement e) => e.resolvedStyle.marginLeft + e.resolvedStyle.marginRight;
float needed = Sides(bar);
foreach (var child in bar.Children().Where(e => e.resolvedStyle.position == Position.Relative && e.resolvedStyle.display != DisplayStyle.None))
{
if (child.name != "meters") { needed += child.layout.width + Margins(child); continue; }
needed += Sides(child) + Margins(child);
foreach (var meter in meters.Where(e => e.resolvedStyle.display != DisplayStyle.None))
{
float captions = 0f;
foreach (var label in meter.Query<Label>(className: "meter-name").ToList().Where(l => !string.IsNullOrEmpty(l.text)))
{
float font = label.resolvedStyle.fontSize;
if (!(font > 0f)) return false; // wait for the first settled geometry
captions += label.MeasureTextSize(label.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x
* smallTextSize / font + Sides(label) + Margins(label);
}
var body = meter.Q(className: "meter-body");
if (body == null) return false; // a reduced tree has no complete caption-fit budget
needed += UnityEngine.Mathf.Max(meter.resolvedStyle.minWidth.value,
captions + Sides(body) + Margins(body) + Sides(meter)) + Margins(meter);
}
}
return needed > width;
}
void SetCompact(float width)
{
if (!(width > 0)) return; // NaN before layout: wait for it
var raised = FloorRaises(width);
var tierWidth = raised ? width - FloorGrowth() : width; // the owner's text floor needs room (#624)
bar.EnableInClassList(CompactClass, tierWidth < CompactBelowPx);
hudRoot.EnableInClassList(NarrowClass, tierWidth < NarrowBelowPx || bridge.Content.UsesAttention && raised && smallTextSize > OneRowSmallMaxPx);
bar.EnableInClassList(CaptionLineClass, hudRoot.ClassListContains(NarrowClass) && !bar.ClassListContains(CompactClass));
captionFitWrap = raised && width >= TwoRowBelowPx && bar.ClassListContains(CompactClass) && CaptionsNeedAnotherRow(width);
hudRoot.EnableInClassList(TwoRowClass, width < TwoRowBelowPx || captionFitWrap);
hudRoot.EnableInClassList(ThreeRowClass, width < ThreeRowBelowPx);
StyleSmallText(raised);
PlaceUnderBar();
SetTight();
ScreenNav.DisableCovered(hudRoot); // two rows or one: what an open screen covers changes with it (#400)
}
/// <summary>End Turn's hourglass, in the button's left padding (Statecraft.uss .end-turn), painted into the button so it
/// stays a leaf sized by its text (UiIcon.Paint).</summary>
static void PaintHourglass(MeshGenerationContext m)
{
if (!m.visualElement.enabledInHierarchy) return; // no bright sign on a disabled End Turn (game over)
UiIcon.Paint(m, "hourglass", new UnityEngine.Rect(UiLanguage.Within(m.visualElement) ? m.visualElement.layout.width - 32f : 10f,
(m.visualElement.layout.height - 22f) / 2f, 22f, 22f), UiIcon.IsFocused(m.visualElement)); // the right side in Hebrew (#193)
}
/// <summary>L1 (#2340): a change's direction is not told by green and red alone, which deuteranopia cannot tell apart. A
/// small triangle in the change's own colour points up for a rise and down for a fall, in the room the stylesheet keeps
/// before the change (ChangeMarkPadPx; the right side in the mirrored Hebrew bar). Painted, as the hourglass is, because
/// the Hebrew face (Frank Ruhl Libre) has no arrow glyph. Owner ruling Q27, 4 Nov 2026:
/// https://github.com/eyalgolan/statecraft-israel/issues/2340#issuecomment-6623136558</summary>
static void PaintChange(MeshGenerationContext m)
{
var e = m.visualElement; bool up = e.ClassListContains("delta-up");
if (!up && !e.ClassListContains("delta-down")) return;
float w = UnityEngine.Mathf.Min(ChangeMarkPadPx - 2f, e.resolvedStyle.fontSize * 0.55f), h = w * 0.9f;
float cx = UiLanguage.Within(e) ? e.layout.width - 1f - w / 2f : 1f + w / 2f, cy = e.layout.height / 2f, tip = up ? -h / 2f : h / 2f;
var p = m.painter2D; // tip: the point's offset from the middle line, up (negative) for a rise; the base is opposite
p.fillColor = e.resolvedStyle.color;
p.BeginPath();
p.MoveTo(new UnityEngine.Vector2(cx - w / 2f, cy - tip)); p.LineTo(new UnityEngine.Vector2(cx + w / 2f, cy - tip)); p.LineTo(new UnityEngine.Vector2(cx, cy + tip));
p.ClosePath();
p.Fill();
}
void Set(string name, string value) => root.Q<Label>(name).text = value;
void Set(string meter, Meter m)
{
Set(meter + "-value", m.Value);
var delta = root.Q<Label>(meter + "-delta");
delta.text = m.Delta;
delta.EnableInClassList("delta-up", m.Sign > 0);
delta.EnableInClassList("delta-down", m.Sign < 0);
// The meter in words, under its caption in the UI's language (#398).
var (element, caption) = said[meter];
element.tooltip = HudModel.Spoken(text, caption, m);
}
public void Render()
{
var m = HudModel.From(bridge, text);
var attention = root.Q<Label>("attention");
attention.style.display = bridge.Content.UsesAttention ? DisplayStyle.Flex : DisplayStyle.None;
attention.pickingMode = bridge.Content.UsesAttention ? PickingMode.Position : PickingMode.Ignore;
attention.focusable = false;
attention.tooltip = "";
Set("year", m.Year); Set("turn", m.Turn); Set("date", m.Date); Set("attention", m.Attention);
Set("security-level", m.SecurityLevel);
var score = root.Q<Label>("score"); // the GDD loop only (#380): hidden when HudModel gives none
score.text = m.Score;
score.style.display = m.Score.Length == 0 ? DisplayStyle.None : DisplayStyle.Flex;
var exhausted = root.Q<Label>("exhausted"); // hidden while ExhaustedTurns is 0 (R-END-002)
exhausted.text = m.Exhausted;
var wasShown = exhausted.style.display == DisplayStyle.Flex;
exhausted.style.display = m.Exhausted.Length == 0 ? DisplayStyle.None : DisplayStyle.Flex;
if (wasShown != m.Exhausted.Length > 0) SetCompact(bar.layout.width); // the plate's raised layout follows the line (PadPlate)
Set("treasury", m.Treasury); Set("immigration", m.Immigration); Set("security", m.Security);
Set("support", m.Support); Set("standing", m.Standing); Set("fx", m.Fx);
// Social cohesion: the GDD loop only (#380), as the score; a hidden meter takes no room in the bar.
Set("cohesion", m.Cohesion);
said["cohesion"].element.style.display = m.ShowsCohesion ? DisplayStyle.Flex : DisplayStyle.None;
root.Q<Button>("end-turn").SetEnabled(bridge.State.GameOver == null);
endTurn.text = text[bridge.NeedsOrders.Count > 0 ? "hud.end_turn_needs_orders" : "hud.end_turn"];
turnBox.EnableInClassList("needs-orders", bridge.NeedsOrders.Count > 0);
// #1109: a vacant seat the player can fill lights the Cabinet disc's badge, and its tip says why.
var cabinet = root.Q<Button>("nav-cabinet"); bool vacant = bridge.Vacancies.Count > 0;
cabinet.EnableInClassList(ActionClass, vacant);
cabinet.tooltip = vacant ? text["hud.nav.cabinet_vacant"] : cabinet.text;
meterTip?.Refresh(); // an open tip follows the new words
}
}
}