Merge eureka/aetheria-release-scenario-picker: New Game is a two-pane scenario picker

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-10-23 01:44:07 +02:00
commit 48606e4253
7 changed files with 699 additions and 37 deletions

View file

@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UI;
// A render of the New Game screen as the game builds it: the real Main Menu scene's panel prototype, docked and filled
// by ScenarioPicker.Dock and ScenarioPicker.Show with every scenario group, on a plain dark background (the cloud
// backdrop is a play-mode renderer). Writes <project>/Temp/scenario-picker.png at 1920x1080, or the path after -pngOut (Unity empties Temp on exit).
//
// Unity -batchmode -projectPath <project> -executeMethod ScenarioPickerCapture.Run [-pngOut <file>] -logFile <log>
//
// Needs a GPU device; do not pass -nographics or -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
public static class ScenarioPickerCapture
{
private const int Width = 1920, Height = 1080;
public static void Run()
{
try
{
Capture();
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
// The menu's two panes built the way MainMenu.Start builds them, against the Main Menu scene.
internal static (MainMenu menu, PropertiesPanel list, PropertiesPanel detail) Build()
{
EditorSceneManager.OpenScene("Assets/Scenes/Main Menu.unity", OpenSceneMode.Single);
var menu = UnityEngine.Object.FindObjectsByType<MainMenu>(FindObjectsInactive.Include, FindObjectsSortMode.None)[0];
menu.PanelPrototype.gameObject.SetActive(false);
var list = menu.PanelPrototype.Instantiate<PropertiesPanel>();
var detail = menu.PanelPrototype.Instantiate<PropertiesPanel>();
// Edit mode runs no Awake, which is what activates each row a panel adds.
list.Awake();
detail.Awake();
ScenarioPicker.Dock(detail, list);
return (menu, list, detail);
}
internal static List<(string label, Scenario[] scenarios)> AllGroups() => new List<(string label, Scenario[] scenarios)>
{
("modes", Scenarios.Modes), ("development", Scenarios.Development), ("test arenas", Scenarios.Tests)
};
private static void Capture()
{
var (menu, list, detail) = Build();
menu.Dialog.gameObject.SetActive(false);
list.Title.text = MainMenu.TitleSubtitle("new game", "scenarios");
ScenarioPicker.Show(list, detail, AllGroups(), _ => { }, () => { }, menu.Dialog.Confirm);
list.RefreshValues();
detail.RefreshValues();
var canvas = menu.GetComponentInParent<Canvas>(true).rootCanvas;
var target = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);
var cameraObject = new GameObject("ScenarioPickerCapture camera");
var camera = cameraObject.AddComponent<Camera>();
camera.orthographic = true;
camera.orthographicSize = 5;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = new Color(.04f, .05f, .08f);
camera.cullingMask = 1 << LayerMask.NameToLayer("UI");
camera.targetTexture = target;
canvas.renderMode = RenderMode.ScreenSpaceCamera;
canvas.worldCamera = camera;
canvas.planeDistance = 10;
canvas.gameObject.SetActive(true);
Canvas.ForceUpdateCanvases();
LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform) list.transform);
LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform) detail.transform);
foreach (var text in list.transform.GetComponentsInChildren<TMPro.TMP_Text>())
text.ForceMeshUpdate();
Canvas.ForceUpdateCanvases();
list.Content.GetComponentInParent<ScrollRect>().onValueChanged.Invoke(Vector2.zero);
camera.Render();
var previous = RenderTexture.active;
RenderTexture.active = target;
var read = new Texture2D(Width, Height, TextureFormat.RGBA32, false);
read.ReadPixels(new Rect(0, 0, Width, Height), 0, 0);
RenderTexture.active = previous;
var background = read.GetPixel(0, 0);
var differing = 0;
foreach (var pixel in read.GetPixels32())
if (Mathf.Abs(pixel.r / 255f - background.r) + Mathf.Abs(pixel.g / 255f - background.g) + Mathf.Abs(pixel.b / 255f - background.b) > .05f)
differing++;
if (differing < Width * Height / 100)
throw new InvalidOperationException($"The capture is uniform: only {differing} pixels differ from the background.");
var path = Path.GetFullPath(Path.Combine(Application.dataPath, "..", "Temp", "scenario-picker.png"));
var args = Environment.GetCommandLineArgs();
var outIndex = Array.IndexOf(args, "-pngOut");
if (outIndex >= 0) path = Path.GetFullPath(args[outIndex + 1]);
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllBytes(path, read.EncodeToPNG());
Debug.Log($"[ScenarioPickerCapture] {path} ({differing} of {Width * Height} pixels differ from the background)");
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2e79f280179150e4080250c45e07cd69

View file

@ -0,0 +1,265 @@
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
// The picker's selection and keyboard rules, driven through the events the game delivers: Move and Cancel reach the
// focused Launch button through ExecuteEvents, as the Input System UI module sends them, and a click is Button.onClick.
//
// Unity -batchmode -projectPath <project> -executeMethod ScenarioPickerVerify.Run -logFile <log>
//
// Exits the Editor itself, 0 when every rule holds and 1 on the first that does not.
public static class ScenarioPickerVerify
{
private sealed class Fake : Scenario
{
private readonly uint _seed;
private readonly bool _ambient;
public Fake(string name, uint seed = 0, bool ambient = true) { Name = name; _seed = seed; _ambient = ambient; }
public override string Name { get; }
public override string Id => Name.ToLowerInvariant();
public override string Brief => $"brief of {Name}";
public override uint Seed => _seed;
public override bool Ambient => _ambient;
public override Galaxy Generate(GalaxyStage stage) => throw new NotSupportedException();
public override void Stage(ScenarioStage stage) => throw new NotSupportedException();
}
private sealed class Screen
{
public ScenarioPicker Picker;
public PropertiesPanel List, Detail;
public Button[] Rows;
public Button Back, Launch;
public readonly List<Scenario> Launched = new List<Scenario>();
public int Backs;
public Scenario[] A, B, C;
}
public static void Run()
{
try
{
SelectionFollowsClicksAndArrows();
ArrowsStopAtTheEnds();
LeftAndRightAreIgnored();
LaunchIsOnePathAndFocusClears();
CancelAndBackAreOnePath();
DetailPaneFollowsSelection();
OneGroupHasNoSectionLabel();
LaunchesOnceHoweverItIsReached();
ArrowingThroughTheRealListKeepsTheSelectionVisible();
Debug.Log("[ScenarioPickerVerify] ok");
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
private static void Require(bool condition, string what)
{
if (!condition) throw new InvalidOperationException(what);
}
private static Screen Build(bool oneGroup = false, bool real = false)
{
var (menu, list, detail) = ScenarioPickerCapture.Build();
// Build opens the scene afresh, which destroys the previous EventSystem.
var events = new GameObject("verify EventSystem").AddComponent<EventSystem>();
// Edit mode never calls OnEnable, which is what registers an EventSystem as current.
typeof(EventSystem).GetMethod("OnEnable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(events, null);
var screen = new Screen
{
List = list, Detail = detail,
A = new Scenario[] { new Fake("Alpha", 7), new Fake("Beta") },
B = new Scenario[] { new Fake("Gamma", ambient: false) },
C = new Scenario[] { new Fake("Delta"), new Fake("Echo") }
};
var groups = real ? ScenarioPickerCapture.AllGroups() : oneGroup
? new List<(string label, Scenario[] scenarios)> { ("modes", screen.A) }
: new List<(string label, Scenario[] scenarios)> { ("modes", screen.A), ("development", screen.B), ("test arenas", screen.C) };
// The menu builds a panel while it is inactive and shows it afterwards; the picker must find its scroll all the same.
if (real) list.gameObject.SetActive(false);
screen.Picker = ScenarioPicker.Show(list, detail, groups, screen.Launched.Add, () => screen.Backs++, menu.Dialog.Confirm);
var buttons = list.GetComponentsInChildren<PropertyButton>(false).Where(button => !button.transform.IsChildOf(detail.transform)).Select(button => button.Button).ToArray();
screen.Rows = buttons.Take(buttons.Length - 1).ToArray();
screen.Back = buttons.Last();
screen.Launch = detail.GetComponentsInChildren<Button>(false).Single();
if (real) { list.gameObject.SetActive(true); Layout(menu, list, detail); }
return screen;
}
// A live 1920x1080 layout, as the game has one a frame after Show; edit mode has no frames, so it is forced here.
private static void Layout(MainMenu menu, PropertiesPanel list, PropertiesPanel detail)
{
menu.Dialog.gameObject.SetActive(false);
var canvas = menu.GetComponentInParent<Canvas>(true).rootCanvas;
var camera = new GameObject("verify camera").AddComponent<Camera>();
camera.targetTexture = new RenderTexture(1920, 1080, 24);
canvas.renderMode = RenderMode.ScreenSpaceCamera;
canvas.worldCamera = camera;
canvas.planeDistance = 10;
canvas.gameObject.SetActive(true);
Canvas.ForceUpdateCanvases();
LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform) canvas.transform);
foreach (var text in list.GetComponentsInChildren<TMP_Text>()) text.ForceMeshUpdate();
Canvas.ForceUpdateCanvases();
Scroll(list).onValueChanged.Invoke(Vector2.zero);
}
private static ScrollRect Scroll(PropertiesPanel list) => list.Content.GetComponentInParent<ScrollRect>();
// Wholly inside the viewport, in world space, and not hidden by FitViewport's CanvasGroup.
private static bool Shown(Button row, ScrollRect scroll)
{
var view = new Vector3[4];
((RectTransform) scroll.viewport).GetWorldCorners(view);
var rect = new Vector3[4];
((RectTransform) row.transform).GetWorldCorners(rect);
var alpha = 1f;
for (var t = row.transform; t != null && t != scroll.content; t = t.parent)
if (t.TryGetComponent<CanvasGroup>(out var group)) alpha = Mathf.Min(alpha, group.alpha);
return rect[0].y >= view[0].y - .01f && rect[1].y <= view[1].y + .01f && alpha == 1;
}
private static void Move(Screen screen, MoveDirection direction) =>
ExecuteEvents.Execute(screen.Launch.gameObject, new AxisEventData(EventSystem.current) { moveDir = direction }, ExecuteEvents.moveHandler);
private static void Cancel(Screen screen) =>
ExecuteEvents.Execute(screen.Launch.gameObject, new BaseEventData(EventSystem.current), ExecuteEvents.cancelHandler);
private static string Selected(Screen screen) => screen.Picker.Selected.Name;
private static void SelectionFollowsClicksAndArrows()
{
var screen = Build();
Require(screen.Rows.Length == 5, $"Expected 5 scenario rows, found {screen.Rows.Length}.");
Require(Selected(screen) == "Alpha", "The first scenario is not selected on Show.");
Require(EventSystem.current.currentSelectedGameObject == screen.Launch.gameObject, "Launch is not focused on Show.");
Move(screen, MoveDirection.Down);
Require(Selected(screen) == "Beta", "Down did not select the next row.");
Move(screen, MoveDirection.Down);
Require(Selected(screen) == "Gamma", "Down did not cross into the next group.");
Move(screen, MoveDirection.Up);
Require(Selected(screen) == "Beta", "Up did not select the previous row.");
screen.Rows[3].onClick.Invoke();
Require(Selected(screen) == "Delta", "Clicking a name did not select it.");
Require(screen.Launched.Count == 0, "Clicking a name launched it.");
Require(EventSystem.current.currentSelectedGameObject == screen.Launch.gameObject, "A click on a name took focus off Launch.");
Require(screen.Rows.All(row => row.navigation.mode == Navigation.Mode.None) && screen.Launch.navigation.mode == Navigation.Mode.None
&& screen.Back.navigation.mode == Navigation.Mode.None, "A picker button still takes Unity navigation.");
var accent = screen.Rows[3].targetGraphic.color;
Require(screen.Rows.Where((row, i) => i != 3).All(row => row.targetGraphic.color != accent), "Only the selected row is drawn in the accent.");
Move(screen, MoveDirection.Up);
Require(screen.Rows[2].targetGraphic.color == accent && screen.Rows[3].targetGraphic.color != accent, "The accent did not follow the selection.");
}
private static void ArrowsStopAtTheEnds()
{
var screen = Build();
Move(screen, MoveDirection.Up);
Require(Selected(screen) == "Alpha", "Up wrapped off the first row.");
for (var i = 0; i < 10; i++) Move(screen, MoveDirection.Down);
Require(Selected(screen) == "Echo", "Down wrapped or stopped short of the last row.");
}
private static void LeftAndRightAreIgnored()
{
var screen = Build();
Move(screen, MoveDirection.Down);
Move(screen, MoveDirection.Left);
Move(screen, MoveDirection.Right);
Require(Selected(screen) == "Beta", "Left or Right moved the selection.");
}
private static void LaunchIsOnePathAndFocusClears()
{
var screen = Build();
Move(screen, MoveDirection.Down);
screen.Launch.onClick.Invoke();
Require(screen.Launched.Count == 1 && screen.Launched[0] == screen.A[1], "Launch did not launch the selected scenario once.");
Require(EventSystem.current.currentSelectedGameObject == null, "Focus survived Launch, so a second Enter could launch again.");
Require(screen.Backs == 0, "Launch went back.");
}
private static void CancelAndBackAreOnePath()
{
var screen = Build();
Cancel(screen);
Require(screen.Backs == 1 && screen.Launched.Count == 0, "Cancel did not go back exactly once.");
Require(EventSystem.current.currentSelectedGameObject == null, "Focus survived Cancel.");
screen = Build();
screen.Back.onClick.Invoke();
Require(screen.Backs == 1 && screen.Launched.Count == 0, "The Back button did not go back exactly once.");
Require(EventSystem.current.currentSelectedGameObject == null, "Focus survived Back.");
}
private static string DetailText(Screen screen)
{
screen.Detail.RefreshValues();
return string.Join("|", screen.Detail.GetComponentsInChildren<TextMeshProUGUI>(false).Select(text => text.text));
}
private static void DetailPaneFollowsSelection()
{
var screen = Build();
var first = DetailText(screen);
Require(first.Contains("brief of Alpha") && first.Contains("7") && first.Contains("on"), $"Detail does not describe Alpha: {first}");
Require(first.Contains("modes") && first.Contains("Alpha"), "Detail heading is not the group and name.");
Move(screen, MoveDirection.Down);
Move(screen, MoveDirection.Down);
var third = DetailText(screen);
Require(third.Contains("brief of Gamma") && third.Contains("new each launch") && third.Contains("off"), $"Detail does not describe Gamma: {third}");
Require(third.Contains("development") && !third.Contains("Alpha"), "Detail heading did not follow the selection.");
Require(screen.Detail.GetComponentsInChildren<Button>(false).Single() == screen.Launch, "Selecting rebuilt the Launch button.");
}
private static void OneGroupHasNoSectionLabel()
{
var many = Build();
var one = Build(oneGroup: true);
Require(many.List.Children == 5 + 3 + 2 + 1, $"Three groups should list 5 rows, 3 section labels, 2 spacers and Back, not {many.List.Children} children.");
Require(one.List.Children == 2 + 1, $"One group should list its 2 rows and Back, not {one.List.Children} children.");
}
private static void LaunchesOnceHoweverItIsReached()
{
var screen = Build();
screen.Launch.onClick.Invoke();
screen.Launch.onClick.Invoke();
ExecuteEvents.Execute(screen.Launch.gameObject, new BaseEventData(EventSystem.current), ExecuteEvents.submitHandler);
Require(screen.Launched.Count == 1, $"Launch ran {screen.Launched.Count} times after a click, a second click and Submit.");
Require(screen.Launch.navigation.mode == Navigation.Mode.None && Scroll(screen.List).verticalScrollbar.navigation.mode == Navigation.Mode.None,
"The list scrollbar or Launch takes Unity navigation.");
}
// The real scenario groups overflow the list's viewport; every row the arrows reach must end wholly visible.
private static void ArrowingThroughTheRealListKeepsTheSelectionVisible()
{
var screen = Build(real: true);
var scroll = Scroll(screen.List);
var content = (RectTransform) scroll.content;
var viewport = (RectTransform) scroll.viewport;
Require(content.rect.height > viewport.rect.height + 1, $"The real list ({content.rect.height}) does not overflow its viewport ({viewport.rect.height}); the scroll rules are unmeasured.");
Require(Shown(screen.Rows[0], scroll), "The first row is not shown on Show.");
for (var i = 1; i < screen.Rows.Length; i++)
{
Move(screen, MoveDirection.Down);
Canvas.ForceUpdateCanvases();
Require(Shown(screen.Rows[i], scroll), $"Down to row {i} ({Selected(screen)}) left it hidden or cut off.");
}
for (var i = screen.Rows.Length - 2; i >= 0; i--)
{
Move(screen, MoveDirection.Up);
Canvas.ForceUpdateCanvases();
Require(Shown(screen.Rows[i], scroll), $"Up to row {i} ({Selected(screen)}) left it hidden or cut off.");
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7ca0b5db32f745a43a8fdc67dfac2996

View file

@ -23,7 +23,7 @@ public class MainMenu : MonoBehaviour
public float FadeAlphaExponent = 2;
public float FadePositionExponent = 2;
private (PropertiesPanel panel, CanvasGroup group) _currentMenu, _nextMenu;
private (PropertiesPanel panel, CanvasGroup group, PropertiesPanel detail) _currentMenu, _nextMenu;
private bool _fadeFromRight;
private float _fadeLerp;
private bool _fading;
@ -38,10 +38,14 @@ public class MainMenu : MonoBehaviour
_panelPosition = PanelPrototype.transform.position;
var panel1 = PanelPrototype.Instantiate<PropertiesPanel>();
_currentMenu = (panel1, panel1.GetComponent<CanvasGroup>());
var detail1 = PanelPrototype.Instantiate<PropertiesPanel>();
ScenarioPicker.Dock(detail1, panel1);
_currentMenu = (panel1, panel1.GetComponent<CanvasGroup>(), detail1);
var panel2 = PanelPrototype.Instantiate<PropertiesPanel>();
_nextMenu = (panel2, panel2.GetComponent<CanvasGroup>());
var detail2 = PanelPrototype.Instantiate<PropertiesPanel>();
ScenarioPicker.Dock(detail2, panel2);
_nextMenu = (panel2, panel2.GetComponent<CanvasGroup>(), detail2);
_currentMenu.panel.gameObject.SetActive(false);
//_saveDirectory = ActionGameManager.GameDataDirectory.CreateSubdirectory("Saves");
@ -74,7 +78,7 @@ public class MainMenu : MonoBehaviour
}
}
private string TitleSubtitle(string title, string subtitle) => $"{title}\n<smallcaps><size=50%>{subtitle}";
public static string TitleSubtitle(string title, string subtitle) => $"{title}\n<smallcaps><size=50%>{subtitle}";
private void Fade(bool fromRight)
{
@ -87,10 +91,18 @@ public class MainMenu : MonoBehaviour
private static bool _exclusionsShown;
private void ShowMain()
// Starts the next screen on an empty panel with a title and its scenario detail pane hidden and empty.
private void Next(string title)
{
_nextMenu.panel.Clear();
_nextMenu.panel.Title.text = TitleSubtitle("aetheria", "terminus");
_nextMenu.panel.Title.text = title;
_nextMenu.detail.Clear();
_nextMenu.detail.gameObject.SetActive(false);
}
private void ShowMain()
{
Next(TitleSubtitle("aetheria", "terminus"));
if (ActionGameManager.CurrentGalaxy == null)
{
// No run is live: at the title, after death, or after a new run failed to start. A saved run exists only as
@ -131,31 +143,18 @@ public class MainMenu : MonoBehaviour
// to set up a run and the test arenas are listed only in editor and development builds.
private void ShowScenarios()
{
_nextMenu.panel.Clear();
_nextMenu.panel.Title.text = TitleSubtitle("new game", "scenarios");
AddScenarios(Scenarios.Modes);
Next(TitleSubtitle("new game", "scenarios"));
var groups = new List<(string label, Scenario[] scenarios)> { ("modes", Scenarios.Modes) };
if (Debug.isDebugBuild)
{
_nextMenu.panel.AddSection("development");
AddScenarios(Scenarios.Development);
_nextMenu.panel.AddSection("test arenas");
AddScenarios(Scenarios.Tests);
groups.Add(("development", Scenarios.Development));
groups.Add(("test arenas", Scenarios.Tests));
}
_nextMenu.panel.AddButton("Back",
() =>
{
ShowMain();
Fade(false);
});
}
private void AddScenarios(IEnumerable<Scenario> scenarios)
{
foreach (var scenario in scenarios)
ScenarioPicker.Show(_nextMenu.panel, _nextMenu.detail, groups, Launch, () =>
{
_nextMenu.panel.AddButton(scenario.Name, () => Launch(scenario));
_nextMenu.panel.AddProperty(() => scenario.Brief);
}
ShowMain();
Fade(false);
}, Dialog.Confirm);
}
// The only way into a new run: generates the scenario's galaxy off the main thread and enters the game, where
@ -263,8 +262,7 @@ public class MainMenu : MonoBehaviour
private void ShowSettings()
{
_nextMenu.panel.Clear();
_nextMenu.panel.Title.text = "settings";
Next("settings");
_nextMenu.panel.AddButton("Gameplay",
() =>
{
@ -299,8 +297,7 @@ public class MainMenu : MonoBehaviour
private void ShowGameplaySettings()
{
_nextMenu.panel.Clear();
_nextMenu.panel.Title.text = TitleSubtitle("gameplay", "settings");
Next(TitleSubtitle("gameplay", "settings"));
_nextMenu.panel.AddField("Name",
() => ActionGameManager.PlayerSettings.Name,
s => ActionGameManager.PlayerSettings.Name = s);
@ -322,8 +319,7 @@ public class MainMenu : MonoBehaviour
private void ShowGraphicsSettings()
{
_nextMenu.panel.Clear();
_nextMenu.panel.Title.text = TitleSubtitle("graphics", "settings");
Next(TitleSubtitle("graphics", "settings"));
_nextMenu.panel.AddField("Nebula Quality",
() => (int)ActionGameManager.PlayerSettings.GraphicsSettings.NebulaQuality,
i =>
@ -347,8 +343,7 @@ public class MainMenu : MonoBehaviour
private void ShowInputSettings()
{
_nextMenu.panel.Clear();
_nextMenu.panel.Title.text = TitleSubtitle("input", "settings");
Next(TitleSubtitle("input", "settings"));
_nextMenu.panel.AddButton("Back",
() =>
{
@ -359,8 +354,7 @@ public class MainMenu : MonoBehaviour
private void ShowAudioSettings()
{
_nextMenu.panel.Clear();
_nextMenu.panel.Title.text = TitleSubtitle("audio", "settings");
Next(TitleSubtitle("audio", "settings"));
_nextMenu.panel.AddButton("Back",
() =>
{

View file

@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using UniRx;
using UniRx.Triggers;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.UI;
using UnityEngine.UI;
// The New Game screen: scenario names on the left pane by group, the selected scenario's brief, seed and ambient on a
// docked right pane, one Launch. This class owns which scenario is selected (one index into the rows it built);
// everything the screen shows about a scenario, and what Launch and Enter launch, reads that index. Keys arrive only as
// Input System UI events on the focused Launch button, so Enter and a mouse click are the same Button.onClick.
public sealed class ScenarioPicker
{
private readonly List<Scenario> _scenarios = new List<Scenario>();
private readonly List<string> _groupLabels = new List<string>();
private readonly List<Button> _rows = new List<Button>();
private readonly List<ColorBlock> _rowColors = new List<ColorBlock>();
private readonly List<Color> _rowFills = new List<Color>();
private readonly PropertiesPanel _list;
private readonly PropertiesPanel _detail;
private readonly Action<Scenario> _launch;
private readonly Action _back;
private Button _launchButton;
private ScrollRect _scroll;
private UnityAction<Vector2> _fit;
private static readonly Color Accent = new Color(1, .4458f, .05f);
private int _selected;
private bool _launched;
private bool _restoreDeselect;
private ScenarioPicker(PropertiesPanel list, PropertiesPanel detail, Action<Scenario> launch, Action back)
{
_list = list;
_detail = detail;
_launch = launch;
_back = back;
}
// The scenario the detail pane describes and Launch will launch.
public Scenario Selected => _scenarios[_selected];
// Parks the detail pane beside the list pane: a child of it, outside its layout, hidden until Show.
public static void Dock(PropertiesPanel detail, PropertiesPanel list, float width = 480, float gap = 128)
{
var rect = (RectTransform) detail.transform;
rect.SetParent(list.transform, false);
detail.gameObject.AddComponent<LayoutElement>().ignoreLayout = true;
rect.anchorMin = new Vector2(1, 0);
rect.anchorMax = new Vector2(1, 1);
rect.pivot = new Vector2(0, .5f);
rect.anchoredPosition = new Vector2(gap, 0);
rect.sizeDelta = new Vector2(width, 0);
detail.gameObject.SetActive(false);
}
private static readonly Color Muted = new Color(1, 1, 1, .55f);
// Builds both panes for the groups, shows the detail pane, selects the first scenario and focuses Launch. The
// launchChrome is a button of the menu's own styling, cloned for Launch.
public static ScenarioPicker Show(PropertiesPanel list, PropertiesPanel detail,
IReadOnlyList<(string label, Scenario[] scenarios)> groups, Action<Scenario> launch, Action back, Button launchChrome)
{
var picker = new ScenarioPicker(list, detail, launch, back);
foreach (var group in groups)
{
if (groups.Count > 1)
{
if (picker._scenarios.Count > 0) list.AddSpacer();
var header = list.AddSection(group.label);
header.GetComponent<LayoutElement>().preferredHeight = 26;
var text = header.GetComponentInChildren<TMP_Text>();
text.fontSize = 14;
text.fontStyle = FontStyles.SmallCaps;
text.alignment = TextAlignmentOptions.Left;
text.color = Muted;
}
foreach (var scenario in group.scenarios)
{
var index = picker._scenarios.Count;
picker._scenarios.Add(scenario);
picker._groupLabels.Add(group.label);
var row = list.AddButton(scenario.Name, () => picker.Select(index));
picker.Track(row.Button);
picker._rows.Add(row.Button);
picker._rowColors.Add(row.Button.colors);
picker._rowFills.Add(row.Button.targetGraphic.color);
}
}
picker.Track(list.AddButton("Back", picker.Back).Button);
detail.Clear();
detail.gameObject.SetActive(true);
// The pane's own title is an invisible copy of the page title, so both panes stack their content from the same
// line; the scenario is headed by its group label and name in the body.
detail.Title.text = list.Title.text;
detail.Title.color = Color.clear;
Style(detail.AddProperty(() => $"<smallcaps>{picker._groupLabels[picker._selected]}"), 14, Muted);
Style(detail.AddProperty(() => picker.Selected.Name), 30, Color.white);
detail.AddProperty(() => $"<margin-right=20%>{picker.Selected.Brief}");
detail.AddSpacer();
detail.AddProperty(() => $"<color=#ffffff8c>Seed</color><pos=22%>{(picker.Selected.Seed == 0 ? "new each launch" : picker.Selected.Seed.ToString())}");
detail.AddProperty(() => $"<color=#ffffff8c>Ambient</color><pos=22%>{(picker.Selected.Ambient ? "on" : "off")}");
detail.AddSpacer();
picker._launchButton = AddLaunch(detail, launchChrome, picker.Activate);
picker.Track(picker._launchButton);
picker._launchButton.OnMoveAsObservable().Subscribe(move =>
{
if (move.moveDir == MoveDirection.Up) picker.Step(-1);
else if (move.moveDir == MoveDirection.Down) picker.Step(1);
});
picker._launchButton.OnCancelAsObservable().Subscribe(_ => picker.Back());
picker.StyleScrollbars();
picker.HoldFocus();
picker.Select(0);
// Layout is not live until the frame after Show; edit mode has no frames.
if (Application.isPlaying) Observable.NextFrame().Subscribe(_ => picker.FitViewport());
return picker;
}
private static void Style(Property property, float size, Color color)
{
property.Label.enableAutoSizing = false;
property.Label.fontSize = size;
property.Label.color = color;
}
// Launch is a clone of the menu's own chrome button, filled with the accent so it reads as the default action. The
// clone lives under a spacer row, so the pane's Clear destroys it.
private static Button AddLaunch(PropertiesPanel detail, Button chrome, Action onClick)
{
var holder = detail.AddSpacer();
holder.GetComponent<LayoutElement>().preferredHeight = 40;
var button = UnityEngine.Object.Instantiate(chrome, holder, false);
var rect = (RectTransform) button.transform;
rect.anchorMin = Vector2.zero;
rect.anchorMax = new Vector2(0, 1);
rect.pivot = new Vector2(0, .5f);
rect.anchoredPosition = Vector2.zero;
rect.sizeDelta = new Vector2(220, 0);
// The visible chrome is the button's Fill child, which the button's own layout group sizes to its text and
// centres; with the group off, Fill stretches to the button.
button.GetComponent<LayoutGroup>().enabled = false;
var fill = button.targetGraphic.rectTransform;
fill.anchorMin = Vector2.zero;
fill.anchorMax = Vector2.one;
fill.offsetMin = fill.offsetMax = Vector2.zero;
button.gameObject.SetActive(true);
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() => onClick());
button.targetGraphic.color = Accent;
button.GetComponentInChildren<TMP_Text>().text = "Launch";
return button;
}
// The detail pane needs no scrollbar; the list's gets a visible track, so its handle reads as a scrollbar rather
// than a bar that stops partway.
private void StyleScrollbars()
{
var detailScroll = ScrollOf(_detail);
if (detailScroll != null && detailScroll.verticalScrollbar != null) detailScroll.verticalScrollbar.gameObject.SetActive(false);
_scroll = ScrollOf(_list);
if (_scroll == null) return;
if (_scroll.verticalScrollbar != null)
{
if (!_scroll.verticalScrollbar.TryGetComponent<Image>(out var track)) track = _scroll.verticalScrollbar.gameObject.AddComponent<Image>();
track.color = new Color(Accent.r, Accent.g, Accent.b, .2f);
// A click on the bar selects it and takes focus off Launch, which would silence the arrows.
_scroll.verticalScrollbar.navigation = new Navigation { mode = Navigation.Mode.None };
}
_scroll.onValueChanged.RemoveAllListeners();
_fit = _ => FitViewport();
_scroll.onValueChanged.AddListener(_fit);
}
// The panel is inactive until the menu shows it, which is after Show builds it; an inactive ScrollRect still counts.
private static ScrollRect ScrollOf(PropertiesPanel panel) => (panel.Content ?? panel.transform).GetComponentInParent<ScrollRect>(true);
// Hides every list entry the viewport only partly shows, so the list ends on a whole row instead of slicing text.
private void FitViewport()
{
if (_scroll == null || _scroll.content == null) return;
if (_rows[0] == null)
{
_scroll.onValueChanged.RemoveListener(_fit);
return;
}
var (low, high) = ViewSpan(_scroll);
foreach (RectTransform entry in _list.Content ?? _list.transform)
{
var bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(_scroll.content, entry);
var whole = bounds.min.y >= low - .5f && bounds.max.y <= high + .5f;
if (!entry.TryGetComponent<CanvasGroup>(out var group)) group = entry.gameObject.AddComponent<CanvasGroup>();
group.alpha = whole ? 1 : 0;
group.blocksRaycasts = whole;
}
}
// The viewport's vertical extent in content space. CalculateRelativeRectTransformBounds cannot give it: it also
// folds in the rects of the viewport's children, which makes the content's own bounds the answer.
private static (float low, float high) ViewSpan(ScrollRect scroll)
{
var view = scroll.viewport != null ? scroll.viewport : (RectTransform) scroll.transform;
var rect = view.rect;
var low = scroll.content.InverseTransformPoint(view.TransformPoint(new Vector3(0, rect.yMin))).y;
var high = scroll.content.InverseTransformPoint(view.TransformPoint(new Vector3(0, rect.yMax))).y;
return (Mathf.Min(low, high), Mathf.Max(low, high));
}
// Takes a button out of Unity's navigation so a click never moves focus and Move never walks automatic navigation.
private void Track(Button button) => button.navigation = new Navigation { mode = Navigation.Mode.None };
// Moves the selection one row, stopping at either end.
private void Step(int delta) => Select(_selected + delta);
// Makes one row the selection: clamps the index, redraws the highlight, and returns focus to Launch.
private void Select(int index)
{
_selected = Mathf.Clamp(index, 0, _scenarios.Count - 1);
for (var i = 0; i < _rows.Count; i++)
{
// The prefab tint barely moves the row colour, so the selected row is drawn in the menu accent.
var colors = _rowColors[i];
if (i == _selected) colors.normalColor = Color.white;
_rows[i].colors = colors;
_rows[i].targetGraphic.color = i == _selected ? Accent : _rowFills[i];
}
Focus(_launchButton.gameObject);
Reveal((RectTransform) _rows[_selected].transform);
}
// Scrolls the list pane just far enough that the selected row is inside its viewport.
private void Reveal(RectTransform row)
{
var scroll = _scroll;
if (scroll == null || scroll.content == null) return;
var (low, high) = ViewSpan(scroll);
var rowBounds = RectTransformUtility.CalculateRelativeRectTransformBounds(scroll.content, row);
var shift = rowBounds.max.y > high ? rowBounds.max.y - high
: rowBounds.min.y < low ? rowBounds.min.y - low : 0;
// Content moves against the row: a row above the viewport needs the content to move down, and the reverse.
scroll.content.anchoredPosition -= new Vector2(0, shift);
if (shift != 0) FitViewport();
}
// Launches the selection, once: Enter, Submit and a mouse click all arrive here, and nothing launches again until
// the picker is shown afresh, however long the menu takes to fade out.
private void Activate()
{
if (_launched) return;
_launched = true;
Focus(null);
ReleaseFocus();
_launch(Selected);
}
// Leaves the screen; the same path for the Back button and Cancel.
private void Back()
{
Focus(null);
ReleaseFocus();
_back();
}
// While the picker is up, a click on empty space must not drop focus from Launch, or the arrows and Enter go dead.
// The input module's flag is scene-wide, so the picker takes it for its own lifetime and gives it back on leaving.
private void HoldFocus()
{
if (EventSystem.current == null || !(EventSystem.current.currentInputModule is InputSystemUIInputModule module) || !module.deselectOnBackgroundClick) return;
module.deselectOnBackgroundClick = false;
_restoreDeselect = true;
}
private void ReleaseFocus()
{
if (!_restoreDeselect) return;
_restoreDeselect = false;
if (EventSystem.current != null && EventSystem.current.currentInputModule is InputSystemUIInputModule module) module.deselectOnBackgroundClick = true;
}
private static void Focus(GameObject target)
{
if (EventSystem.current != null) EventSystem.current.SetSelectedGameObject(target);
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 252d53300699b374db95fe7d7fcfd9b8