Files
cruiseSimulator/Assets/Soundings/Runtime/SoundingsApp.cs

614 lines
24 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using UnityEngine;
using UnityEngine.UIElements;
namespace Soundings
{
public sealed partial class SoundingsApp : MonoBehaviour
{
private const string SaveKey = "soundings.company.v1";
private static readonly int[] HotbarPages = { 0, 3, 1, 2, 4 };
private static readonly string[] HotbarNames = { "Harbor", "Chart", "Deck plans", "Shipyard", "Logbook" };
private static FontDefinition interfaceFont;
private Company company;
private Harbor harbor;
private PassageAudio passageAudio;
private PanelSettings panel;
private VisualElement root;
private Font displayFont;
private Texture2D titleArt;
private bool title = true, guidedCareer = true, paused, fleetOpen, shipActionsOpen;
private bool? pendingStart;
private int page, deckIndex, destination = -1, bunkerTons, yardSelection;
private Facility tool = Facility.Cabin;
private string shipName = "Peregrine";
private string notice;
private bool warning;
private bool autoSmoke;
private Ship Ship => company?.ActiveShip;
private bool HarborOnScreen => underway != null || page <= 2;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void Boot()
{
var game = new GameObject("Soundings");
game.AddComponent<SoundingsApp>().Initialize();
}
private void Initialize()
{
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
autoSmoke = Array.IndexOf(Environment.GetCommandLineArgs(), "-soundings-smoke") >= 0;
Application.targetFrameRate = 60;
harbor = gameObject.AddComponent<Harbor>();
harbor.Initialize();
passageAudio = gameObject.AddComponent<PassageAudio>();
passageAudio.Initialize();
displayFont = Resources.Load<Font>("Display");
interfaceFont = FontDefinition.FromFont(Resources.Load<Font>("Interface"));
titleArt = Resources.Load<Texture2D>("Art/FlagshipTitle");
panel = ScriptableObject.CreateInstance<PanelSettings>();
panel.scaleMode = PanelScaleMode.ScaleWithScreenSize;
panel.referenceResolution = new Vector2Int(1440, 810);
panel.screenMatchMode = PanelScreenMatchMode.MatchWidthOrHeight;
panel.match = .36f;
panel.themeStyleSheet = Resources.Load<ThemeStyleSheet>("SoundingsTheme");
var document = gameObject.AddComponent<UIDocument>();
document.panelSettings = panel;
root = document.rootVisualElement;
root.style.flexGrow = 1;
root.style.unityFontDefinition = interfaceFont;
foreach (string sheet in new[] { "Soundings", "Shipwork", "Ledger", "FirstVoyageGuide", "Passage", "ServiceControls" })
{
StyleSheet stylesheet = Resources.Load<StyleSheet>(sheet);
if (stylesheet != null)
root.styleSheets.Add(stylesheet);
}
company = autoSmoke ? null : Load();
Render();
if (autoSmoke)
StartCoroutine(VisualSmoke());
}
private Company Load()
{
if (!PlayerPrefs.HasKey(SaveKey))
return null;
try
{
Company loaded = JsonUtility.FromJson<Company>(PlayerPrefs.GetString(SaveKey));
if (loaded != null && loaded.CanLoad())
{
loaded.RestoreHullDecks();
return loaded;
}
}
catch (ArgumentException exception)
{
Debug.LogWarning("Could not read the company save. " + exception.Message);
}
Notify("The company save could not be read.", true);
return null;
}
private void Save()
{
if (autoSmoke)
return;
PlayerPrefs.SetString(SaveKey, JsonUtility.ToJson(company));
PlayerPrefs.Save();
}
private void StartCompany(bool financed)
{
company = Company.Start(financed);
title = paused = fleetOpen = shipActionsOpen = false;
page = financed ? 2 : 0;
yardSelection = 1;
deckIndex = 0;
inspectedPort = 1;
selectedVoyage = 0;
ledgerRecordOffset = 0;
ledgerAccounts = false;
worldChart = false;
ResetWeatherSelection();
tool = Facility.Cabin;
systemTools = false;
shipName = "Peregrine";
pendingStart = null;
harbor.ResetView(true);
ResetItinerary();
Notify(financed && !guidedCareer ? "Choose your first hull." : null);
if (guidedCareer)
StartGuide(financed);
Save();
Render();
}
private void ResetItinerary()
{
destination = -1;
bunkerTons = 0;
if (Ship == null)
return;
foreach (Lane lane in Market.Lanes)
{
int other = lane.Other(Ship.Port);
if (other >= 0 && company.Permits[other] && Ship.HullIndex >= Market.Ports[other].MinimumHull)
{
destination = other;
break;
}
}
SetRecommendedFuel();
}
private void SetRecommendedFuel()
{
if (Ship == null)
return;
Voyage quote = company.Forecast(Ship, destination);
int preferred = Mathf.Max(10, (quote?.RequiredFuel ?? 10) - Ship.Fuel);
bunkerTons = Mathf.Clamp(preferred, 0, Ship.Tank - Ship.Fuel);
}
private void ChangePage(int next)
{
if (underway != null || paused)
return;
page = next;
fleetOpen = shipActionsOpen = false;
if (destination < 0)
ResetItinerary();
Notify(null);
Render();
}
private void Notify(string message, bool failed = false)
{
notice = message;
warning = failed;
}
private void Apply(string failure, string success)
{
Notify(failure ?? success, failure != null);
if (failure == null)
Save();
Render();
}
private void Render()
{
string focus = (root.focusController?.focusedElement as VisualElement)?.name;
SetPassageFreeLook(false);
root.Clear();
bool showingHarbor = !title && company != null && HarborOnScreen;
harbor.SetVisible(showingHarbor);
if (showingHarbor)
harbor.Show(Ship);
if (title || company == null)
DrawTitle();
else
{
RefreshGuide();
DrawShell();
if (paused)
DrawPause();
}
if (!string.IsNullOrEmpty(focus) && root.Q<VisualElement>(focus) != null)
root.schedule.Execute(() => root.Q<VisualElement>(focus)?.Focus());
}
private void DrawTitle()
{
var screen = Add(root, "game-title-screen");
var artwork = new Image
{
image = titleArt,
scaleMode = ScaleMode.ScaleAndCrop,
pickingMode = PickingMode.Ignore
};
artwork.AddToClassList("title-picture");
screen.Add(artwork);
Shade(screen, false, (0f, new Color32(9, 16, 22, 253)), (.24f, new Color32(9, 16, 22, 249)),
(.35f, new Color32(9, 16, 22, 205)),
(.61f, new Color32(9, 16, 22, 38)), (1f, new Color32(9, 16, 22, 0)));
Shade(screen, true, (0f, new Color32(6, 12, 18, 12)), (.59f, new Color32(6, 12, 18, 20)),
(1f, new Color32(6, 12, 18, 143)));
var intro = Add(screen, "title-menu");
var crest = Add(intro, "title-crest");
GameIcon(crest, "compass");
AddText(crest, "Cruise line simulator", "eyebrow title-kicker");
AddDisplay(intro, "Soundings", "title-wordmark");
if (pendingStart.HasValue)
{
AddDisplay(intro, "Replace this company?", "title-question");
AddText(intro, "A new career replaces your saved fleet and voyages.", "title-confirm-copy");
intro.Add(Action("Start a new career", () => StartCompany(pendingStart.Value), "primary title-command", "replace"));
intro.Add(Action("Keep my company", () => { pendingStart = null; Render(); }, "title-command", "keep"));
}
else
{
if (company != null)
intro.Add(Action("Continue career", () =>
{
title = false;
page = Ship == null ? 2 : 0;
ResetItinerary();
Notify(null);
Render();
}, "primary title-command", "resume"));
StartOption(intro, "Take the helm", "Used coastal ship / $135,000 cash / No debt", false);
StartOption(intro, "Start from the shipyard", "Empty fleet / $580,000 cash / $500,000 loan", true);
intro.Add(Action($"First voyage guide: {(guidedCareer ? "On" : "Off")}", () =>
{
guidedCareer = !guidedCareer;
Render();
}, "title-guide-toggle", "guide-toggle"));
}
AddNotice(intro);
if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
intro.Add(Action("Quit game", () => Application.Quit(), "title-quit", "title-quit"));
}
private void StartOption(VisualElement parent, string titleText, string description, bool financed)
{
Button option = Action("", () =>
{
if (company == null)
StartCompany(financed);
else
{
pendingStart = financed;
Render();
}
}, "career-option", financed ? "start-financed" : "start-used");
AddText(option, titleText, "career-option-name");
AddText(option, description, "career-option-balance");
parent.Add(option);
}
private void DrawShell()
{
var shell = Add(root, "game-shell");
var world = Add(shell, "harbor-viewport");
if (HarborOnScreen)
{
AddHarbor(world);
if (page == 0 || underway != null)
{
AttachCamera(world);
Shade(shell, true, (0f, new Color32(5, 13, 19, 177)), (.23f, new Color32(5, 13, 19, 4)),
(.67f, new Color32(5, 13, 19, 4)), (1f, new Color32(5, 13, 19, 231)));
}
else
Add(shell, "workspace-veil").pickingMode = PickingMode.Ignore;
}
var scene = Add(shell, "game-scene");
scene.pickingMode = PickingMode.Ignore;
scene.SetEnabled(!paused);
if (underway != null)
{
DrawUnderway(scene);
DrawServiceNavigation(scene);
}
else
{
switch (page)
{
case 0: DrawHarborScene(scene); break;
case 1: DrawDecks(scene); break;
case 2: DrawShipyard(scene); break;
case 3: DrawPorts(scene); break;
case 4: DrawFinance(scene); break;
}
}
var hud = Add(shell, "game-hud");
hud.pickingMode = PickingMode.Ignore;
hud.SetEnabled(!paused);
var hudLeft = Add(hud, "hud-left");
Button menu = Action("", () => { paused = true; Render(); }, "menu-icon", "company-menu");
menu.tooltip = "Pause menu (Esc)";
GameIcon(menu, "menu");
hudLeft.Add(menu);
AddDisplay(hudLeft, "Soundings", "hud-brand");
var instruments = Add(hud, "hud-instruments");
HeadMetric(instruments, "Day", company.Day.ToString("00"));
HeadMetric(instruments, "Reputation", company.Reputation.ToString());
HeadMetric(instruments, "Treasury", Money(company.Cash), "hud-money");
if (underway == null)
{
hudLeft.Add(Action($"Fleet {company.Fleet.Count}", () =>
{
fleetOpen = !fleetOpen;
shipActionsOpen = false;
Render();
}, "fleet-toggle", "fleet-toggle"));
DrawHotbar(shell).SetEnabled(!paused);
if (fleetOpen)
DrawFleet(shell).SetEnabled(!paused);
}
if (!paused && !fleetOpen)
DrawGuide(shell);
if (!string.IsNullOrEmpty(notice))
{
var toast = Add(shell, "game-toast");
toast.pickingMode = PickingMode.Ignore;
AddNotice(toast);
}
}
private void DrawHarborScene(VisualElement scene)
{
Ship ship = Ship;
PortSpec port = Market.Ports[ship?.Port ?? 0];
var location = Add(scene, "harbor-location");
location.pickingMode = PickingMode.Ignore;
AddText(location, "Port of", "eyebrow port-kicker");
AddDisplay(location, port.Name, "harbor-port-name");
AddText(location, $"{port.Region} / {port.Country}", "harbor-port-region");
if (ship == null)
{
var empty = Add(scene, "harbor-empty");
AddDisplay(empty, "The berth is empty", "harbor-vessel-name");
empty.Add(Action("Visit the shipyard", () => ChangePage(2), "primary helm-command", "open-yard"));
return;
}
var vessel = Add(scene, "harbor-docket");
vessel.pickingMode = PickingMode.Ignore;
AddText(vessel, $"{ship.Hull.Name} / {ship.Decks.Count} decks", "eyebrow berth-kicker");
AddDisplay(vessel, ship.Name, "harbor-vessel-name");
var details = Add(vessel, "berth-instruments");
AddText(details, $"Fuel {ship.Fuel:N0} / {ship.Tank:N0} t", "berth-value");
AddText(details, $"Condition {ship.Condition}%", "berth-value");
if (shipActionsOpen)
{
var actions = Add(vessel, "ship-action-strip");
actions.Add(Action("Refit decks", () => ChangePage(1), "", "ship-refit"));
actions.Add(Action("Overview", () => { shipActionsOpen = false; Render(); }, "", "ship-action-close"));
}
var commands = Add(scene, "helm-orders");
commands.pickingMode = PickingMode.Ignore;
Button plan = Action("Set course", OpenVoyageChart, "primary helm-command", "plan-voyage");
GameIcon(plan, "chart");
commands.Add(plan);
var camera = Add(commands, "camera-legend");
AddText(camera, "Drag to orbit / Scroll to zoom", "camera-copy");
Button reset = Action("Reset", () => harbor.ResetView(), "camera-reset", "reset-camera");
reset.tooltip = "Reset harbor camera (Home)";
camera.Add(reset);
}
private VisualElement DrawHotbar(VisualElement shell)
{
var bar = Add(shell, "game-hotbar");
var tools = Add(bar, "tool-belt");
for (int i = 0; i < HotbarPages.Length; i++)
{
int target = HotbarPages[i];
Button nav = Action("", () => ChangePage(target), page == target ? "game-tool selected" : "game-tool", "nav-" + target);
nav.tooltip = $"{HotbarNames[i]} ({i + 1})";
GameIcon(nav, target switch { 0 => "anchor", 1 => "decks", 2 => "yard", 3 => "chart", _ => "log" });
AddText(nav, HotbarNames[i], "game-tool-name");
AddText(nav, (i + 1).ToString(), "game-key");
tools.Add(nav);
}
return bar;
}
private VisualElement DrawFleet(VisualElement shell)
{
var popover = Add(shell, "fleet-manifest");
AddDisplay(popover, "Fleet", "fleet-title");
if (company.Fleet.Count == 0)
AddText(popover, "No ships in service.", "muted");
for (int i = 0; i < company.Fleet.Count; i++)
{
int selected = i;
Ship ship = company.Fleet[i];
Button entry = Action("", () =>
{
company.SelectedShip = selected;
deckIndex = 0;
fleetOpen = false;
ResetItinerary();
Apply(null, null);
}, i == company.SelectedShip ? "fleet-entry fleet-active" : "fleet-entry", "fleet-" + i);
AddText(entry, ship.Name, "fleet-name");
AddText(entry, Market.Ports[ship.Port].Name, "muted");
popover.Add(entry);
}
popover.Add(Action("Close fleet", () => { fleetOpen = false; Render(); }, "fleet-close", "fleet-close"));
return popover;
}
private void DrawPause()
{
var shade = Add(root, "pause-overlay");
var menu = Add(shade, "pause-sheet");
GameIcon(menu, "anchor");
AddDisplay(menu, "Paused", "pause-title");
menu.Add(Action("Resume", () => { paused = false; Render(); }, "primary pause-command", "resume-game"));
menu.Add(Action("Restart first voyage guide", RestartGuide, "pause-command", "restart-guide"));
if (underway == null)
{
menu.Add(Action("Title screen", () =>
{
paused = fleetOpen = shipActionsOpen = false;
title = true;
Notify(null);
Render();
}, "pause-command", "return-title"));
}
if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
menu.Add(Action("Quit to desktop", () => Application.Quit(), "pause-command", "quit-game"));
}
private void AttachCamera(VisualElement world)
{
int pointerId = -1;
bool freeLook = false;
Vector2 start = Vector2.zero, last = Vector2.zero;
bool dragging = false;
world.RegisterCallback<PointerDownEvent>(evt =>
{
if (paused || pointerId >= 0 || (evt.button != 0 && evt.button != 1))
return;
pointerId = evt.pointerId;
freeLook = underway != null && evt.button == 1 && (passageBridge || passageExploring);
SetPassageFreeLook(freeLook);
start = last = evt.localPosition;
dragging = false;
world.CapturePointer(pointerId);
evt.StopPropagation();
});
world.RegisterCallback<PointerMoveEvent>(evt =>
{
if (evt.pointerId != pointerId)
return;
Vector2 position = evt.localPosition;
if (dragging || (position - start).sqrMagnitude > 16)
{
dragging = true;
if (!freeLook)
harbor.Orbit(position - last);
else if (!passageCursorLocked)
harbor.Look(position - last);
}
last = position;
});
world.RegisterCallback<PointerUpEvent>(evt =>
{
if (evt.pointerId != pointerId)
return;
pointerId = -1;
freeLook = false;
SetPassageFreeLook(false);
world.ReleasePointer(evt.pointerId);
if (!dragging && evt.button == 0 && underway == null && Ship != null &&
harbor.IsShipAt(new Vector2(evt.localPosition.x / world.resolvedStyle.width,
1 - evt.localPosition.y / world.resolvedStyle.height)))
{
shipActionsOpen = !shipActionsOpen;
Render();
}
});
world.RegisterCallback<PointerCaptureOutEvent>(_ =>
{
pointerId = -1;
freeLook = false;
if (!passageCursorLocked || !Input.GetMouseButton(1))
SetPassageFreeLook(false);
});
world.RegisterCallback<PointerCancelEvent>(evt =>
{
if (evt.pointerId == pointerId)
world.ReleasePointer(pointerId);
});
world.RegisterCallback<WheelEvent>(evt =>
{
if (paused)
return;
harbor.Zoom(evt.delta.y);
evt.StopPropagation();
});
}
private void AddHarbor(VisualElement holder)
{
var view = new Image { scaleMode = ScaleMode.StretchToFill, pickingMode = PickingMode.Ignore };
view.AddToClassList("harbor-image");
holder.Add(view);
holder.RegisterCallback<GeometryChangedEvent>(evt =>
{
if (evt.newRect.width < 32 || evt.newRect.height < 32)
return;
float panelWidth = root.resolvedStyle.width;
float scale = panelWidth > 0 ? Screen.width / panelWidth : 1;
int width = Mathf.Clamp(Mathf.RoundToInt(evt.newRect.width * scale), 32, SystemInfo.maxTextureSize);
int height = Mathf.Clamp(Mathf.RoundToInt(evt.newRect.height * scale), 32, SystemInfo.maxTextureSize);
harbor.Resize(width, height);
view.image = harbor.Frame;
});
if (harbor.Frame != null)
view.image = harbor.Frame;
}
private void AddNotice(VisualElement parent)
{
if (!string.IsNullOrEmpty(notice))
AddText(parent, notice, warning ? "notice warning" : "notice");
}
private static void HeadMetric(VisualElement parent, string label, string value, string modifier = "")
{
var metric = Add(parent, "hud-metric");
AddText(metric, label, "eyebrow hud-label");
AddText(metric, value, "hud-value " + modifier);
}
private static void Classes(VisualElement element, string classes)
{
foreach (string item in classes.Split(' '))
if (item.Length != 0)
element.AddToClassList(item);
}
private static VisualElement Add(VisualElement parent, string classes)
{
var element = new VisualElement();
Classes(element, classes);
parent.Add(element);
return element;
}
private static Label AddText(VisualElement parent, string value, string classes)
{
var label = new Label(value) { pickingMode = PickingMode.Ignore };
label.style.unityFontDefinition = interfaceFont;
Classes(label, classes);
parent.Add(label);
return label;
}
private Label AddDisplay(VisualElement parent, string value, string classes)
{
Label label = AddText(parent, value, classes);
label.style.unityFontDefinition = FontDefinition.FromFont(displayFont);
return label;
}
private static Button Action(string text, Action clicked, string classes = "", string id = null)
{
var button = new Button(clicked) { text = text, name = id ?? text };
button.style.unityFontDefinition = interfaceFont;
Classes(button, "action " + classes);
return button;
}
private static string Money(long amount) => amount < 0 ? "−" + (-amount).ToString("C0") : amount.ToString("C0");
private void OnDestroy()
{
SetPassageFreeLook(false);
if (panel != null)
Destroy(panel);
}
}
}