3993 lines
169 KiB
C#
3993 lines
169 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using KernelPanic.Combat;
|
||
using KernelPanic.Core;
|
||
using KernelPanic.Data;
|
||
using KernelPanic.Meta;
|
||
using KernelPanic.Run;
|
||
using UnityEngine;
|
||
using UnityEngine.UIElements;
|
||
|
||
namespace KernelPanic.UI
|
||
{
|
||
/// <summary>
|
||
/// Runtime-built GameScene combat UI. Intent icons use a compact terminal vocabulary:
|
||
/// ! attack/status attack/segfault, # defend, + buff, * special, ? hidden/rootkit,
|
||
/// ~ reviving/race link, : split, @ countdown, . orphan.
|
||
/// </summary>
|
||
[RequireComponent(typeof(UIDocument))]
|
||
[RequireComponent(typeof(RunManager))]
|
||
[RequireComponent(typeof(CombatManager))]
|
||
public sealed class CombatSceneController : MonoBehaviour
|
||
{
|
||
private const string StyleResourcePath = "CombatScene";
|
||
private const string SharedScrollbarStyleResourcePath = "TerminalScrollbars";
|
||
private const string SharedRarityStyleResourcePath = "RarityPresentation";
|
||
private const int MaxFeedbackElements = 42;
|
||
private const string FilledCycle = "●";
|
||
private const string EmptyCycle = "○";
|
||
|
||
[SerializeField] private DistroDatabase distroDatabase;
|
||
[SerializeField] private CardDatabase cardDatabase;
|
||
[SerializeField] private LanguageDeckDatabase languageDeckDatabase;
|
||
|
||
private UIDocument _document;
|
||
private RunManager _runManager;
|
||
private CombatManager _combatManager;
|
||
private SaveService _saveService;
|
||
private VisualElement _root;
|
||
private VisualElement _statusBar;
|
||
private Label _waveLabel;
|
||
private Label _phaseLabel;
|
||
private Label _entropyLabel;
|
||
private Label _bitsLabel;
|
||
private Label _bandwidthLabel;
|
||
private Label _rootCreditsLabel;
|
||
private Label _seedLabel;
|
||
private VisualElement _playerPanel;
|
||
private VisualElement _interpreterStrip;
|
||
private VisualElement _lazyStackPile;
|
||
private VisualElement _tokenArea;
|
||
private VisualElement _enemyRow;
|
||
private VisualElement _handRow;
|
||
private VisualElement _turnResourceGrid;
|
||
private VisualElement _packageReadinessStrip;
|
||
private Label _packageActivationLabel;
|
||
private readonly Dictionary<string, VisualElement> _packageReadinessChips = new();
|
||
private int _packageActivationVersion;
|
||
private int _packageActivationFrame = -1;
|
||
private readonly Queue<string> _packageActivationMessages = new();
|
||
private VisualElement _journalEntries;
|
||
private Foldout _journal;
|
||
private Button _endTurnButton;
|
||
private Button _prefetchButton;
|
||
private Label _targetHint;
|
||
private Label _schedulerActivity;
|
||
private ScrollView _handScroll;
|
||
private ScrollView _journalScroll;
|
||
private ExecutionTrackView _queueView;
|
||
private ExecutionTrackView _stackView;
|
||
private ExecutionPreviewView _executionPreview;
|
||
private Label _encounterBrief;
|
||
private float _journalStartedAt;
|
||
private readonly Dictionary<EnemyInstance, Button> _enemyCards = new();
|
||
private readonly HashSet<EnemyInstance> _restartingEnemies = new();
|
||
private readonly HashSet<IVisualElementScheduledItem> _scheduledFeedback = new();
|
||
private readonly Queue<string> _recentLog = new();
|
||
private readonly Dictionary<CardInstance, VisualElement> _retainedHandCards = new();
|
||
private int _executionSequence;
|
||
private Button _surrenderButton;
|
||
private Button _surrenderCancelButton;
|
||
private Label _surrenderConfirmLabel;
|
||
private VisualElement _feedbackLayer;
|
||
private VisualElement _damageVignette;
|
||
private VisualElement _overlay;
|
||
private Color _distroAccent;
|
||
private readonly Dictionary<CombatantState, VisualElement> _combatantElements = new();
|
||
private readonly Dictionary<CardInstance, VisualElement> _handCardElements = new();
|
||
private readonly Dictionary<CardInstance, VisualElement> _queueChipElements = new();
|
||
private readonly Dictionary<CardInstance, VisualElement> _stackChipElements = new();
|
||
private readonly Dictionary<CombatantState, int> _previousUptime = new();
|
||
private readonly Dictionary<CombatantState, int> _previousShield = new();
|
||
private readonly Dictionary<VisualElement, int> _feedbackBeatVersions = new();
|
||
private readonly Dictionary<CombatantState, Rect> _lastCombatantFeedbackRects = new();
|
||
private readonly Dictionary<CombatantState, int> _heldDeathUptime = new();
|
||
private readonly HashSet<CombatantState> _deathBeatStartedCombatants = new();
|
||
private readonly HashSet<CombatantState> _deathFeedbackObserved = new();
|
||
private readonly HashSet<CombatantState> _visuallyRemovedCombatants = new();
|
||
private int _feedbackCascadeIndex;
|
||
private int _feedbackBeatVersion;
|
||
private int _combatBeatCursorMs;
|
||
private int _combatBeatCursorVersion;
|
||
private int _rootShakeVersion;
|
||
private int _hitStopVersion;
|
||
private int _lastHitStopFrame = -1;
|
||
private Label _archBtwCounterLabel;
|
||
private VisualElement _fedoraRiskFillElement;
|
||
private Label _fedoraRiskValueLabel;
|
||
private bool _pendingFedoraPayoff;
|
||
private bool _surrenderConfirming;
|
||
private bool _runEndedBySurrender;
|
||
private bool _runEndOverlayPresented;
|
||
private bool _playerFeedbackAnchorTracked;
|
||
private FirstBattleGuide _firstBattleGuide;
|
||
private TutorialFlow _tutorial;
|
||
private SaveData _lastKnownSave;
|
||
private string _saveError;
|
||
private string _checkpointError;
|
||
private bool _routeSelectionOpen;
|
||
private bool _routeEventOpen;
|
||
private DailyQuestTracker _dailyQuestTracker;
|
||
private IVisualElementScheduledItem _dailyQuestSaveSchedule;
|
||
private CombatRunTelemetry _runTelemetry;
|
||
private RunHistoryEntry _runHistoryEntry;
|
||
private bool _pileInspectorOpen;
|
||
private string _inspectedPile;
|
||
|
||
private void Awake()
|
||
{
|
||
_document = GetComponent<UIDocument>();
|
||
_runManager = GetComponent<RunManager>();
|
||
_combatManager = GetComponent<CombatManager>();
|
||
if (Application.isPlaying && GetComponent<CombatAudio>() == null) gameObject.AddComponent<CombatAudio>();
|
||
_saveService = new SaveService();
|
||
_root = _document.rootVisualElement;
|
||
LoadStyles();
|
||
TerminalTheme.Attach(_root);
|
||
ApplyTerminalFont();
|
||
BuildLayout();
|
||
|
||
_root.AddToClassList("scene-fade-hidden");
|
||
_root.schedule.Execute(() => _root.RemoveFromClassList("scene-fade-hidden")).StartingIn(0);
|
||
}
|
||
|
||
private void ApplyTerminalFont()
|
||
{
|
||
var font = TerminalFontResolver.Resolve(null);
|
||
if (font != null)
|
||
{
|
||
_root.style.unityFontDefinition = new StyleFontDefinition(font);
|
||
}
|
||
}
|
||
|
||
private void OnEnable()
|
||
{
|
||
_runTelemetry?.Dispose();
|
||
_runTelemetry = new CombatRunTelemetry(() => _combatManager.PlayerState, DescribeDamageSource)
|
||
{
|
||
SurrenderRequested = () => _combatManager.RunEndedBySurrender
|
||
};
|
||
_queueView ??= new ExecutionTrackView(_interpreterStrip, false);
|
||
_stackView ??= new ExecutionTrackView(_lazyStackPile, true);
|
||
_root?.EnableInClassList("reduced-motion", UIPreferences.ReducedMotion);
|
||
_combatManager.StateChanged += Refresh;
|
||
_combatManager.CombatLog += HandleCombatLog;
|
||
_combatManager.PackageActivated += HandlePackageActivated;
|
||
_runManager.RepositoryChanged += Refresh;
|
||
GameEvents.CardPlayed += HandleCardPlayed;
|
||
GameEvents.CardResolving += HandleCardResolving;
|
||
GameEvents.CardResolved += HandleCardResolved;
|
||
GameEvents.PhaseChanged += HandlePhaseChanged;
|
||
GameEvents.DamageDealt += HandleDamageDealt;
|
||
GameEvents.OverflowDamageTravel += HandleOverflowDamageTravel;
|
||
GameEvents.CombatantDefeated += HandleCombatantDefeated;
|
||
GameEvents.DeathSpawnedEnemy += HandleDeathSpawnedEnemy;
|
||
GameEvents.EnemyWouldAct += HandleEnemyWouldAct;
|
||
GameEvents.PlayerDamaged += HandlePlayerDamaged;
|
||
GameEvents.StatusApplied += HandleStatusApplied;
|
||
GameEvents.StatusExpired += HandleStatusEnded;
|
||
GameEvents.StatusCleansed += HandleStatusEnded;
|
||
GameEvents.UbuntuAptUpdatePeeked += HandleUbuntuAptUpdatePeeked;
|
||
GameEvents.FedoraBleedingEdgeTriggered += HandleFedoraBleedingEdgeTriggered;
|
||
GameEvents.ArchBtwTurnEnded += HandleArchBtwTurnEnded;
|
||
_root?.RegisterCallback<KeyDownEvent>(HandleKeyDown);
|
||
}
|
||
|
||
private void Start()
|
||
{
|
||
bool resuming = RunContext.TryTakeResume(out ResolvedRunCheckpoint resume);
|
||
RunConfig config = resume?.Config;
|
||
if (!resuming && !TryBuildRunConfig(out config))
|
||
{
|
||
HandleMissingRunConfig();
|
||
return;
|
||
}
|
||
|
||
_distroAccent = config.Distro == null ? Color.white : config.Distro.AccentColor;
|
||
TerminalTheme.SetDistro(_root, config.Distro);
|
||
_combatManager.SetGeneratedCardPool(BuildGeneratedCardPool());
|
||
if (!config.IsTutorial)
|
||
{
|
||
_dailyQuestTracker = new DailyQuestTracker(_saveService,
|
||
() => _runManager.CurrentConfig != null && !_runManager.IsSuspended,
|
||
() => _combatManager.PlayerState);
|
||
var notice = TerminalLayout.BodyText("", "DailyQuestSaveNotice");
|
||
notice.style.display = DisplayStyle.None;
|
||
_root.Insert(1, notice);
|
||
_dailyQuestSaveSchedule = _root.schedule.Execute(() =>
|
||
{
|
||
bool saved = _dailyQuestTracker.Flush();
|
||
notice.text = saved ? "" : "Daily quest progress could not be saved. Retrying...";
|
||
notice.style.display = saved ? DisplayStyle.None : DisplayStyle.Flex;
|
||
}).Every(2000);
|
||
}
|
||
if (config.IsTutorial)
|
||
{
|
||
_tutorial = new TutorialFlow(_overlay, _runManager, _combatManager, cardDatabase, languageDeckDatabase,
|
||
_saveService, config, () => SceneLoader.LoadMainMenu(_root));
|
||
_tutorial.SetRefresh(Refresh);
|
||
}
|
||
if (resuming)
|
||
{
|
||
try
|
||
{
|
||
if (!config.IsTutorial) RunCheckpointService.Consume(_saveService, resume);
|
||
_runManager.RestoreCheckpoint(resume);
|
||
_combatManager.RestoreBoundaryState(config, resume.Snapshot.combat);
|
||
_tutorial?.ResumeSecondWave();
|
||
}
|
||
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
|
||
{
|
||
_overlay.Clear();
|
||
_overlay.style.display = DisplayStyle.Flex;
|
||
_overlay.Add(TerminalLayout.BodyText("Resume could not complete: " + ex.Message));
|
||
_overlay.Add(new Button(() => SceneLoader.LoadMainMenu(_root)) { text = "return to menu" });
|
||
return;
|
||
}
|
||
}
|
||
else _runManager.StartRun(config);
|
||
Refresh();
|
||
}
|
||
|
||
private IReadOnlyList<CardDefinition> BuildGeneratedCardPool()
|
||
{
|
||
List<CardDefinition> cards = new();
|
||
if (cardDatabase != null)
|
||
{
|
||
cards.AddRange(cardDatabase.AllCards);
|
||
return cards;
|
||
}
|
||
|
||
if (languageDeckDatabase == null)
|
||
{
|
||
return cards;
|
||
}
|
||
|
||
AddLanguageDeck(Language.Python, cards);
|
||
return cards;
|
||
}
|
||
|
||
private void OnDisable()
|
||
{
|
||
Time.timeScale = 1f;
|
||
_dailyQuestSaveSchedule?.Pause();
|
||
_dailyQuestTracker?.Dispose();
|
||
_dailyQuestTracker = null;
|
||
SettleRunRewardsIfNeeded();
|
||
_tutorial?.Dispose();
|
||
_combatManager.StateChanged -= Refresh;
|
||
_combatManager.CombatLog -= HandleCombatLog;
|
||
_combatManager.PackageActivated -= HandlePackageActivated;
|
||
_runManager.RepositoryChanged -= Refresh;
|
||
GameEvents.CardPlayed -= HandleCardPlayed;
|
||
GameEvents.CardResolving -= HandleCardResolving;
|
||
GameEvents.CardResolved -= HandleCardResolved;
|
||
GameEvents.PhaseChanged -= HandlePhaseChanged;
|
||
GameEvents.DamageDealt -= HandleDamageDealt;
|
||
GameEvents.OverflowDamageTravel -= HandleOverflowDamageTravel;
|
||
GameEvents.CombatantDefeated -= HandleCombatantDefeated;
|
||
GameEvents.DeathSpawnedEnemy -= HandleDeathSpawnedEnemy;
|
||
GameEvents.EnemyWouldAct -= HandleEnemyWouldAct;
|
||
GameEvents.PlayerDamaged -= HandlePlayerDamaged;
|
||
GameEvents.StatusApplied -= HandleStatusApplied;
|
||
GameEvents.StatusExpired -= HandleStatusEnded;
|
||
GameEvents.StatusCleansed -= HandleStatusEnded;
|
||
GameEvents.UbuntuAptUpdatePeeked -= HandleUbuntuAptUpdatePeeked;
|
||
GameEvents.FedoraBleedingEdgeTriggered -= HandleFedoraBleedingEdgeTriggered;
|
||
GameEvents.ArchBtwTurnEnded -= HandleArchBtwTurnEnded;
|
||
_root?.UnregisterCallback<KeyDownEvent>(HandleKeyDown);
|
||
foreach (var scheduled in _scheduledFeedback) scheduled.Pause();
|
||
_scheduledFeedback.Clear();
|
||
_queueView?.Dispose();
|
||
_stackView?.Dispose();
|
||
_queueView = null;
|
||
_stackView = null;
|
||
_feedbackLayer?.Clear();
|
||
_runTelemetry?.Dispose();
|
||
_runTelemetry = null;
|
||
}
|
||
|
||
private void HandleKeyDown(KeyDownEvent evt)
|
||
{
|
||
if (_tutorial?.Guide.Active == true)
|
||
{
|
||
if (evt.keyCode == KeyCode.E && _tutorial.Guide.CanEndTurn) _combatManager.EndPlayerTurn();
|
||
evt.StopPropagation(); return;
|
||
}
|
||
if (_executionPreview?.IsOpen == true)
|
||
{
|
||
if (evt.keyCode == KeyCode.Escape) _executionPreview.Close();
|
||
evt.StopPropagation();
|
||
return;
|
||
}
|
||
if (_pileInspectorOpen)
|
||
{
|
||
if (evt.keyCode == KeyCode.Escape) ClosePileInspector();
|
||
evt.StopPropagation();
|
||
return;
|
||
}
|
||
if (!_surrenderConfirming)
|
||
{
|
||
if (_overlay.resolvedStyle.display != DisplayStyle.None) return;
|
||
if (evt.keyCode == KeyCode.E && _endTurnButton.enabledSelf)
|
||
{
|
||
_combatManager.EndPlayerTurn();
|
||
evt.StopPropagation();
|
||
}
|
||
return;
|
||
}
|
||
|
||
// Enter belongs to the focused Button; never turn an unrelated submit into shutdown.
|
||
if (evt.keyCode == KeyCode.Y)
|
||
{
|
||
ConfirmSurrender();
|
||
evt.StopPropagation();
|
||
return;
|
||
}
|
||
|
||
if (evt.keyCode == KeyCode.N || evt.keyCode == KeyCode.Escape)
|
||
{
|
||
CancelSurrender();
|
||
evt.StopPropagation();
|
||
}
|
||
}
|
||
|
||
private bool TryBuildRunConfig(out RunConfig config)
|
||
{
|
||
if (RunContext.TryCreateRunConfig(languageDeckDatabase, out config))
|
||
{
|
||
return true;
|
||
}
|
||
|
||
if (Application.isEditor && TryBuildEditorFallback(out config))
|
||
{
|
||
Debug.Log("GameScene started without RunContext; using Ubuntu Python/JavaScript dev fallback.");
|
||
return true;
|
||
}
|
||
|
||
config = null;
|
||
return false;
|
||
}
|
||
|
||
private bool TryBuildEditorFallback(out RunConfig config)
|
||
{
|
||
config = null;
|
||
DistroDefinition distro = distroDatabase == null ? null : distroDatabase.FindById("ubuntu");
|
||
if (distro == null)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
List<CardDefinition> startingDeck = new();
|
||
for (int i = 0; i < distro.ExclusiveCards.Count && startingDeck.Count < CardLoadout.MaxEquippedCards; i++)
|
||
{
|
||
if (distro.ExclusiveCards[i] != null && !distro.ExclusiveCards[i].IsToken && !distro.ExclusiveCards[i].IsRunOnly)
|
||
{
|
||
startingDeck.Add(distro.ExclusiveCards[i]);
|
||
}
|
||
}
|
||
|
||
AddLanguageDeck(Language.Python, startingDeck);
|
||
AddLanguageDeck(Language.JavaScript, startingDeck);
|
||
config = new RunConfig(distro, Language.Python, Language.JavaScript, startingDeck, Environment.TickCount, 1);
|
||
return true;
|
||
}
|
||
|
||
private void AddLanguageDeck(Language language, List<CardDefinition> target)
|
||
{
|
||
LanguageDeckDefinition deck = languageDeckDatabase == null ? null : languageDeckDatabase.FindByLanguage(language);
|
||
if (deck == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
for (int entryIndex = 0; entryIndex < deck.Entries.Count; entryIndex++)
|
||
{
|
||
LanguageDeckDefinition.LanguageDeckEntry entry = deck.Entries[entryIndex];
|
||
for (int copy = 0; copy < entry.Count; copy++)
|
||
{
|
||
if (entry.Card != null && !entry.Card.IsRunOnly)
|
||
{
|
||
target.Add(entry.Card);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
private void HandleMissingRunConfig()
|
||
{
|
||
_root.Clear();
|
||
_root.AddToClassList("combat-root");
|
||
Label error = new("combat bootstrap failed: no RunContext and no editor fallback data");
|
||
error.AddToClassList("overlay-line");
|
||
_root.Add(error);
|
||
Debug.LogError("GameScene could not start: no RunContext and no Ubuntu editor fallback data.");
|
||
}
|
||
|
||
private void LoadStyles()
|
||
{
|
||
StyleSheet rarityStyleSheet = Resources.Load<StyleSheet>(SharedRarityStyleResourcePath);
|
||
if (rarityStyleSheet != null)
|
||
{
|
||
_root.styleSheets.Add(rarityStyleSheet);
|
||
}
|
||
|
||
StyleSheet styleSheet = Resources.Load<StyleSheet>(StyleResourcePath);
|
||
if (styleSheet != null)
|
||
{
|
||
_root.styleSheets.Add(styleSheet);
|
||
}
|
||
|
||
StyleSheet scrollbarStyleSheet = Resources.Load<StyleSheet>(SharedScrollbarStyleResourcePath);
|
||
if (scrollbarStyleSheet != null)
|
||
{
|
||
_root.styleSheets.Add(scrollbarStyleSheet);
|
||
}
|
||
}
|
||
|
||
private void BuildLayout()
|
||
{
|
||
_root.Clear();
|
||
_lastCombatantFeedbackRects.Clear();
|
||
_heldDeathUptime.Clear();
|
||
_deathBeatStartedCombatants.Clear();
|
||
_visuallyRemovedCombatants.Clear();
|
||
_playerFeedbackAnchorTracked = false;
|
||
_root.AddToClassList("combat-root");
|
||
_root.style.flexGrow = 1;
|
||
_root.focusable = true;
|
||
|
||
_statusBar = BuildStatusBar();
|
||
_root.Add(_statusBar);
|
||
|
||
var workspace = new ScrollView(ScrollViewMode.Vertical);
|
||
workspace.AddToClassList("combat-workspace");
|
||
_root.Add(workspace);
|
||
_firstBattleGuide = new FirstBattleGuide();
|
||
workspace.Add(_firstBattleGuide.Element);
|
||
_encounterBrief = TerminalLayout.BodyText("", "EncounterBrief");
|
||
workspace.Add(_encounterBrief);
|
||
_executionPreview = new ExecutionPreviewView();
|
||
workspace.Add(_executionPreview.Element);
|
||
VisualElement main = new();
|
||
main.AddToClassList("main-layout");
|
||
workspace.Add(main);
|
||
|
||
_playerPanel = CreatePanel("host", "distro", 0);
|
||
_playerPanel.AddToClassList("player-panel");
|
||
main.Add(_playerPanel);
|
||
|
||
VisualElement enemiesPanel = CreatePanel("process table", "select a process to target", 0);
|
||
enemiesPanel.AddToClassList("process-panel");
|
||
main.Add(enemiesPanel);
|
||
_targetHint = SoftwareCardView.Text("", "target-hint");
|
||
enemiesPanel.Add(_targetHint);
|
||
_enemyRow = new();
|
||
_enemyRow.AddToClassList("enemy-row");
|
||
enemiesPanel.Add(_enemyRow);
|
||
|
||
var packages = new VisualElement { name = "CombatPackages" };
|
||
packages.AddToClassList("combat-packages");
|
||
_packageReadinessStrip = new VisualElement { name = "PackageReadiness" };
|
||
_packageReadinessStrip.AddToClassList("package-readiness-strip");
|
||
_packageReadinessChips.Clear();
|
||
packages.Add(_packageReadinessStrip);
|
||
_packageActivationLabel = SoftwareCardView.Text("", "package-activation");
|
||
_packageActivationLabel.name = "PackageActivation";
|
||
packages.Add(_packageActivationLabel);
|
||
workspace.Add(packages);
|
||
|
||
VisualElement scheduler = new();
|
||
scheduler.AddToClassList("scheduler");
|
||
VisualElement schedulerHeader = PanelHeader("execution scheduler", "");
|
||
_schedulerActivity = schedulerHeader.Q<Label>(className: "panel-subtitle");
|
||
_schedulerActivity.AddToClassList("scheduler-activity");
|
||
_schedulerActivity.text = "No operations dispatched.";
|
||
scheduler.Add(schedulerHeader);
|
||
_interpreterStrip = AddTrackZone(scheduler, "queue / FIFO", "Interpreter: resolves in order during the interpret phase", "track-zone-queue");
|
||
_lazyStackPile = AddTrackZone(scheduler, "stack / LIFO", "After FIFO: newest first. Captured multiplier scales damage and explicit Shield only.", "track-zone-stack");
|
||
_interpreterStrip.name = "TutorialQueue";
|
||
_lazyStackPile.name = "TutorialStack";
|
||
_queueView = new ExecutionTrackView(_interpreterStrip, false);
|
||
_stackView = new ExecutionTrackView(_lazyStackPile, true);
|
||
_tokenArea = AddTrackZone(scheduler, "py automation", "2 script slots / expires at wave end", "track-zone-token");
|
||
_tokenArea.name = "PythonAutomationReadout";
|
||
_tokenArea.style.flexDirection = FlexDirection.Column;
|
||
_tokenArea.style.alignItems = Align.Stretch;
|
||
_tokenArea.style.width = Length.Percent(100);
|
||
_root.Add(scheduler);
|
||
|
||
VisualElement bottom = new();
|
||
bottom.AddToClassList("bottom-layout");
|
||
_root.Add(bottom);
|
||
VisualElement handPanel = CreatePanel("executable buffer", "Tab / Enter to select · E end turn", 0);
|
||
handPanel.AddToClassList("hand-panel");
|
||
bottom.Add(handPanel);
|
||
_handScroll = new ScrollView(ScrollViewMode.VerticalAndHorizontal);
|
||
_handScroll.AddToClassList("hand-scroll");
|
||
handPanel.Add(_handScroll);
|
||
_handRow = new();
|
||
_handRow.AddToClassList("hand-row");
|
||
_handScroll.Add(_handRow);
|
||
_handScroll.contentViewport.RegisterCallback<GeometryChangedEvent>(_ => FitHandCardsToViewport());
|
||
// ScrollView aligns oversized focused cards to the bottom, hiding identity/cost.
|
||
// Handle focus before it reaches the scroller and reveal the top of tall cards.
|
||
handPanel.RegisterCallback<FocusInEvent>(evt =>
|
||
{
|
||
if (evt.target is not Button face || !face.ClassListContains("hand-card")) return;
|
||
evt.StopPropagation();
|
||
void RevealCard()
|
||
{
|
||
// Reveal the identity region itself: requesting the full face lets
|
||
// ScrollView's deferred layout scroll back down to its bottom edge.
|
||
_handScroll.ScrollTo(face.Q(className: "software-name"));
|
||
_handScroll.ScrollTo(face.Q(className: "software-header"));
|
||
}
|
||
RevealCard();
|
||
_handScroll.schedule.Execute(() =>
|
||
{
|
||
if (handPanel.focusController?.focusedElement == face) RevealCard();
|
||
});
|
||
}, TrickleDown.TrickleDown);
|
||
|
||
VisualElement commandPanel = CreatePanel("dispatch", "turn controls", 0);
|
||
commandPanel.AddToClassList("turn-panel");
|
||
bottom.Add(commandPanel);
|
||
_turnResourceGrid = new();
|
||
_turnResourceGrid.name = "TutorialPiles";
|
||
_turnResourceGrid.AddToClassList("turn-resource-grid");
|
||
commandPanel.Add(_turnResourceGrid);
|
||
_prefetchButton = new Button(() => _combatManager.TryPrefetch())
|
||
{
|
||
name = "PrefetchButton", text = "draw 1 / 2 Cycles",
|
||
tooltip = "Prefetch: draw 1 card once per turn. Requires 2 free RAM so any card fits. Draws from the deck, reshuffling discard if needed."
|
||
};
|
||
_prefetchButton.AddToClassList("prefetch-action");
|
||
handPanel.Q<Label>(className: "panel-subtitle")?.RemoveFromHierarchy();
|
||
handPanel.Q(className: "panel-header").Add(_prefetchButton);
|
||
_endTurnButton = new(() => _combatManager.EndPlayerTurn()) { text = "[E] end turn" };
|
||
_endTurnButton.name = "TutorialEndTurn";
|
||
_endTurnButton.AddToClassList("primary-action");
|
||
commandPanel.Add(_endTurnButton);
|
||
var guideButton = new Button(() =>
|
||
{
|
||
if (_tutorial != null) _tutorial.Review();
|
||
else _firstBattleGuide.Begin(_runManager.CurrentConfig, true);
|
||
}) { text = "? guide", name = "ReplayBattleGuide" };
|
||
guideButton.tooltip = "Battle guide: replay the first-battle tips";
|
||
guideButton.AddToClassList("battle-guide-toggle");
|
||
commandPanel.Q<Label>(className: "panel-subtitle")?.RemoveFromHierarchy();
|
||
commandPanel.Q(className: "panel-header").Add(guideButton);
|
||
_surrenderButton = new(HandleSurrenderClicked) { text = "> shutdown -r run" };
|
||
_surrenderButton.AddToClassList("secondary-action");
|
||
_surrenderButton.AddToClassList("surrender-action");
|
||
commandPanel.Add(_surrenderButton);
|
||
_surrenderConfirmLabel = new("End this run? Unbanked progress is lost. [Y/n]");
|
||
_surrenderConfirmLabel.AddToClassList("surrender-confirm");
|
||
_surrenderConfirmLabel.AddToClassList("hidden");
|
||
commandPanel.Add(_surrenderConfirmLabel);
|
||
_surrenderCancelButton = new(CancelSurrender) { text = "[Esc] cancel shutdown" };
|
||
_surrenderCancelButton.AddToClassList("secondary-action");
|
||
_surrenderCancelButton.AddToClassList("hidden");
|
||
commandPanel.Add(_surrenderCancelButton);
|
||
|
||
var log = new Foldout { text = "journal / recent combat events", value = false };
|
||
_journal = log;
|
||
log.AddToClassList("combat-journal");
|
||
_journalEntries = new VisualElement();
|
||
var logScroll = new ScrollView(ScrollViewMode.Vertical);
|
||
_journalScroll = logScroll;
|
||
_journalStartedAt = Time.realtimeSinceStartup;
|
||
logScroll.AddToClassList("journal-scroll");
|
||
logScroll.Add(_journalEntries);
|
||
log.Add(logScroll);
|
||
log.RegisterValueChangedCallback(evt =>
|
||
{
|
||
if (!evt.newValue) return;
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (_journal.value && _journalEntries.childCount > 0)
|
||
_journalScroll.ScrollTo(_journalEntries.ElementAt(_journalEntries.childCount - 1));
|
||
}, 20);
|
||
});
|
||
_root.Add(log);
|
||
|
||
_feedbackLayer = new();
|
||
_feedbackLayer.AddToClassList("feedback-layer");
|
||
_feedbackLayer.pickingMode = PickingMode.Ignore;
|
||
_root.Add(_feedbackLayer);
|
||
|
||
_damageVignette = new();
|
||
_damageVignette.AddToClassList("damage-vignette");
|
||
_damageVignette.pickingMode = PickingMode.Ignore;
|
||
_root.Add(_damageVignette);
|
||
|
||
_overlay = new();
|
||
_overlay.AddToClassList("overlay");
|
||
TerminalTheme.ConstrainModalFocus(_overlay);
|
||
_overlay.style.display = DisplayStyle.None;
|
||
_root.Add(_overlay);
|
||
}
|
||
|
||
private VisualElement BuildStatusBar()
|
||
{
|
||
VisualElement bar = new();
|
||
bar.AddToClassList("combat-status-bar");
|
||
|
||
_waveLabel = AddStatusReadout(bar, "wave", "--", false);
|
||
_phaseLabel = AddStatusReadout(bar, "phase", "--", true);
|
||
_bitsLabel = AddStatusReadout(bar, "Bits", "0", false);
|
||
_entropyLabel = AddStatusReadout(bar, "Entropy", "0", false);
|
||
_bandwidthLabel = AddStatusReadout(bar, "Bandwidth", "0", false);
|
||
_rootCreditsLabel = AddStatusReadout(bar, "Root Credits", "0", false);
|
||
|
||
VisualElement spacer = new();
|
||
spacer.AddToClassList("status-spacer");
|
||
bar.Add(spacer);
|
||
|
||
_seedLabel = new("--");
|
||
_seedLabel.AddToClassList("seed-value");
|
||
bar.Add(_seedLabel);
|
||
return bar;
|
||
}
|
||
|
||
private static Label AddStatusReadout(VisualElement parent, string labelText, string valueText, bool phase)
|
||
{
|
||
VisualElement cluster = new();
|
||
cluster.AddToClassList("status-cluster");
|
||
Label label = new(labelText);
|
||
label.AddToClassList("status-label");
|
||
Label value = new(valueText);
|
||
value.AddToClassList(phase ? "phase-pill" : "status-value");
|
||
cluster.Add(label);
|
||
cluster.Add(value);
|
||
parent.Add(cluster);
|
||
return value;
|
||
}
|
||
|
||
private VisualElement AddTrackZone(VisualElement parent, string title, string subtitle, string className)
|
||
{
|
||
VisualElement zone = new();
|
||
zone.AddToClassList("track-zone");
|
||
zone.AddToClassList(className);
|
||
|
||
VisualElement header = new();
|
||
header.AddToClassList("track-header");
|
||
header.tooltip = subtitle;
|
||
Label titleLabel = new(title);
|
||
titleLabel.AddToClassList("track-title");
|
||
Label subtitleLabel = new(subtitle);
|
||
subtitleLabel.AddToClassList("track-subtitle");
|
||
header.Add(titleLabel);
|
||
header.Add(subtitleLabel);
|
||
zone.Add(header);
|
||
|
||
var scroll = new ScrollView(className == "track-zone-queue" ? ScrollViewMode.Horizontal : ScrollViewMode.Vertical);
|
||
scroll.AddToClassList("track-scroll");
|
||
VisualElement contents = new();
|
||
contents.AddToClassList("track-contents");
|
||
contents.userData = zone;
|
||
scroll.Add(contents);
|
||
zone.Add(scroll);
|
||
parent.Add(zone);
|
||
return contents;
|
||
}
|
||
|
||
private void Refresh()
|
||
{
|
||
if (_combatManager.PlayerState == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_tutorial?.UpdateState();
|
||
RefreshStatus();
|
||
RefreshPlayer();
|
||
RefreshTracks();
|
||
RefreshEnemies();
|
||
RefreshHand();
|
||
RefreshTurnPanel();
|
||
RefreshPackageReadiness();
|
||
RefreshOverlay();
|
||
_executionPreview?.Refresh(_combatManager);
|
||
if (_encounterBrief != null)
|
||
{
|
||
// Encounter advice belongs to onboarding, not every battle's workspace.
|
||
_encounterBrief.text = "";
|
||
_encounterBrief.style.display = DisplayStyle.None;
|
||
}
|
||
_firstBattleGuide?.Refresh(_combatManager.AwaitingWaveContinue, _combatManager.RunFinished);
|
||
}
|
||
|
||
private void RefreshPackageReadiness()
|
||
{
|
||
if (_packageReadinessStrip == null) return;
|
||
var readouts = _combatManager.GetPackageReadouts();
|
||
var currentIds = new HashSet<string>();
|
||
foreach (var readout in readouts)
|
||
{
|
||
string id = readout.Definition.Id;
|
||
currentIds.Add(id);
|
||
if (!_packageReadinessChips.TryGetValue(id, out var chip))
|
||
{
|
||
chip = new VisualElement { name = "Readiness_" + id, focusable = true, tabIndex = 0 };
|
||
chip.AddToClassList("package-readiness-chip");
|
||
chip.Add(RarityPresentation.CreatePackageBadge(readout.Definition.Rarity));
|
||
chip.Add(SoftwareCardView.Text(readout.Definition.DisplayName, "package-readiness-name"));
|
||
chip.Add(SoftwareCardView.Text("", "package-readiness-state"));
|
||
_packageReadinessChips[id] = chip;
|
||
_packageReadinessStrip.Add(chip);
|
||
}
|
||
chip.Q<Label>(className: "package-readiness-state").text = readout.State;
|
||
chip.tooltip = readout.Definition.DisplayName + "\n" + readout.Details;
|
||
}
|
||
foreach (var id in new List<string>(_packageReadinessChips.Keys))
|
||
{
|
||
if (currentIds.Contains(id)) continue;
|
||
_packageReadinessChips[id].RemoveFromHierarchy();
|
||
_packageReadinessChips.Remove(id);
|
||
}
|
||
_packageReadinessStrip.parent.style.display = readouts.Count > 0 ? DisplayStyle.Flex : DisplayStyle.None;
|
||
}
|
||
|
||
private void HandlePackageActivated(PackageActivation activation)
|
||
{
|
||
if (_packageActivationLabel == null) return;
|
||
if (_packageActivationFrame != Time.frameCount) _packageActivationMessages.Clear();
|
||
_packageActivationFrame = Time.frameCount;
|
||
if (_packageActivationMessages.Count == 3) _packageActivationMessages.Dequeue();
|
||
_packageActivationMessages.Enqueue(activation.Name + ": " + activation.Message);
|
||
_packageActivationLabel.text = string.Join(" | ", _packageActivationMessages);
|
||
int version = ++_packageActivationVersion;
|
||
// Feedback only: readiness and effects always use real combat state.
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (version == _packageActivationVersion) _packageActivationLabel.text = "";
|
||
}, 3500);
|
||
}
|
||
|
||
private void RefreshStatus()
|
||
{
|
||
SaveData data;
|
||
try
|
||
{
|
||
data = _lastKnownSave = _saveService.Load();
|
||
if (_runManager.RewardsSettled) _saveError = null;
|
||
}
|
||
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
|
||
{
|
||
_saveError = ex.Message;
|
||
data = _lastKnownSave ?? new SaveData();
|
||
}
|
||
RunConfig config = _runManager.CurrentConfig;
|
||
_waveLabel.text = _runManager.Journey.campaign && !_runManager.Journey.endless
|
||
? $"{Math.Min(_runManager.Journey.FinalWave, _runManager.CurrentWaveNumber)}/{_runManager.Journey.FinalWave}"
|
||
: _runManager.CurrentWaveNumber.ToString();
|
||
_waveLabel.tooltip = _runManager.Journey.campaign && !_runManager.Journey.endless
|
||
? $"Clear {_runManager.Journey.FinalWave} waves, defeat the Kernel Overseer, then finish or continue into endless mode."
|
||
: "Endless mode";
|
||
if (config?.IsTutorial == true)
|
||
{
|
||
_waveLabel.text = $"training {config.TutorialLesson}/{TutorialCampaign.LessonCount}";
|
||
_waveLabel.tooltip = "Clear both training waves for a one-time Bandwidth and Entropy reward.";
|
||
}
|
||
_phaseLabel.text = PhaseText(_combatManager.CurrentPhase);
|
||
_bitsLabel.text = _runManager.Bits.ToString();
|
||
_entropyLabel.text = FormatWalletWithAccrual(data.entropyBalance, _runManager.AccruedEntropy);
|
||
_bandwidthLabel.text = FormatWalletWithAccrual(data.bandwidthBalance, _runManager.AccruedBandwidth);
|
||
_rootCreditsLabel.text = data.rootCredits.ToString();
|
||
_seedLabel.text = $"seed {config?.RunSeed ?? 0}";
|
||
}
|
||
|
||
private void RefreshPlayer()
|
||
{
|
||
var uptimeMeter = _playerPanel.Q(className: "meter-block");
|
||
_playerPanel.Clear();
|
||
_combatantElements.Remove(_combatManager.PlayerState);
|
||
_combatantElements[_combatManager.PlayerState] = _playerPanel;
|
||
var distro = _runManager.CurrentConfig.Distro;
|
||
_playerPanel.Add(PanelHeader(DisplayName(distro), "HOST"));
|
||
var config = _runManager.CurrentConfig;
|
||
var identity = SoftwareCardView.Text($"{config.PrimaryLanguage} / {config.SecondaryLanguage}", "host-languages");
|
||
identity.tooltip = distro.Passive == null ? "" : distro.Passive.RulesText;
|
||
_playerPanel.Add(identity);
|
||
ApplyAccent(_playerPanel);
|
||
|
||
CombatantState state = _combatManager.PlayerState;
|
||
TrackCombatantFeedbackAnchor(state, _playerPanel);
|
||
DetectBeneficialResourceFeedback(state, _playerPanel);
|
||
ApplyStatusStateClasses(_playerPanel, state);
|
||
if (uptimeMeter == null) uptimeMeter = MeterBlock("uptime", state.CurrentUptime, state.MaxUptime, MeterTone.Uptime);
|
||
else UpdateMeter(uptimeMeter, state.CurrentUptime, state.MaxUptime);
|
||
uptimeMeter.name = "TutorialUptime";
|
||
_playerPanel.Add(uptimeMeter);
|
||
var shieldStat = TurnStat("shield", state.Shield.ToString());
|
||
shieldStat.name = "TutorialShield"; _playerPanel.Add(shieldStat);
|
||
_playerPanel.Add(CycleBlock(state.Cycles, state.MaxCycles));
|
||
|
||
Label ram = new($"ram hand cap {_combatManager.HandController.UsedRam}/{_combatManager.HandController.RamCapacity}");
|
||
ram.AddToClassList("ram-note");
|
||
_playerPanel.Add(ram);
|
||
if (_combatManager.ActiveKernelRamPenalty > 0)
|
||
{
|
||
Label ramPressure = new($"! kernel panic: RAM -{_combatManager.ActiveKernelRamPenalty}");
|
||
ramPressure.AddToClassList("status-label");
|
||
ramPressure.AddToClassList("intent-attack");
|
||
_playerPanel.Add(ramPressure);
|
||
}
|
||
|
||
_playerPanel.Add(StatusBlock(state, true));
|
||
|
||
var compilation = _combatManager.Compilation;
|
||
if (compilation.Active)
|
||
{
|
||
VisualElement panel = new();
|
||
panel.AddToClassList("compilation-panel");
|
||
panel.tooltip = "emerge --world: Compilation advances after each completed round and resets each wave.";
|
||
VisualElement heading = new();
|
||
heading.AddToClassList("compilation-heading");
|
||
heading.Add(SoftwareCardView.Text("Compilation", "compilation-title"));
|
||
heading.Add(SoftwareCardView.Text($"{compilation.Level}/{compilation.Maximum}", "compilation-level"));
|
||
panel.Add(heading);
|
||
VisualElement progress = new();
|
||
progress.AddToClassList("compilation-progress");
|
||
for (int level = 0; level < compilation.Maximum; level++)
|
||
{
|
||
VisualElement step = new();
|
||
step.AddToClassList("compilation-step");
|
||
step.EnableInClassList("compilation-step-filled", level < compilation.Level);
|
||
progress.Add(step);
|
||
}
|
||
panel.Add(progress);
|
||
panel.Add(CompilationModifier("card damage", $"{compilation.DamagePercent - 100:+0;-0;0}%"));
|
||
if (config.DistroVersion >= 4)
|
||
panel.Add(CompilationModifier("card shield", $"+{compilation.ShieldPercent - 100}%"));
|
||
_playerPanel.Add(panel);
|
||
}
|
||
|
||
if (IsDistro("fedora"))
|
||
{
|
||
_playerPanel.Add(FedoraRiskMeter(_combatManager.FedoraCrashChance));
|
||
}
|
||
|
||
if (IsDistro("arch"))
|
||
{
|
||
_playerPanel.Add(ArchBtwCounter(state.ArchBtwStacks));
|
||
}
|
||
}
|
||
|
||
private bool IsDistro(string id)
|
||
{
|
||
return string.Equals(_runManager?.CurrentConfig?.Distro?.Id, id, StringComparison.OrdinalIgnoreCase);
|
||
}
|
||
|
||
private static VisualElement CompilationModifier(string label, string value)
|
||
{
|
||
return TerminalLayout.StatRow(label, value, rowClass: "compilation-modifier",
|
||
keyClass: "compilation-label", valueClass: "compilation-value");
|
||
}
|
||
|
||
private void RefreshTracks()
|
||
{
|
||
_queueView.Sync(_combatManager.InterpreterQueue.Cards);
|
||
_stackView.Sync(_combatManager.LazyStack.Cards);
|
||
_stackView.SyncMultipliers(_combatManager.LazyStack.Entries);
|
||
_queueView.SyncPreviews(_combatManager, _combatManager.InterpreterQueue.Cards);
|
||
_stackView.SyncPreviews(_combatManager, _combatManager.LazyStack.Cards);
|
||
if (_combatManager.AwaitingWaveContinue || _combatManager.RunFinished)
|
||
{
|
||
_queueView.EndExecution();
|
||
_stackView.EndExecution();
|
||
}
|
||
_tokenArea.Clear();
|
||
bool pythonIdle = _combatManager.Python.AutomationCount == 0
|
||
&& _combatManager.Python.RepeatCount == 0 && _combatManager.Python.AreaCount == 0;
|
||
IEnumerable<string> pythonReadout = pythonIdle ? new[] { "0 / 2 slots" } : _combatManager.Python.Readout;
|
||
foreach (string line in pythonReadout)
|
||
{
|
||
var label = new Label(line);
|
||
label.style.whiteSpace = WhiteSpace.Normal;
|
||
_tokenArea.Add(label);
|
||
}
|
||
((VisualElement)_tokenArea.userData).EnableInClassList("track-idle", _combatManager.Python.AutomationCount == 0);
|
||
_root.Q(className: "scheduler").EnableInClassList("scheduler-idle",
|
||
_combatManager.InterpreterQueue.Count == 0 && _combatManager.LazyStack.Count == 0
|
||
&& _combatManager.Python.AutomationCount == 0 && _combatManager.Python.RepeatCount == 0 && _combatManager.Python.AreaCount == 0);
|
||
((VisualElement)_interpreterStrip.userData).EnableInClassList("track-resolving", _combatManager.CurrentPhase == TurnPhase.Interpret);
|
||
}
|
||
|
||
private void RefreshEnemies()
|
||
{
|
||
var focused = _root.focusController?.focusedElement as VisualElement;
|
||
var focusedEnemy = focused != null && _enemyRow.Contains(focused) ? focused.userData as EnemyInstance : null;
|
||
PruneVisuallyRemovedCombatants();
|
||
var present = new HashSet<EnemyInstance>(_combatManager.Enemies);
|
||
var stale = new List<EnemyInstance>();
|
||
foreach (var entry in _enemyCards)
|
||
if (!present.Contains(entry.Key) || _visuallyRemovedCombatants.Contains(entry.Key.State)) stale.Add(entry.Key);
|
||
foreach (var enemy in stale)
|
||
{
|
||
_enemyCards[enemy].RemoveFromHierarchy();
|
||
_enemyCards.Remove(enemy);
|
||
_combatantElements.Remove(enemy.State);
|
||
_restartingEnemies.Remove(enemy);
|
||
_previousUptime.Remove(enemy.State);
|
||
_previousShield.Remove(enemy.State);
|
||
}
|
||
bool compactEnemies = false; // Scroll the workspace instead of reducing critical text.
|
||
_enemyRow.EnableInClassList("enemy-row-compact", compactEnemies);
|
||
_targetHint.text = _combatManager.PendingTargetCard == null
|
||
? ""
|
||
: $"> target required: {DisplayName(_combatManager.PendingTargetCard.Definition)}";
|
||
_targetHint.EnableInClassList("hidden", _combatManager.PendingTargetCard == null);
|
||
_targetHint.EnableInClassList("target-required", _combatManager.PendingTargetCard != null);
|
||
if (_combatManager.PlayerState != null)
|
||
{
|
||
_combatantElements[_combatManager.PlayerState] = _playerPanel;
|
||
}
|
||
|
||
for (int i = 0; i < _combatManager.Enemies.Count; i++)
|
||
{
|
||
int index = i;
|
||
EnemyInstance enemy = _combatManager.Enemies[i];
|
||
if (_visuallyRemovedCombatants.Contains(enemy.State))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
if (!_enemyCards.TryGetValue(enemy, out Button card))
|
||
{
|
||
card = new Button(() =>
|
||
{
|
||
// Resolve the current index: an earlier process may have exited.
|
||
for (int target = 0; target < _combatManager.Enemies.Count; target++)
|
||
if (ReferenceEquals(_combatManager.Enemies[target], enemy)) { _combatManager.SelectEnemy(target); break; }
|
||
}) { userData = enemy };
|
||
card.AddToClassList("enemy-card");
|
||
card.Add(SoftwareCardView.Text("", "process-state"));
|
||
card.Add(SoftwareCardView.Text("", "enemy-name"));
|
||
card.Add(MeterBlock("uptime", enemy.CurrentUptime, enemy.MaxUptime, MeterTone.Uptime));
|
||
var intent = new VisualElement { name = "ProcessIntent" };
|
||
intent.AddToClassList("process-intent-slot");
|
||
card.Add(intent);
|
||
card.Add(SoftwareCardView.Text("", "enemy-shield"));
|
||
card.Add(SoftwareCardView.Text("", "process-behavior"));
|
||
card.Add(new VisualElement { name = "ProcessSignals" });
|
||
var statusSlot = new VisualElement { name = "ProcessStatuses" };
|
||
statusSlot.AddToClassList("process-statuses");
|
||
card.Add(statusSlot);
|
||
_enemyCards.Add(enemy, card);
|
||
_enemyRow.Add(card);
|
||
}
|
||
card.EnableInClassList("enemy-card-compact", compactEnemies);
|
||
card.EnableInClassList("enemy-card-elite", enemy.HasEliteSignal);
|
||
bool deathPending = enemy.DefeatedPendingRemoval || (enemy.State.IsDefeated && !enemy.PendingRevive);
|
||
// Some existing reaping paths set IsDefeated before DamagePipeline can emit defeat.
|
||
// Observe that authoritative transition once, using the same visual acknowledgement.
|
||
if (deathPending && !_deathFeedbackObserved.Contains(enemy.State))
|
||
HandleCombatantDefeated(new CombatantDefeatedEvent(enemy.State));
|
||
bool deathBeatStarted = _deathBeatStartedCombatants.Contains(enemy.State);
|
||
bool holdDeathDisplay = deathPending && !deathBeatStarted;
|
||
int displayedUptime = enemy.CurrentUptime;
|
||
card.EnableInClassList("enemy-card-defeated-hold", deathPending && deathBeatStarted);
|
||
card.SetEnabled((!enemy.State.IsDefeated || holdDeathDisplay) && _combatManager.TutorialGuide?.AllowsEnemy(enemy) != false);
|
||
card.EnableInClassList("enemy-targetable", _combatManager.PendingTargetCard != null && !deathPending && !enemy.State.IsDefeated);
|
||
card.AddToClassList("process-" + enemy.ArchetypeId.Replace('_', '-'));
|
||
card.Q<Label>(className: "process-state").text = $"{(_combatManager.SelectedEnemyIndex == index ? "> " : " ")}{EnemyProcessPresentation.Symbol(enemy.ArchetypeId)} {EnemyProcessPresentation.Lifecycle(enemy)}";
|
||
card.EnableInClassList("process-restarting", enemy.PendingRevive);
|
||
bool highlighted = _combatManager.SelectedEnemyIndex == index;
|
||
card.EnableInClassList("enemy-card-targeted", highlighted);
|
||
card.Q<Label>(className: "enemy-name").text = enemy.Name;
|
||
card.tooltip = enemy.Name + " / " + IntentText(enemy.DisplayIntent);
|
||
if (enemy.HasBehavior(EnemyBehaviorFlags.ObfuscateIntent))
|
||
card.tooltip += "\nSurge: 8-10 damage. Harden: 6-8 Shield. Bypass: 3-4 damage ignoring Shield.\nDamage reveals this round's action, including hits absorbed by Shield. Hides again next round.";
|
||
if (enemy.HasBehavior(EnemyBehaviorFlags.LeavesOrphan))
|
||
card.tooltip += $"\n{CombatTuning.OrphanSpawnChancePercent}% chance to leave an orphan on permanent death.";
|
||
card.Q<Label>(className: "process-behavior").text = EnemyProcessPresentation.Behavior(enemy);
|
||
var signals = card.Q("ProcessSignals");
|
||
signals.Clear();
|
||
if (enemy.HasSpecialSignal)
|
||
{
|
||
signals.Add(EnemySignalPanel(enemy, _combatManager.Enemies));
|
||
}
|
||
|
||
_combatantElements[enemy.State] = card;
|
||
if (!deathPending)
|
||
{
|
||
DetectBeneficialResourceFeedback(enemy.State, card);
|
||
}
|
||
|
||
ApplyStatusStateClasses(card, enemy.State);
|
||
UpdateMeter(card.Q(className: "meter-block"), displayedUptime, enemy.MaxUptime);
|
||
card.Q<Label>(className: "enemy-shield").text = enemy.State.Shield > 0 ? $"# shield {enemy.State.Shield}" : "";
|
||
var intentSlot = card.Q("ProcessIntent");
|
||
intentSlot.Clear();
|
||
if (enemy.PendingRevive)
|
||
{
|
||
intentSlot.Add(SoftwareCardView.Text("~ inactive / restart pending", "process-terminated"));
|
||
if (_restartingEnemies.Add(enemy))
|
||
{
|
||
PlayElementBeat(card, "feedback-status", 240);
|
||
AppendCombatLog($"{enemy.Name}: restart pending.", "journal-status");
|
||
}
|
||
}
|
||
else if (!deathPending && (!enemy.SpawnedFromDeath || enemy.DeathSpawnIntentRevealed))
|
||
{
|
||
intentSlot.Add(IntentPanel(enemy.DisplayIntent));
|
||
}
|
||
else if (deathPending)
|
||
{
|
||
intentSlot.Add(SoftwareCardView.Text("process terminated", "process-terminated"));
|
||
}
|
||
if (!enemy.PendingRevive && _restartingEnemies.Remove(enemy) && enemy.HasRevived && !deathPending)
|
||
{
|
||
_heldDeathUptime.Remove(enemy.State);
|
||
_deathBeatStartedCombatants.Remove(enemy.State);
|
||
_deathFeedbackObserved.Remove(enemy.State);
|
||
SpawnFloatingText(card, "restarted", "float-heal");
|
||
PlayElementBeat(card, "feedback-spawned", 240);
|
||
AppendCombatLog($"{enemy.Name}: restarted / revival spent.", "journal-status");
|
||
}
|
||
var statuses = card.Q("ProcessStatuses");
|
||
statuses.Clear();
|
||
statuses.EnableInClassList("hidden", enemy.State.Statuses.Count == 0);
|
||
if (enemy.State.Statuses.Count > 0) statuses.Add(StatusPipRow(enemy.State));
|
||
if (ReferenceEquals(focusedEnemy, enemy)) card.Focus();
|
||
TrackCombatantFeedbackAnchor(enemy.State, card);
|
||
}
|
||
}
|
||
|
||
private int HeldDeathUptime(CombatantState state, int maxUptime)
|
||
{
|
||
if (state != null && _heldDeathUptime.TryGetValue(state, out int uptime))
|
||
{
|
||
return Mathf.Clamp(uptime, 0, Mathf.Max(1, maxUptime));
|
||
}
|
||
|
||
return Mathf.Clamp(maxUptime, 1, Mathf.Max(1, maxUptime));
|
||
}
|
||
|
||
private void PruneVisuallyRemovedCombatants()
|
||
{
|
||
bool IsRemoved(CombatantState state)
|
||
{
|
||
IReadOnlyList<EnemyInstance> enemies = _combatManager.Enemies;
|
||
for (int i = 0; i < enemies.Count; i++)
|
||
{
|
||
if (enemies[i].State == state)
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
_visuallyRemovedCombatants.RemoveWhere(IsRemoved);
|
||
_deathBeatStartedCombatants.RemoveWhere(IsRemoved);
|
||
_deathFeedbackObserved.RemoveWhere(IsRemoved);
|
||
List<CombatantState> staleHeldStates = null;
|
||
foreach (CombatantState state in _heldDeathUptime.Keys)
|
||
{
|
||
if (!IsRemoved(state))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
staleHeldStates ??= new List<CombatantState>();
|
||
staleHeldStates.Add(state);
|
||
}
|
||
|
||
if (staleHeldStates == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
for (int i = 0; i < staleHeldStates.Count; i++)
|
||
{
|
||
_heldDeathUptime.Remove(staleHeldStates[i]);
|
||
}
|
||
}
|
||
|
||
private void FitHandCardsToViewport()
|
||
{
|
||
float width = _handScroll.contentViewport.contentRect.width;
|
||
if (width <= 0) return;
|
||
foreach (var face in _retainedHandCards.Values)
|
||
face.style.maxWidth = Mathf.Max(1, width - face.resolvedStyle.marginLeft - face.resolvedStyle.marginRight);
|
||
}
|
||
|
||
private void RefreshHand()
|
||
{
|
||
TerminalTheme.PreserveFocus(_handRow);
|
||
_handRow.Q("EmptyHand")?.RemoveFromHierarchy();
|
||
// Keep button identities between updates so keyboard focus and horizontal scroll survive.
|
||
_handCardElements.Clear();
|
||
var hand = _combatManager.HandController.Cards;
|
||
var current = new HashSet<CardInstance>(hand);
|
||
var stale = new List<CardInstance>();
|
||
foreach (var pair in _retainedHandCards)
|
||
if (!current.Contains(pair.Key)) { pair.Value.RemoveFromHierarchy(); stale.Add(pair.Key); }
|
||
foreach (var card in stale) _retainedHandCards.Remove(card);
|
||
if (hand.Count == 0)
|
||
{
|
||
var empty = EmptyState("Buffer empty. End your turn to draw.");
|
||
empty.name = "EmptyHand";
|
||
_handRow.Add(empty);
|
||
}
|
||
|
||
for (int i = 0; i < hand.Count; i++)
|
||
{
|
||
CardInstance card = hand[i];
|
||
bool added = !_retainedHandCards.TryGetValue(card, out VisualElement face);
|
||
if (added)
|
||
{
|
||
face = CardFace(card);
|
||
_retainedHandCards[card] = face;
|
||
_handRow.Add(face);
|
||
}
|
||
else
|
||
{
|
||
face.Clear();
|
||
PopulateCardFace(face, card);
|
||
}
|
||
face.EnableInClassList("hand-card-selected", _combatManager.PendingTargetCard == card);
|
||
face.style.marginRight = i == hand.Count - 1 ? 0 : 10;
|
||
face.EnableInClassList("hand-card-unaffordable", GetDisplayCardCost(card) > _combatManager.PlayerState.Cycles);
|
||
var stateLabel = face.Q<Label>(className: "software-state");
|
||
string reason = card.IsBroken ? (card.CorruptionRoundsRemaining > 0
|
||
? $"[!] RECOVER {card.CorruptionRoundsRemaining} ROUNDS" : "[!] CORRUPTED") : card.IsLocked ? $"[L] UNLOCK {EnemyArchetypeCatalog.DrmUnlockCycleCost}c"
|
||
: card.Definition.IsToken ? "TOKEN / NOT EXECUTABLE"
|
||
: GetDisplayCardCost(card) > _combatManager.PlayerState.Cycles ? $"NEEDS {GetDisplayCardCost(card)} CYCLES"
|
||
: _combatManager.PendingTargetCard == card ? "> SELECT TARGET" : "";
|
||
if (!string.IsNullOrEmpty(reason)) { stateLabel.text = reason; face.tooltip += "\n" + reason; }
|
||
face.SetEnabled(!_combatManager.RunFinished && _combatManager.CurrentPhase == TurnPhase.Execute && !card.IsBroken
|
||
&& _combatManager.TutorialGuide?.AllowsCard(card) != false);
|
||
_handCardElements[card] = face;
|
||
if (added) PlayElementBeat(face, "hand-card-drawn", 180);
|
||
}
|
||
FitHandCardsToViewport();
|
||
}
|
||
|
||
private void RefreshTurnPanel()
|
||
{
|
||
_turnResourceGrid.Clear();
|
||
CombatantState state = _combatManager.PlayerState;
|
||
IReadOnlyList<CardInstance> hand = _combatManager.HandController.Cards;
|
||
var cyclesStat = TurnStat("cycles", $"{state.Cycles}/{state.MaxCycles}");
|
||
cyclesStat.name = "TutorialCycles"; _turnResourceGrid.Add(cyclesStat);
|
||
var handStat = TurnStat("hand", $"{_combatManager.HandController.UsedRam}/{_combatManager.HandController.RamCapacity}");
|
||
handStat.name = "TutorialRam"; _turnResourceGrid.Add(handStat);
|
||
_turnResourceGrid.Add(PileStat("draw", _combatManager.DeckController.DrawPile));
|
||
_turnResourceGrid.Add(PileStat("discard", _combatManager.DeckController.DiscardPile));
|
||
_turnResourceGrid.Add(PileStat("exhaust", _combatManager.DeckController.ExhaustPile));
|
||
_endTurnButton.SetEnabled(_combatManager.CanSurrenderRun && _combatManager.TutorialGuide?.CanEndTurn != false);
|
||
_prefetchButton.style.display = _combatManager.RunConfig?.IsTutorial == true ? DisplayStyle.None : DisplayStyle.Flex;
|
||
_prefetchButton.SetEnabled(_combatManager.CanPrefetch);
|
||
RefreshSurrenderCommand();
|
||
}
|
||
|
||
private VisualElement PileStat(string pile, IReadOnlyList<CardInstance> cards)
|
||
{
|
||
var button = new Button(() => OpenPileInspector(pile, cards))
|
||
{
|
||
name = "InspectPile_" + pile,
|
||
text = $"{pile} {cards.Count} [inspect]",
|
||
tooltip = $"Inspect {pile} cards, including upgrades. Draw order is hidden."
|
||
};
|
||
button.AddToClassList("pile-stat-button");
|
||
button.SetEnabled(_combatManager.CanSurrenderRun);
|
||
return button;
|
||
}
|
||
|
||
private void OpenPileInspector(string pile, IReadOnlyList<CardInstance> cards)
|
||
{
|
||
if (!_combatManager.CanSurrenderRun || _surrenderConfirming) return;
|
||
_inspectedPile = pile;
|
||
_pileInspectorOpen = true;
|
||
_overlay.Clear();
|
||
_overlay.AddToClassList("pile-overlay");
|
||
var inventories = new Dictionary<string, IReadOnlyList<CardInstance>>
|
||
{
|
||
["draw"] = new List<CardInstance>(_combatManager.DeckController.DrawPile),
|
||
["discard"] = new List<CardInstance>(_combatManager.DeckController.DiscardPile),
|
||
["exhaust"] = new List<CardInstance>(_combatManager.DeckController.ExhaustPile)
|
||
};
|
||
inventories[pile] = new List<CardInstance>(cards);
|
||
_overlay.Add(CardPileView.BuildBrowser(pile, inventories, ClosePileInspector, _combatManager.GetPileCostDetails,
|
||
card => CardEffectFactory.GetRulesText(card, _combatManager.RunConfig)));
|
||
_overlay.style.display = DisplayStyle.Flex;
|
||
_overlay.Q<TextField>("PileSearch")?.Focus();
|
||
}
|
||
|
||
private void ClosePileInspector()
|
||
{
|
||
_pileInspectorOpen = false;
|
||
// Move focus before clearing; modal refresh must not schedule focus back into a hidden overlay.
|
||
_turnResourceGrid.Q<Button>("InspectPile_" + _inspectedPile)?.Focus();
|
||
RefreshOverlay();
|
||
}
|
||
|
||
private string DescribeDamageSource(CombatantState source)
|
||
{
|
||
if (ReferenceEquals(source, _combatManager.PlayerState)) return "Self-inflicted damage";
|
||
foreach (var enemy in _combatManager.Enemies)
|
||
if (ReferenceEquals(enemy.State, source)) return $"{enemy.Name}: {enemy.CurrentIntent.DisplayLabel}";
|
||
return "Unattributed system damage";
|
||
}
|
||
|
||
private RunHistoryEntry GetRunHistoryEntry()
|
||
{
|
||
if (_runHistoryEntry != null && _runHistoryEntry.runId == _runManager.RunId) return _runHistoryEntry;
|
||
var config = _runManager.CurrentConfig;
|
||
var entry = new RunHistoryEntry
|
||
{
|
||
runId = _runManager.RunId,
|
||
endedUtc = DateTimeOffset.UtcNow.ToString("O"),
|
||
distroId = config?.Distro?.Id,
|
||
distroName = config?.Distro == null ? "Unknown distro" : DisplayName(config.Distro),
|
||
distroVersion = config?.DistroVersion ?? 1,
|
||
languages = $"{config?.PrimaryLanguage} + {config?.SecondaryLanguage}",
|
||
seed = config?.RunSeed ?? 0,
|
||
build = RunHistory.CaptureBuild(config),
|
||
waveReached = _combatManager.RunCompleted ? _runManager.WavesCleared : _runManager.CurrentWaveNumber,
|
||
wavesCleared = _runManager.WavesCleared,
|
||
surrendered = _runEndedBySurrender || _combatManager.RunEndedBySurrender,
|
||
victory = _combatManager.RunCompleted
|
||
};
|
||
_runTelemetry?.FillReport(entry);
|
||
if (entry.victory) entry.cause = $"Kernel Overseer defeated. {_runManager.Journey.FinalWave}-wave campaign complete.";
|
||
entry.cause ??= entry.surrendered ? "Shutdown signal accepted." : "Uptime reached 0; no damaging action recorded.";
|
||
_runHistoryEntry = entry;
|
||
return entry;
|
||
}
|
||
|
||
private void RefreshSurrenderCommand()
|
||
{
|
||
bool canSurrender = _combatManager.CanSurrenderRun;
|
||
if (!canSurrender)
|
||
{
|
||
_surrenderConfirming = false;
|
||
}
|
||
|
||
if (_surrenderButton != null)
|
||
{
|
||
_surrenderButton.text = _surrenderConfirming ? "> confirm shutdown" : "> shutdown -r run";
|
||
_surrenderButton.SetEnabled(canSurrender);
|
||
_surrenderButton.EnableInClassList("surrender-action-confirming", _surrenderConfirming);
|
||
}
|
||
|
||
if (_surrenderConfirmLabel != null)
|
||
{
|
||
_surrenderConfirmLabel.EnableInClassList("hidden", !_surrenderConfirming);
|
||
_surrenderConfirmLabel.parent.parent.EnableInClassList("confirming", _surrenderConfirming);
|
||
}
|
||
_surrenderCancelButton?.EnableInClassList("hidden", !_surrenderConfirming);
|
||
}
|
||
|
||
private void HandleSurrenderClicked()
|
||
{
|
||
if (!_combatManager.CanSurrenderRun)
|
||
{
|
||
_surrenderConfirming = false;
|
||
RefreshSurrenderCommand();
|
||
return;
|
||
}
|
||
|
||
if (!_surrenderConfirming)
|
||
{
|
||
_surrenderConfirming = true;
|
||
RefreshSurrenderCommand();
|
||
_root?.Focus();
|
||
return;
|
||
}
|
||
|
||
ConfirmSurrender();
|
||
}
|
||
|
||
private void ConfirmSurrender()
|
||
{
|
||
if (!_combatManager.CanSurrenderRun)
|
||
{
|
||
_surrenderConfirming = false;
|
||
RefreshSurrenderCommand();
|
||
return;
|
||
}
|
||
|
||
_surrenderConfirming = false;
|
||
_runEndedBySurrender = true;
|
||
_runTelemetry?.MarkSurrender();
|
||
_combatManager.SurrenderRun();
|
||
}
|
||
|
||
private void CancelSurrender()
|
||
{
|
||
if (!_surrenderConfirming)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_surrenderConfirming = false;
|
||
RefreshSurrenderCommand();
|
||
_surrenderButton?.Focus();
|
||
}
|
||
|
||
private void RefreshOverlay()
|
||
{
|
||
if (_overlay == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
if (_combatManager.Python.HasChoice && !_combatManager.RunFinished)
|
||
{
|
||
_pileInspectorOpen = false;
|
||
_overlay.RemoveFromClassList("pile-overlay");
|
||
TerminalTheme.PreserveFocus(_overlay);
|
||
_overlay.Clear();
|
||
_overlay.style.display = DisplayStyle.Flex;
|
||
_overlay.AddToClassList("python-choice-overlay");
|
||
var dialog = new VisualElement { name = "PythonChoiceDialog" };
|
||
dialog.AddToClassList("python-choice-dialog");
|
||
dialog.Add(SoftwareCardView.Text("[ python / select one ]", "python-choice-eyebrow"));
|
||
string heading = _combatManager.Python.ChoiceTitle;
|
||
int separator = heading.IndexOf(':');
|
||
dialog.Add(SoftwareCardView.Text(separator < 0 ? heading : heading.Substring(0, separator), "python-choice-title"));
|
||
if (separator >= 0)
|
||
dialog.Add(SoftwareCardView.Text(heading.Substring(separator + 1).Trim(), "python-choice-description"));
|
||
var choices = new ScrollView(ScrollViewMode.Vertical) { name = "PythonChoiceScroll" };
|
||
choices.AddToClassList("python-choice-scroll");
|
||
choices.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
|
||
choices.contentContainer.AddToClassList("python-choice-grid");
|
||
for (int i = 0; i < _combatManager.Python.Choices.Count; i++)
|
||
{
|
||
int index = i;
|
||
var option = _combatManager.Python.Choices[i];
|
||
var button = new Button(() => _combatManager.Python.Choose(index)) { name = $"PythonChoice{index}" };
|
||
if (option.Card != null)
|
||
SoftwareCardView.Populate(button, option.Card, option.Cost,
|
||
CardEffectFactory.GetRulesText(option.Card, _combatManager.RunConfig));
|
||
else
|
||
button.Add(SoftwareCardView.Text(option.Label, "python-choice-description"));
|
||
button.AddToClassList("python-choice-option");
|
||
// These choices already show the complete rules; a repeated tooltip
|
||
// would cover the dialog header on small screens.
|
||
button.tooltip = null;
|
||
button.Add(SoftwareCardView.Text(option.ActionLabel ?? "> replace script", "python-choice-action"));
|
||
button.SetEnabled(option.Enabled);
|
||
choices.Add(button);
|
||
}
|
||
dialog.Add(choices);
|
||
dialog.Add(SoftwareCardView.Text("Tab / Shift+Tab to browse · Enter to select", "python-choice-hint"));
|
||
// Intercept focus before ScrollView tracks it: its automatic scrolling
|
||
// aligns oversized cards to their bottom, hiding the card's name.
|
||
dialog.RegisterCallback<FocusInEvent>(evt =>
|
||
{
|
||
if (evt.target is not Button focused || !focused.ClassListContains("python-choice-option")) return;
|
||
evt.StopPropagation();
|
||
void RevealChoice()
|
||
{
|
||
if (focused.worldBound.height > choices.contentViewport.worldBound.height)
|
||
choices.scrollOffset = new Vector2(0, Mathf.Max(0,
|
||
focused.worldBound.yMin - choices.contentContainer.worldBound.yMin));
|
||
else choices.ScrollTo(focused);
|
||
}
|
||
RevealChoice();
|
||
// Repeat after layout for newly attached cards, but never scroll back
|
||
// to a stale selection after the player has moved focus again.
|
||
choices.schedule.Execute(() =>
|
||
{
|
||
if (dialog.focusController?.focusedElement == focused) RevealChoice();
|
||
});
|
||
}, TrickleDown.TrickleDown);
|
||
TerminalTheme.ConstrainModalFocus(dialog);
|
||
_overlay.Add(dialog);
|
||
choices.Query<Button>().ToList().Find(b => b.enabledSelf)?.Focus();
|
||
return;
|
||
}
|
||
|
||
_overlay.RemoveFromClassList("python-choice-overlay");
|
||
|
||
if (_pileInspectorOpen && !_combatManager.RunFinished && !_combatManager.AwaitingWaveContinue
|
||
&& _combatManager.CurrentPhase == TurnPhase.Execute) return;
|
||
_pileInspectorOpen = false;
|
||
if (_tutorial != null) { _overlay.RemoveFromClassList("pile-overlay"); _tutorial.Refresh(); return; }
|
||
TerminalTheme.PreserveFocus(_overlay);
|
||
_overlay.RemoveFromClassList("pile-overlay");
|
||
bool wasVisible = _overlay.style.display == DisplayStyle.Flex;
|
||
_overlay.Clear();
|
||
if (_combatManager.RunFinished)
|
||
{
|
||
_routeSelectionOpen = false;
|
||
_routeEventOpen = false;
|
||
SettleRunRewardsIfNeeded();
|
||
_overlay.style.display = DisplayStyle.Flex;
|
||
_overlay.Add(BuildRunEndOverlay());
|
||
if (!wasVisible) _overlay.Q<Button>()?.Focus();
|
||
return;
|
||
}
|
||
|
||
_runEndOverlayPresented = false;
|
||
_runEndedBySurrender = false;
|
||
if (_combatManager.AwaitingWaveContinue)
|
||
{
|
||
if (!_runManager.RepositoryVisitActive)
|
||
{
|
||
_runManager.GenerateRepositoryOffers(cardDatabase, languageDeckDatabase);
|
||
return;
|
||
}
|
||
|
||
_overlay.style.display = DisplayStyle.Flex;
|
||
_overlay.Add(_routeSelectionOpen ? BuildRouteSelectionView() : BuildRepositoryView());
|
||
if (!wasVisible) _overlay.Q<Button>()?.Focus();
|
||
return;
|
||
}
|
||
|
||
_routeSelectionOpen = false;
|
||
_routeEventOpen = false;
|
||
_overlay.style.display = DisplayStyle.None;
|
||
}
|
||
|
||
private VisualElement BuildRunEndOverlay()
|
||
{
|
||
_runEndedBySurrender |= _combatManager.RunEndedBySurrender;
|
||
VisualElement screen = new();
|
||
screen.AddToClassList("death-overlay");
|
||
screen.EnableInClassList("death-surrender", _runEndedBySurrender);
|
||
screen.EnableInClassList("run-victory", _combatManager.RunCompleted);
|
||
|
||
if (!_runEndOverlayPresented)
|
||
{
|
||
_runEndOverlayPresented = true;
|
||
if (!UIPreferences.ReducedMotion && !_combatManager.RunCompleted)
|
||
{
|
||
VisualElement beat = new();
|
||
beat.AddToClassList("death-crash-beat");
|
||
screen.Add(beat);
|
||
screen.schedule.Execute(() => beat.AddToClassList("death-crash-beat-settled")).StartingIn(25);
|
||
screen.schedule.Execute(() => beat.RemoveFromHierarchy()).StartingIn(260);
|
||
}
|
||
}
|
||
|
||
VisualElement content = new();
|
||
content.AddToClassList("death-content");
|
||
|
||
var config = _runManager.CurrentConfig;
|
||
VisualElement reportHeader = new();
|
||
reportHeader.AddToClassList("death-report-header");
|
||
reportHeader.Add(SoftwareCardView.Text("RUN REPORT", "death-eyebrow"));
|
||
reportHeader.Add(SoftwareCardView.Text($"seed {config?.RunSeed ?? 0}", "death-seed"));
|
||
content.Add(reportHeader);
|
||
content.Add(OverlayTitle(_combatManager.RunCompleted ? "KERNEL SECURED" : _runEndedBySurrender ? "SYSTEM HALTED" : "KERNEL PANIC"));
|
||
|
||
var report = GetRunHistoryEntry();
|
||
string cause = report.cause;
|
||
Label causeLabel = OverlayLine(cause);
|
||
causeLabel.AddToClassList("death-cause");
|
||
content.Add(causeLabel);
|
||
if (config?.Distro != null)
|
||
content.Add(SoftwareCardView.Text($"{DisplayName(config.Distro)} V{config.DistroVersion} / {config.PrimaryLanguage} + {config.SecondaryLanguage}", "death-session"));
|
||
|
||
VisualElement summary = new();
|
||
summary.AddToClassList("death-section");
|
||
summary.AddToClassList("death-summary");
|
||
summary.AddToClassList("death-wave-stats");
|
||
summary.Add(DeathStat("wave reached", report.waveReached.ToString()));
|
||
summary.Add(DeathStat("waves cleared", _runManager.WavesCleared.ToString()));
|
||
content.Add(summary);
|
||
|
||
bool recapUnavailable = report.victory && report.finalRound == 0;
|
||
content.Add(SoftwareCardView.Text(recapUnavailable ? "COMBAT RECAP" : $"FINAL ROUND {report.finalRound}", "death-eyebrow"));
|
||
var recap = new VisualElement();
|
||
recap.AddToClassList("death-section");
|
||
recap.Add(OverlayLine(recapUnavailable ? "Combat recap unavailable after resuming this checkpoint."
|
||
: $"{report.damageDealt} uptime dealt / {report.damageTaken} uptime lost / {report.shieldBlocked} blocked by shield"));
|
||
if (report.finalHits.Count > 0)
|
||
{
|
||
var hits = new Foldout { text = "Last incoming hits (up to 8)", value = false };
|
||
foreach (string hit in report.finalHits) hits.Add(OverlayLine(hit));
|
||
recap.Add(hits);
|
||
}
|
||
content.Add(recap);
|
||
|
||
content.Add(SoftwareCardView.Text("RECOVERED RESOURCES", "death-eyebrow"));
|
||
VisualElement rewards = new();
|
||
rewards.AddToClassList("death-section");
|
||
rewards.AddToClassList("death-rewards");
|
||
rewards.Add(RewardReadout("#", _runManager.AccruedBandwidth, "bandwidth", false));
|
||
rewards.Add(RewardReadout("*", _runManager.AccruedEntropy, "entropy", _runManager.AccruedEntropy <= 0));
|
||
content.Add(rewards);
|
||
content.Add(SoftwareCardView.Text("Return to your collection to prepare the next run.", "death-next-run"));
|
||
|
||
Button returnButton = new(() => SceneLoader.LoadMainMenu(_root)) { text = "> return to menu" };
|
||
returnButton.AddToClassList("primary-action");
|
||
returnButton.AddToClassList("death-return-action");
|
||
if (!string.IsNullOrEmpty(_saveError))
|
||
{
|
||
content.Add(OverlayLine((_runManager.RewardsSettled ? "Could not reload saved progress: " : "Rewards are not saved yet: ") + _saveError));
|
||
var retrySave = new Button(() => { SettleRunRewardsIfNeeded(); Refresh(); }) { text = "Retry saving rewards" };
|
||
content.Add(retrySave);
|
||
returnButton.SetEnabled(_runManager.RewardsSettled);
|
||
}
|
||
content.Add(returnButton);
|
||
|
||
var scroll = new ScrollView(ScrollViewMode.Vertical);
|
||
scroll.AddToClassList("death-scroll");
|
||
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
|
||
// Center within the actual viewport, including Unity's internal ScrollView wrapper.
|
||
// A minimum (not fixed) height lets short windows scroll the entire report.
|
||
scroll.contentContainer.style.alignItems = Align.Center;
|
||
scroll.contentContainer.style.justifyContent = Justify.Center;
|
||
scroll.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
|
||
scroll.contentContainer.style.minHeight = evt.newRect.height);
|
||
scroll.Add(content);
|
||
screen.Add(scroll);
|
||
return screen;
|
||
}
|
||
|
||
private void SettleRunRewardsIfNeeded()
|
||
{
|
||
if (_runManager?.CurrentConfig?.IsTutorial == true) return;
|
||
if (_runManager == null || _saveService == null || _runManager.IsSuspended || _runManager.CurrentConfig == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
if (_runManager.RewardsSettled)
|
||
{
|
||
return;
|
||
}
|
||
|
||
try
|
||
{
|
||
SaveData data = _saveService.Load();
|
||
data.bandwidthBalance = Math.Max(0, data.bandwidthBalance) + _runManager.AccruedBandwidth;
|
||
data.entropyBalance = Math.Max(0, data.entropyBalance) + _runManager.AccruedEntropy;
|
||
data.RecordRunStats(_runManager.CurrentConfig?.Distro?.Id,
|
||
_combatManager.RunCompleted ? _runManager.WavesCleared : _runManager.CurrentWaveNumber);
|
||
if (_combatManager.RunFinished) RunHistory.Record(data.recentRuns, GetRunHistoryEntry());
|
||
if (data.activeRun?.runId == _runManager.RunId) data.activeRun = null;
|
||
_saveService.Save(data);
|
||
_lastKnownSave = data;
|
||
_runManager.MarkRunRewardsSettled();
|
||
_saveError = null;
|
||
}
|
||
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
|
||
{
|
||
_saveError = ex.Message;
|
||
}
|
||
}
|
||
|
||
private VisualElement BuildRepositoryView()
|
||
{
|
||
VisualElement repo = new();
|
||
repo.AddToClassList("repository");
|
||
repo.AddToClassList("screen-frame");
|
||
repo.Add(BuildRepositoryHeader());
|
||
|
||
ScrollView body = new(ScrollViewMode.Vertical);
|
||
body.AddToClassList("repository-body");
|
||
body.AddToClassList("screen-frame-content");
|
||
|
||
VisualElement offers = new();
|
||
offers.AddToClassList("repository-offers");
|
||
if (_runManager.RepositoryOffers.Count == 0)
|
||
{
|
||
offers.Add(EmptyState("repository clean: no offers left this visit"));
|
||
}
|
||
else
|
||
{
|
||
for (int i = 0; i < _runManager.RepositoryOffers.Count; i++)
|
||
{
|
||
offers.Add(RepositoryOfferTile(_runManager.RepositoryOffers[i]));
|
||
}
|
||
}
|
||
|
||
body.Add(offers);
|
||
body.Add(RemoveCardBlock());
|
||
repo.Add(body);
|
||
|
||
VisualElement footer = new();
|
||
footer.AddToClassList("repository-footer");
|
||
footer.AddToClassList("screen-frame-footer");
|
||
Button reroll = new(() => _runManager.RerollRepositoryOffers(cardDatabase, languageDeckDatabase))
|
||
{
|
||
text = $"apt update {_runManager.RerollCost} bits"
|
||
};
|
||
reroll.AddToClassList("primary-action");
|
||
reroll.AddToClassList("repository-footer-action");
|
||
reroll.AddToClassList("repository-reroll-action");
|
||
reroll.EnableInClassList("repo-unaffordable", _runManager.Bits < _runManager.RerollCost);
|
||
reroll.SetEnabled(_runManager.Bits >= _runManager.RerollCost);
|
||
footer.Add(reroll);
|
||
|
||
Button leave = new(() =>
|
||
{
|
||
if (_runManager.Journey.campaign) SetRouteSelectionOpen(true);
|
||
else _combatManager.ContinueToNextWave();
|
||
}) { name = "BootNextWaveButton", text = "> boot next-wave" };
|
||
leave.AddToClassList("primary-action");
|
||
leave.AddToClassList("repository-leave-action");
|
||
leave.SetEnabled(!_runManager.IsSuspended);
|
||
VisualElement leaveBlock = new();
|
||
leaveBlock.AddToClassList("repository-leave-block");
|
||
leaveBlock.Add(leave);
|
||
Label banked = new($"{_runManager.Bits} bits remaining");
|
||
banked.AddToClassList("repository-banked-hint");
|
||
banked.AddToClassList("screen-frame-hint");
|
||
leaveBlock.Add(banked);
|
||
var suspend = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save & exit" };
|
||
suspend.AddToClassList("primary-action");
|
||
suspend.AddToClassList("repository-leave-action");
|
||
suspend.SetEnabled(!_runManager.IsSuspended);
|
||
leaveBlock.Add(suspend);
|
||
if (!string.IsNullOrEmpty(_checkpointError))
|
||
leaveBlock.Add(TerminalLayout.BodyText("Save failed: " + _checkpointError + " Stay here and retry.", className: "screen-frame-hint"));
|
||
footer.Add(leaveBlock);
|
||
repo.Add(footer);
|
||
return repo;
|
||
}
|
||
|
||
private void SetRouteSelectionOpen(bool open)
|
||
{
|
||
_routeSelectionOpen = open;
|
||
_routeEventOpen = false;
|
||
RefreshOverlay();
|
||
_overlay.Q<Button>(open ? "BackToRepositoryButton" : "BootNextWaveButton")?.Focus();
|
||
}
|
||
|
||
private VisualElement BuildRouteSelectionView()
|
||
{
|
||
bool reward = _runManager.BuildRewardPending;
|
||
bool eventScreen = !reward && _routeEventOpen && !_runManager.CampaignChoicePending;
|
||
bool committed = eventScreen && !_runManager.RouteEventPending;
|
||
var screen = new VisualElement { name = reward ? "BuildRewardScreen" : eventScreen ? "RouteEventScreen" : "RouteSelectionScreen" };
|
||
screen.AddToClassList("repository");
|
||
screen.AddToClassList("screen-frame");
|
||
screen.AddToClassList("route-map-screen");
|
||
var header = new VisualElement();
|
||
header.AddToClassList("repository-header");
|
||
header.AddToClassList("screen-frame-header");
|
||
var copy = new VisualElement();
|
||
copy.AddToClassList("repository-header-copy");
|
||
var title = new Label(_runManager.CampaignChoicePending ? "campaign complete" : reward ? "claim your build reward"
|
||
: eventScreen ? RunRouteMap.Title(_runManager.Journey.selectedRoute) : "choose your route");
|
||
title.AddToClassList("screen-frame-title");
|
||
copy.Add(title);
|
||
var subtitle = new Label(_runManager.CampaignChoicePending
|
||
? "bank your rewards or continue into endless"
|
||
: reward ? "1. claim reward > 2. choose route > 3. enter stop"
|
||
: eventScreen ? committed ? "stop complete. ready for battle" : "choose your cards. nothing changes until you confirm"
|
||
: $"preparing wave {_runManager.CurrentWaveNumber} {_runManager.Bits} bits remaining");
|
||
subtitle.AddToClassList("repository-subtitle");
|
||
copy.Add(subtitle);
|
||
header.Add(copy);
|
||
screen.Add(header);
|
||
|
||
var body = new ScrollView(ScrollViewMode.Vertical);
|
||
body.AddToClassList("repository-body");
|
||
body.AddToClassList("screen-frame-content");
|
||
body.Add(reward ? RunRouteView.BuildReward(_runManager)
|
||
: eventScreen ? RunMapView.BuildEvent(_runManager) : RunRouteView.Build(_runManager, _combatManager));
|
||
if (!reward && !eventScreen && !_runManager.CampaignChoicePending)
|
||
{
|
||
body.AddToClassList("route-map-body");
|
||
body.contentViewport.RegisterCallback<GeometryChangedEvent>(evt =>
|
||
{
|
||
var mapScroll = body.Q<ScrollView>("RouteMapScroll");
|
||
if (mapScroll != null)
|
||
mapScroll.style.height = Mathf.Max(260, evt.newRect.height - 20);
|
||
});
|
||
}
|
||
if (committed)
|
||
{
|
||
var save = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "save and exit" };
|
||
save.AddToClassList("secondary-action"); body.Add(save);
|
||
}
|
||
screen.Add(body);
|
||
|
||
var footer = new VisualElement();
|
||
footer.AddToClassList("screen-frame-footer");
|
||
footer.AddToClassList("route-map-footer");
|
||
var back = new Button(() =>
|
||
{
|
||
if (!eventScreen) SetRouteSelectionOpen(false);
|
||
else if (_runManager.RouteEventPending)
|
||
{
|
||
_routeEventOpen = false; RefreshOverlay();
|
||
_overlay.Q<Button>("ConfirmRouteButton")?.Focus();
|
||
}
|
||
})
|
||
{ name = eventScreen ? "BackToRouteButton" : "BackToRepositoryButton",
|
||
text = committed ? "stop committed" : eventScreen ? "< back to map" : "< back to repository" };
|
||
back.SetEnabled(!committed);
|
||
back.AddToClassList("primary-action");
|
||
back.AddToClassList("route-map-back");
|
||
footer.Add(back);
|
||
screen.RegisterCallback<KeyDownEvent>(evt =>
|
||
{
|
||
if (evt.keyCode != KeyCode.Escape || !back.enabledSelf) return;
|
||
using var submit = NavigationSubmitEvent.GetPooled();
|
||
submit.target = back; back.SendEvent(submit); evt.StopPropagation();
|
||
});
|
||
void MoveAction(string name, string caption = null)
|
||
{
|
||
var button = body.Q<Button>(name);
|
||
if (button == null) return;
|
||
button.RemoveFromHierarchy();
|
||
if (caption != null) button.text = caption;
|
||
if (name == "ResolveRouteEventButton")
|
||
{
|
||
string fullCaption = button.text;
|
||
button.RegisterCallback<GeometryChangedEvent>(evt => button.text = evt.newRect.width < 160 ? "apply" : fullCaption);
|
||
}
|
||
button.AddToClassList("primary-action");
|
||
button.AddToClassList(name is "ClaimBuildRewardButton" or "ResolveRouteEventButton" ? "route-map-continue" : "route-map-back");
|
||
footer.Add(button);
|
||
}
|
||
if (reward)
|
||
{
|
||
back.text = "< back"; back.tooltip = "Back to repository";
|
||
MoveAction("RewardBits", $"{RunManager.BuildRewardBits} Bits");
|
||
MoveAction("ClaimBuildRewardButton", "claim");
|
||
}
|
||
else if (eventScreen && !committed)
|
||
{
|
||
back.text = "< map";
|
||
MoveAction("SkipRouteEventButton", "pass");
|
||
MoveAction("ResolveRouteEventButton");
|
||
}
|
||
else if (!_runManager.CampaignChoicePending)
|
||
{
|
||
var confirm = new Button(() =>
|
||
{
|
||
if (_runManager.RouteEventPending && !eventScreen)
|
||
{
|
||
_routeEventOpen = true; RefreshOverlay();
|
||
_overlay.Q<Button>("BackToRouteButton")?.Focus();
|
||
}
|
||
else _combatManager.ContinueToNextWave();
|
||
})
|
||
{
|
||
name = "ConfirmRouteButton",
|
||
text = eventScreen ? committed ? "> continue to battle" : "confirm or pass above"
|
||
: _runManager.RouteEventPending ? "> enter stop" : "> continue to battle"
|
||
};
|
||
confirm.AddToClassList("primary-action");
|
||
confirm.AddToClassList("route-map-continue");
|
||
confirm.SetEnabled((!eventScreen || committed) && !_runManager.IsSuspended);
|
||
footer.Add(confirm);
|
||
}
|
||
screen.Add(footer);
|
||
if (committed) screen.schedule.Execute(() => screen.Q<Button>("ConfirmRouteButton")?.Focus());
|
||
return screen;
|
||
}
|
||
|
||
private void SaveAndExitRun()
|
||
{
|
||
if (_runManager.IsSuspended || !_combatManager.AwaitingWaveContinue) return;
|
||
try
|
||
{
|
||
if (_dailyQuestTracker?.Flush() == false)
|
||
throw new IOException("Daily quest progress: " + _dailyQuestTracker.SaveError);
|
||
RunCheckpointService.SaveAndSuspend(_saveService, _runManager, _combatManager);
|
||
_checkpointError = null;
|
||
_overlay.SetEnabled(false);
|
||
SceneLoader.LoadMainMenu(_root);
|
||
}
|
||
catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException)
|
||
{
|
||
_checkpointError = ex.Message;
|
||
Refresh();
|
||
}
|
||
}
|
||
|
||
private VisualElement BuildRepositoryHeader()
|
||
{
|
||
VisualElement header = new();
|
||
header.AddToClassList("repository-header");
|
||
header.AddToClassList("screen-frame-header");
|
||
|
||
VisualElement copy = new();
|
||
copy.AddToClassList("repository-header-copy");
|
||
Label title = new("repository");
|
||
title.AddToClassList("repository-title");
|
||
title.AddToClassList("screen-frame-title");
|
||
Label subtitle = new($"wave {_runManager.CurrentWaveNumber - 1} cleared / {_runManager.RepositoryOffers.Count} packages indexed");
|
||
subtitle.AddToClassList("repository-subtitle");
|
||
copy.Add(title);
|
||
copy.Add(subtitle);
|
||
|
||
VisualElement wallet = new();
|
||
wallet.AddToClassList("repository-wallet");
|
||
Label walletLabel = new("available bits");
|
||
walletLabel.AddToClassList("status-label");
|
||
Label walletValue = new($"◆ {_runManager.Bits}");
|
||
walletValue.AddToClassList("repository-wallet-value");
|
||
wallet.Add(walletLabel);
|
||
wallet.Add(walletValue);
|
||
|
||
header.Add(copy);
|
||
header.Add(wallet);
|
||
return header;
|
||
}
|
||
|
||
private VisualElement RepositoryOfferTile(RepositoryOffer offer)
|
||
{
|
||
VisualElement tile = new();
|
||
tile.AddToClassList("repository-tile");
|
||
tile.AddToClassList(OfferTileClass(offer.Kind));
|
||
bool unavailable = offer.Sold || _runManager.Bits < offer.Price;
|
||
tile.EnableInClassList("repo-unaffordable", unavailable);
|
||
tile.EnableInClassList("repo-sold", offer.Sold);
|
||
|
||
VisualElement top = new();
|
||
top.AddToClassList("repository-tile-top");
|
||
Label kind = new($"{OfferKindIcon(offer.Kind)} {OfferKindText(offer.Kind)}");
|
||
kind.AddToClassList("repository-kind");
|
||
top.Add(kind);
|
||
top.Add(PriceBadge(offer.Price, unavailable));
|
||
tile.Add(top);
|
||
|
||
VisualElement content = offer.Kind switch
|
||
{
|
||
RepositoryOfferKind.NewCard => CardOfferContent(offer),
|
||
RepositoryOfferKind.CardUpgrade => UpgradeOfferContent(offer),
|
||
RepositoryOfferKind.StatUpgrade => StatOfferContent(offer),
|
||
_ => GenericOfferContent(offer)
|
||
};
|
||
tile.Add(content);
|
||
|
||
Button buy = new(() => _runManager.BuyOffer(offer, _combatManager.PlayerState))
|
||
{
|
||
text = offer.Sold ? "installed" : OfferActionText(offer.Kind)
|
||
};
|
||
buy.tooltip = OfferCommandText(offer);
|
||
buy.AddToClassList("repository-action");
|
||
buy.SetEnabled(!offer.Sold && _runManager.Bits >= offer.Price);
|
||
tile.Add(buy);
|
||
return tile;
|
||
}
|
||
|
||
private VisualElement CardOfferContent(RepositoryOffer offer)
|
||
{
|
||
VisualElement content = new();
|
||
content.AddToClassList("repository-card-content");
|
||
CardInstance preview = new(offer.CardDefinition);
|
||
VisualElement card = CardFaceView(preview);
|
||
card.AddToClassList("repository-card-preview");
|
||
content.Add(card);
|
||
|
||
if (offer.CardDefinition != null && offer.CardDefinition.IsRunOnly)
|
||
{
|
||
content.Add(Tag("run-only", "repository-run-only-tag"));
|
||
}
|
||
|
||
return content;
|
||
}
|
||
|
||
private VisualElement UpgradeOfferContent(RepositoryOffer offer)
|
||
{
|
||
VisualElement content = new();
|
||
content.AddToClassList("repository-upgrade-content");
|
||
if (offer.TargetCard != null)
|
||
{
|
||
VisualElement target = CardFaceView(offer.TargetCard);
|
||
target.AddToClassList("repository-upgrade-card");
|
||
content.Add(target);
|
||
}
|
||
|
||
VisualElement delta = new();
|
||
delta.AddToClassList("repository-delta");
|
||
Label arrow = new("▲");
|
||
arrow.AddToClassList("repository-delta-icon");
|
||
Label text = new(offer.Description);
|
||
text.AddToClassList("repository-delta-text");
|
||
delta.Add(arrow);
|
||
delta.Add(text);
|
||
content.Add(delta);
|
||
return content;
|
||
}
|
||
|
||
private VisualElement StatOfferContent(RepositoryOffer offer)
|
||
{
|
||
VisualElement content = new();
|
||
content.AddToClassList("repository-stat-content");
|
||
Label icon = new(StatOfferIcon(offer.StatUpgradeKind));
|
||
icon.AddToClassList("repository-stat-icon");
|
||
Label name = new(offer.DisplayName);
|
||
name.AddToClassList("repository-name");
|
||
Label description = new(offer.Description);
|
||
description.AddToClassList("repository-description");
|
||
content.Add(icon);
|
||
content.Add(name);
|
||
content.Add(description);
|
||
return content;
|
||
}
|
||
|
||
private static VisualElement GenericOfferContent(RepositoryOffer offer)
|
||
{
|
||
VisualElement content = new();
|
||
Label name = new(offer.DisplayName);
|
||
name.AddToClassList("repository-name");
|
||
Label description = new(offer.Description);
|
||
description.AddToClassList("repository-description");
|
||
content.Add(name);
|
||
content.Add(description);
|
||
return content;
|
||
}
|
||
|
||
private static VisualElement PriceBadge(int price, bool warning)
|
||
{
|
||
Label badge = new($"◆ {price}");
|
||
badge.AddToClassList("repository-price");
|
||
badge.EnableInClassList("repository-price-warning", warning);
|
||
return badge;
|
||
}
|
||
|
||
private VisualElement RemoveCardBlock()
|
||
{
|
||
VisualElement block = new();
|
||
block.AddToClassList("repository-remove");
|
||
Label title = new($"installed deck maintenance / remove for {CombatTuning.RemoveCardCost} bit");
|
||
title.AddToClassList("repository-name");
|
||
block.Add(title);
|
||
|
||
VisualElement rows = new();
|
||
rows.AddToClassList("repository-remove-list");
|
||
for (int i = 0; i < _runManager.RunDeck.Count; i++)
|
||
{
|
||
CardInstance card = _runManager.RunDeck[i];
|
||
Button remove = new(() => _runManager.RemoveCard(card))
|
||
{
|
||
text = $"apt remove {DisplayName(card.Definition)}"
|
||
};
|
||
remove.AddToClassList("repo-remove-button");
|
||
remove.EnableInClassList("repo-unaffordable", _runManager.Bits < CombatTuning.RemoveCardCost || _runManager.RunDeck.Count <= 1);
|
||
remove.SetEnabled(_runManager.Bits >= CombatTuning.RemoveCardCost && _runManager.RunDeck.Count > 1);
|
||
rows.Add(remove);
|
||
}
|
||
|
||
block.Add(rows);
|
||
return block;
|
||
}
|
||
|
||
private VisualElement CardFace(CardInstance card)
|
||
{
|
||
Button button = new(() =>
|
||
{
|
||
if (card.IsLocked)
|
||
{
|
||
UnlockCardWithFeedback(card);
|
||
return;
|
||
}
|
||
|
||
PlayCardWithFeedback(card);
|
||
});
|
||
button.text = string.Empty;
|
||
button.userData = card;
|
||
button.AddToClassList("hand-card");
|
||
if (_combatManager.PendingTargetCard == card)
|
||
{
|
||
button.AddToClassList("hand-card-selected");
|
||
}
|
||
|
||
if (GetDisplayCardCost(card) > _combatManager.PlayerState.Cycles)
|
||
{
|
||
button.AddToClassList("hand-card-unaffordable");
|
||
}
|
||
|
||
if (card.IsBroken || card.IsLocked)
|
||
{
|
||
button.AddToClassList("hand-card-unaffordable");
|
||
button.SetEnabled(!card.IsBroken);
|
||
}
|
||
|
||
PopulateCardFace(button, card);
|
||
return button;
|
||
}
|
||
|
||
private VisualElement CardFaceView(CardInstance card)
|
||
{
|
||
VisualElement face = new();
|
||
face.AddToClassList("hand-card");
|
||
SoftwareCardView.Populate(face, card, GetDisplayCardCost(card), CardEffectFactory.GetRulesText(card, _combatManager.RunConfig));
|
||
return face;
|
||
}
|
||
|
||
private void PopulateCardFace(VisualElement target, CardInstance card)
|
||
{
|
||
SoftwareCardView.Populate(target, card, GetDisplayCardCost(card), CardEffectFactory.GetRulesText(card, _combatManager.RunConfig));
|
||
var preview = CardPreviewService.Build(_combatManager, card);
|
||
if (!string.IsNullOrEmpty(preview.Summary) && !preview.Summary.StartsWith("Utility", StringComparison.Ordinal))
|
||
{
|
||
string timing = card.Definition.ResolutionTrack == ResolutionTrack.Native ? "now: " : "preview: ";
|
||
var label = SoftwareCardView.Text(timing + preview.Summary + (preview.IsConditional ? " *" : ""), "software-live-preview");
|
||
target.Q(className: "software-body")?.Add(label);
|
||
}
|
||
// Rules are already printed on the card. Keep hover help contextual and brief.
|
||
target.tooltip = card.IsBroken ? CardPreviewService.CorruptionDetails(card)
|
||
: card.IsLocked ? "Unlock for 1 Cycle before playing."
|
||
: preview.IsConditional ? "Current estimate; targets, defenses and later effects can change the result."
|
||
: "";
|
||
}
|
||
|
||
private static VisualElement IntentPanel(EnemyIntent intent)
|
||
{
|
||
VisualElement panel = new();
|
||
panel.AddToClassList("intent-panel");
|
||
string className = IntentClass(intent.Kind);
|
||
panel.AddToClassList(className);
|
||
|
||
Label label = new("next");
|
||
label.AddToClassList("intent-label");
|
||
Label value = new($"{IntentIcon(intent)} {intent.ValueText}");
|
||
value.AddToClassList("intent-value");
|
||
value.AddToClassList(className);
|
||
Label detail = new(IntentText(intent));
|
||
detail.AddToClassList("status-label");
|
||
var heading = new VisualElement();
|
||
heading.AddToClassList("intent-heading");
|
||
heading.Add(label);
|
||
heading.Add(value);
|
||
panel.Add(heading);
|
||
panel.Add(detail);
|
||
return panel;
|
||
}
|
||
|
||
private static VisualElement EnemySignalPanel(EnemyInstance enemy, IReadOnlyList<EnemyInstance> enemies)
|
||
{
|
||
VisualElement row = new();
|
||
row.AddToClassList("status-row");
|
||
|
||
if (enemy.SpawnedFromDeath)
|
||
{
|
||
row.Add(Tag(". orphaned", "track-tag"));
|
||
}
|
||
|
||
if (enemy.HasEliteSignal)
|
||
{
|
||
row.Add(Tag("! elite", "intent-attack"));
|
||
}
|
||
|
||
if (enemy.HasRamPressureSignal)
|
||
{
|
||
row.Add(Tag($"# RAM -{EnemyArchetypeCatalog.KernelPanicRamPenalty}", "intent-attack"));
|
||
}
|
||
|
||
if (enemy.HasTelemetrySignal)
|
||
{
|
||
row.Add(Tag($"+ profile {enemy.TelemetryStacks}", "intent-special"));
|
||
}
|
||
|
||
if (enemy.HasCardLockerSignal)
|
||
{
|
||
row.Add(Tag($"$ lock {EnemyArchetypeCatalog.DrmUnlockCycleCost}c", "intent-special"));
|
||
}
|
||
|
||
if (enemy.HasSplitSignal)
|
||
{
|
||
string text = CountLivingArchetype(enemies, enemy.ArchetypeId) >= EnemyArchetypeCatalog.ForkBombTotalCap
|
||
? ": split capped"
|
||
: ": split next";
|
||
row.Add(Tag(text, "track-tag"));
|
||
}
|
||
|
||
if (enemy.HasSegfaultSignal)
|
||
{
|
||
row.Add(Tag($"! corrupt in {enemy.CountdownRemaining}", "track-tag"));
|
||
}
|
||
|
||
if (enemy.HasRaceSignal)
|
||
{
|
||
string text = HasLivingPair(enemies, enemy) ? "~ linked random" : "~ unlinked";
|
||
row.Add(Tag(text, "track-tag"));
|
||
}
|
||
|
||
if (enemy.HasRootkitSignal)
|
||
{
|
||
string text = HasOtherLivingEnemy(enemies, enemy) ? "? masked reduced" : "? exposed";
|
||
row.Add(Tag(text, "track-tag"));
|
||
}
|
||
|
||
return row;
|
||
}
|
||
|
||
private static int CountLivingArchetype(IReadOnlyList<EnemyInstance> enemies, string archetypeId)
|
||
{
|
||
int count = 0;
|
||
for (int i = 0; i < enemies.Count; i++)
|
||
{
|
||
EnemyInstance enemy = enemies[i];
|
||
if (enemy.ArchetypeId == archetypeId && !enemy.State.IsDefeated)
|
||
{
|
||
count++;
|
||
}
|
||
}
|
||
|
||
return count;
|
||
}
|
||
|
||
private static bool HasLivingPair(IReadOnlyList<EnemyInstance> enemies, EnemyInstance target)
|
||
{
|
||
if (target == null || target.PairId < 0)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
for (int i = 0; i < enemies.Count; i++)
|
||
{
|
||
EnemyInstance enemy = enemies[i];
|
||
if (enemy != target && enemy.PairId == target.PairId && !enemy.State.IsDefeated)
|
||
{
|
||
return true;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private static bool HasOtherLivingEnemy(IReadOnlyList<EnemyInstance> enemies, EnemyInstance target)
|
||
{
|
||
for (int i = 0; i < enemies.Count; i++)
|
||
{
|
||
EnemyInstance enemy = enemies[i];
|
||
if (enemy != target && !enemy.State.IsDefeated)
|
||
{
|
||
return true;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private static VisualElement MeterBlock(string name, int current, int max, MeterTone tone)
|
||
{
|
||
float ratio = max <= 0 ? 0f : Mathf.Clamp01((float)current / max);
|
||
VisualElement block = new();
|
||
block.AddToClassList("meter-block");
|
||
|
||
VisualElement head = new();
|
||
head.AddToClassList("meter-head");
|
||
Label label = new(name);
|
||
label.AddToClassList("metric-label");
|
||
Label value = new(max <= 0 ? current.ToString() : $"{current}/{max}");
|
||
value.AddToClassList(tone == MeterTone.Muted ? "metric-value-muted" : "metric-value");
|
||
head.Add(label);
|
||
head.Add(value);
|
||
block.Add(head);
|
||
|
||
VisualElement track = new();
|
||
track.AddToClassList("meter-track");
|
||
VisualElement fill = new();
|
||
fill.AddToClassList("meter-fill");
|
||
fill.AddToClassList(MeterFillClass(tone, ratio));
|
||
fill.style.width = Length.Percent(ratio * 100f);
|
||
track.Add(fill);
|
||
block.Add(track);
|
||
return block;
|
||
}
|
||
|
||
private static void UpdateMeter(VisualElement block, int current, int max)
|
||
{
|
||
block.Q<Label>(className: "metric-value").text = $"{current}/{max}";
|
||
var fill = block.Q(className: "meter-fill");
|
||
float ratio = max <= 0 ? 0 : Mathf.Clamp01((float)current / max);
|
||
fill.EnableInClassList("meter-fill-warning", ratio <= 0.5f && ratio > 0.25f);
|
||
fill.EnableInClassList("meter-fill-danger", ratio <= 0.25f);
|
||
fill.style.width = Length.Percent(ratio * 100);
|
||
}
|
||
|
||
private static VisualElement CycleBlock(int current, int max)
|
||
{
|
||
VisualElement block = new();
|
||
block.AddToClassList("cycle-row");
|
||
VisualElement head = new();
|
||
head.AddToClassList("meter-head");
|
||
Label label = new("cycles");
|
||
label.AddToClassList("metric-label");
|
||
Label value = new($"{current}/{max}");
|
||
value.AddToClassList("metric-value");
|
||
head.Add(label);
|
||
head.Add(value);
|
||
block.Add(head);
|
||
|
||
Label pips = new(BuildPips(current, max));
|
||
pips.AddToClassList("cycle-pips");
|
||
block.Add(pips);
|
||
return block;
|
||
}
|
||
|
||
private VisualElement FedoraRiskMeter(float chancePercent)
|
||
{
|
||
float clamped = Mathf.Clamp(chancePercent, 0f, 100f);
|
||
VisualElement block = new();
|
||
block.AddToClassList("meter-block");
|
||
block.AddToClassList("fedora-risk-meter");
|
||
|
||
VisualElement head = new();
|
||
head.AddToClassList("meter-head");
|
||
Label label = new("crash risk");
|
||
label.AddToClassList("metric-label");
|
||
Label value = new($"{clamped:0.#}%");
|
||
value.AddToClassList("metric-value");
|
||
head.Add(label);
|
||
head.Add(value);
|
||
block.Add(head);
|
||
|
||
VisualElement track = new();
|
||
track.AddToClassList("meter-track");
|
||
VisualElement fill = new();
|
||
fill.AddToClassList("meter-fill");
|
||
fill.AddToClassList(FedoraRiskFillClass(clamped));
|
||
fill.style.width = Length.Percent(clamped);
|
||
track.Add(fill);
|
||
block.Add(track);
|
||
|
||
_fedoraRiskFillElement = fill;
|
||
_fedoraRiskValueLabel = value;
|
||
return block;
|
||
}
|
||
|
||
private static string FedoraRiskFillClass(float chancePercent)
|
||
{
|
||
if (chancePercent >= 50f)
|
||
{
|
||
return "meter-fill-danger";
|
||
}
|
||
|
||
return chancePercent >= 25f ? "meter-fill-warning" : "meter-fill";
|
||
}
|
||
|
||
private VisualElement ArchBtwCounter(int stacks)
|
||
{
|
||
VisualElement block = new();
|
||
block.AddToClassList("arch-btw-counter");
|
||
Label label = new($"btw ×{stacks}");
|
||
label.AddToClassList("arch-btw-value");
|
||
label.style.color = _distroAccent;
|
||
block.Add(label);
|
||
_archBtwCounterLabel = label;
|
||
return block;
|
||
}
|
||
|
||
private static VisualElement StatusBlock(CombatantState state, bool includeTooltips)
|
||
{
|
||
VisualElement block = new();
|
||
block.AddToClassList("host-statuses");
|
||
block.EnableInClassList("host-statuses-empty", state.Statuses.Count == 0);
|
||
Label title = new("statuses");
|
||
title.AddToClassList("status-section-title");
|
||
block.Add(title);
|
||
if (!includeTooltips || state.Statuses.Count == 0)
|
||
{
|
||
block.Add(StatusPipRow(state));
|
||
return block;
|
||
}
|
||
|
||
VisualElement details = new();
|
||
details.AddToClassList("status-detail-list");
|
||
for (int i = 0; i < state.Statuses.Count; i++)
|
||
{
|
||
details.Add(StatusDetail(state.Statuses[i]));
|
||
}
|
||
|
||
block.Add(details);
|
||
return block;
|
||
}
|
||
|
||
private static VisualElement StatusDetail(StatusInstance status)
|
||
{
|
||
StatusDescriptor descriptor = StatusEffectController.GetDescriptor(status.Type);
|
||
VisualElement item = new();
|
||
item.AddToClassList("status-detail");
|
||
item.Add(StatusPip(status));
|
||
|
||
Label tooltip = new(descriptor.Tooltip);
|
||
tooltip.AddToClassList("status-tooltip");
|
||
item.Add(tooltip);
|
||
return item;
|
||
}
|
||
|
||
private static VisualElement StatusPipRow(CombatantState state)
|
||
{
|
||
VisualElement row = new();
|
||
row.AddToClassList("status-row");
|
||
if (state.Statuses.Count == 0)
|
||
{
|
||
row.Add(EmptyStatusPip());
|
||
return row;
|
||
}
|
||
|
||
for (int i = 0; i < state.Statuses.Count; i++)
|
||
{
|
||
row.Add(StatusPip(state.Statuses[i]));
|
||
}
|
||
|
||
return row;
|
||
}
|
||
|
||
private static VisualElement StatusPip(StatusInstance status)
|
||
{
|
||
StatusDescriptor descriptor = StatusEffectController.GetDescriptor(status.Type);
|
||
Label pip = new($"{descriptor.IconKey} x{status.Stacks} {DurationText(status.Duration)}");
|
||
pip.AddToClassList("status-pip");
|
||
pip.AddToClassList(descriptor.IsBeneficial ? "status-pip-beneficial" : "status-pip-harmful");
|
||
pip.tooltip = $"{descriptor.DisplayName}: {descriptor.Tooltip}";
|
||
return pip;
|
||
}
|
||
|
||
private static VisualElement EmptyStatusPip()
|
||
{
|
||
Label pip = new("none");
|
||
pip.AddToClassList("status-pip");
|
||
pip.AddToClassList("status-pip-empty");
|
||
return pip;
|
||
}
|
||
|
||
private void FillCardStrip(VisualElement target, IReadOnlyList<CardInstance> cards, string emptyText)
|
||
{
|
||
target.Clear();
|
||
((VisualElement)target.userData).EnableInClassList("track-idle", cards.Count == 0);
|
||
if (cards.Count == 0)
|
||
{
|
||
target.Add(EmptyState(emptyText));
|
||
return;
|
||
}
|
||
|
||
for (int i = 0; i < cards.Count; i++)
|
||
{
|
||
VisualElement chip = CardChip(cards[i]);
|
||
chip.Insert(0, SoftwareCardView.Text($"{i + 1:00} >", "execution-order"));
|
||
chip.tooltip = CardEffectFactory.GetRulesText(cards[i], _combatManager.RunConfig);
|
||
if (target == _interpreterStrip)
|
||
{
|
||
_queueChipElements[cards[i]] = chip;
|
||
}
|
||
else if (target == _lazyStackPile)
|
||
{
|
||
_stackChipElements[cards[i]] = chip;
|
||
}
|
||
|
||
target.Add(chip);
|
||
}
|
||
}
|
||
|
||
private bool PlayCardWithFeedback(CardInstance card)
|
||
{
|
||
int cyclesBefore = _combatManager.PlayerState == null ? 0 : _combatManager.PlayerState.Cycles;
|
||
bool played = _combatManager.PlayCard(card);
|
||
if (played)
|
||
{
|
||
int spent = Mathf.Max(0, cyclesBefore - (_combatManager.PlayerState == null ? cyclesBefore : _combatManager.PlayerState.Cycles));
|
||
if (spent > 0)
|
||
{
|
||
PlayElementBeat(_turnResourceGrid, "cycles-spent-beat", 220);
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
if (_combatManager.PendingTargetCard != card && _handCardElements.TryGetValue(card, out VisualElement face))
|
||
{
|
||
PlayElementBeat(face, "feedback-denied", 220);
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private bool UnlockCardWithFeedback(CardInstance card)
|
||
{
|
||
int cyclesBefore = _combatManager.PlayerState == null ? 0 : _combatManager.PlayerState.Cycles;
|
||
bool unlocked = _combatManager.TryUnlockCard(card);
|
||
if (unlocked)
|
||
{
|
||
int spent = Mathf.Max(0, cyclesBefore - (_combatManager.PlayerState == null ? cyclesBefore : _combatManager.PlayerState.Cycles));
|
||
if (spent > 0)
|
||
{
|
||
PlayElementBeat(_turnResourceGrid, "cycles-spent-beat", 220);
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
if (_handCardElements.TryGetValue(card, out VisualElement face))
|
||
{
|
||
PlayElementBeat(face, "feedback-denied", 220);
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private void HandleCardPlayed(CardPlayedEvent payload)
|
||
{
|
||
if (payload.Card == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_schedulerActivity.text = $"> {DisplayName(payload.Card.Definition)} dispatched / {SoftwareCardView.TrackName(payload.Track)}";
|
||
_firstBattleGuide?.CardPlayed(payload.Track, DisplayName(payload.Card.Definition));
|
||
_tutorial?.ObserveCard(payload.Track);
|
||
VisualElement source = _handCardElements.TryGetValue(payload.Card, out VisualElement cardElement) ? cardElement : null;
|
||
VisualElement destination = payload.Track switch
|
||
{
|
||
ResolutionTrack.InterpreterQueue => _interpreterStrip,
|
||
ResolutionTrack.LazyStack => _lazyStackPile,
|
||
_ => FirstTargetElement(payload.Card)
|
||
};
|
||
|
||
FlyCardGhost(payload.Card, source, destination, payload.Track == ResolutionTrack.Native ? "feedback-card-strike" : "feedback-card-route");
|
||
|
||
if (IsDistro("arch") && _archBtwCounterLabel != null && _combatManager.PlayerState != null)
|
||
{
|
||
_archBtwCounterLabel.text = $"btw ×{_combatManager.PlayerState.ArchBtwStacks}";
|
||
PlayElementBeat(_archBtwCounterLabel, "arch-btw-pop", 200);
|
||
}
|
||
}
|
||
|
||
private void HandleCardResolved(CardResolvedEvent payload)
|
||
{
|
||
if (payload.Card == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_executionSequence++;
|
||
_firstBattleGuide?.CardResolved(DisplayName(payload.Card.Definition), payload.Track);
|
||
_tutorial?.ObserveResolved(payload.Track);
|
||
_schedulerActivity.text = $"[{_executionSequence:00} OK] {DisplayName(payload.Card.Definition)} / {SoftwareCardView.TrackName(payload.Track)}";
|
||
AppendCombatLog($"{DisplayName(payload.Card.Definition)} resolved / {SoftwareCardView.TrackName(payload.Track)}.", "journal-operation");
|
||
if (payload.Track == ResolutionTrack.InterpreterQueue)
|
||
{
|
||
_queueView.Resolved(payload.Card, _executionSequence);
|
||
return;
|
||
}
|
||
|
||
if (payload.Track == ResolutionTrack.LazyStack)
|
||
{
|
||
_stackView.Resolved(payload.Card, _executionSequence);
|
||
}
|
||
}
|
||
|
||
private void HandleCardResolving(CardResolvedEvent payload)
|
||
{
|
||
if (payload.Card?.Definition == null) return;
|
||
_schedulerActivity.text = $"> executing {DisplayName(payload.Card.Definition)} / {SoftwareCardView.TrackName(payload.Track)}";
|
||
if (payload.Track == ResolutionTrack.InterpreterQueue) _queueView.Resolving(payload.Card);
|
||
if (payload.Track == ResolutionTrack.LazyStack) _stackView.Resolving(payload.Card);
|
||
}
|
||
|
||
private void HandlePhaseChanged(PhaseChangedEvent payload)
|
||
{
|
||
_firstBattleGuide?.PhaseChanged(payload.NextPhase);
|
||
_tutorial?.ObservePhase(payload.NextPhase);
|
||
if (payload.NextPhase == TurnPhase.Interpret)
|
||
{
|
||
_executionSequence = 0;
|
||
}
|
||
|
||
_feedbackCascadeIndex = 0;
|
||
_combatBeatCursorMs = 0;
|
||
_combatBeatCursorVersion++;
|
||
ScheduleFeedback(() => PlayElementBeat(_phaseLabel, "phase-pulse", 260), 0);
|
||
}
|
||
|
||
private void HandleDamageDealt(DamageDealtEvent payload)
|
||
{
|
||
bool isPlayer = payload.Target == _combatManager.PlayerState;
|
||
int magnitudeAmount = payload.UptimeDamage > 0 ? payload.UptimeDamage : payload.ShieldDamage > 0 ? payload.ShieldDamage : payload.Amount;
|
||
bool defeated = payload.Target != null && payload.Target.CurrentUptime <= 0;
|
||
HitMagnitudeTier tier = HitMagnitude.Classify(magnitudeAmount, payload.Target?.MaxUptime ?? 1, defeated);
|
||
bool shieldOnly = payload.WasFullyBlocked && payload.ShieldDamage > 0;
|
||
|
||
bool fedoraPayoff = _pendingFedoraPayoff && payload.Source == _combatManager.PlayerState && payload.UptimeDamage > 0;
|
||
_pendingFedoraPayoff = false;
|
||
if (fedoraPayoff && tier < HitMagnitudeTier.Major)
|
||
{
|
||
tier = HitMagnitudeTier.Major;
|
||
}
|
||
|
||
if (payload.ArchRollingReleaseSaveTriggered)
|
||
{
|
||
TriggerRollingReleaseSave();
|
||
}
|
||
|
||
// Feedback observes this hit now; it must not queue behind unrelated animations.
|
||
{
|
||
int beatIndex = _feedbackCascadeIndex++ % 3;
|
||
string bypass = payload.TrueDamage ? "! " : string.Empty;
|
||
string text = shieldOnly
|
||
? $"{bypass}block {payload.ShieldDamage}"
|
||
: payload.WasFullyBlocked
|
||
? $"{bypass}blocked"
|
||
: $"{bypass}{(payload.WasCritical ? "CRIT " : "")}-{payload.UptimeDamage} HP";
|
||
string primaryText = text;
|
||
if (!shieldOnly && payload.ShieldDamage > 0) text += $" / -{payload.ShieldDamage} shield";
|
||
AppendCombatLog($"{CombatantName(payload.Target)}: {text}.", shieldOnly ? "journal-shield" : "journal-damage");
|
||
string tone = BuildDamageFloatClasses(tier, payload, shieldOnly);
|
||
string beatClass = fedoraPayoff ? "feedback-fedora-payoff" : BuildDamageBeatClass(tier, payload, shieldOnly);
|
||
if (fedoraPayoff)
|
||
{
|
||
tone += " float-fedora-payoff";
|
||
}
|
||
|
||
int beatDuration = fedoraPayoff ? Mathf.Max(360, HitBeatDuration(tier, payload.WasMitigated)) : HitBeatDuration(tier, payload.WasMitigated);
|
||
|
||
SpawnFloatingText(payload.Target, primaryText, tone, beatIndex);
|
||
if (!shieldOnly && payload.ShieldDamage > 0)
|
||
SpawnFloatingText(payload.Target, $"-{payload.ShieldDamage} shield", "float-shield", beatIndex + 1);
|
||
if (TryGetCombatantElement(payload.Target, out VisualElement target))
|
||
{
|
||
PlayElementBeat(target, beatClass, beatDuration);
|
||
}
|
||
if (payload.ArchBtwBonusAmount > 0)
|
||
{
|
||
SpawnFloatingText(payload.Target, $"+{payload.ArchBtwBonusAmount} btw", "float-btw-bonus", beatIndex + 1);
|
||
}
|
||
|
||
if (isPlayer && payload.UptimeDamage > 0)
|
||
{
|
||
FlashDamageVignette(tier);
|
||
}
|
||
}
|
||
}
|
||
|
||
private void HandleOverflowDamageTravel(OverflowDamageTravelEvent payload)
|
||
{
|
||
ScheduleCombatBeat(() => SpawnOverflowTravel(payload.From, payload.To, payload.Amount), CombatTuning.OverflowTravelMs);
|
||
}
|
||
|
||
private void TriggerRollingReleaseSave()
|
||
{
|
||
SpawnFloatingText(_playerPanel, "rolling release: recovered", "float-heal float-large");
|
||
PlayElementBeat(_damageVignette, "damage-vignette-rolling-release", 420);
|
||
}
|
||
|
||
private void HandleCombatantDefeated(CombatantDefeatedEvent payload)
|
||
{
|
||
if (payload.Combatant == null || !_deathFeedbackObserved.Add(payload.Combatant)) return;
|
||
// Snapshot identity before the engine removes the process; visual callbacks can run later.
|
||
string combatantName = CombatantName(payload.Combatant);
|
||
bool restartPending = false;
|
||
foreach (var enemy in _combatManager.Enemies)
|
||
if (enemy.State == payload.Combatant) { restartPending = enemy.PendingRevive; break; }
|
||
HoldDeathUptime(payload.Combatant);
|
||
int completionMs = ScheduleCombatBeat(() =>
|
||
{
|
||
if (payload.Combatant != null && payload.Combatant != _combatManager.PlayerState)
|
||
{
|
||
_deathBeatStartedCombatants.Add(payload.Combatant);
|
||
RefreshEnemies();
|
||
}
|
||
|
||
SpawnFloatingText(payload.Combatant, restartPending ? "restart pending" : "terminated", "float-kill float-large", 0);
|
||
AppendCombatLog($"{combatantName}: {(restartPending ? "restart pending" : "terminated")}.", restartPending ? "journal-status" : "journal-damage");
|
||
if (!restartPending && TryGetCombatantFeedbackRect(payload.Combatant, out Rect targetBounds))
|
||
{
|
||
SpawnDeathGhost(targetBounds);
|
||
}
|
||
|
||
if (TryGetCombatantElement(payload.Combatant, out VisualElement target))
|
||
{
|
||
if (target != _playerPanel && !restartPending)
|
||
{
|
||
target.AddToClassList("enemy-card-defeated-hold");
|
||
target.SetEnabled(false);
|
||
}
|
||
|
||
PlayElementBeat(target, restartPending ? "feedback-status" : "feedback-killed", 420);
|
||
}
|
||
}, CombatTuning.DeathBeatMs + CombatTuning.PostDeathPauseMs);
|
||
ScheduleFeedback(() => CompleteCombatantDeathVisual(payload.Combatant), completionMs);
|
||
}
|
||
|
||
private void HoldDeathUptime(CombatantState combatant)
|
||
{
|
||
if (combatant == null || combatant == _combatManager.PlayerState || _heldDeathUptime.ContainsKey(combatant))
|
||
{
|
||
return;
|
||
}
|
||
|
||
int held = _previousUptime.TryGetValue(combatant, out int previous)
|
||
? previous
|
||
: combatant.MaxUptime;
|
||
_heldDeathUptime[combatant] = Mathf.Clamp(held, 1, Mathf.Max(1, combatant.MaxUptime));
|
||
}
|
||
|
||
private void CompleteCombatantDeathVisual(CombatantState combatant)
|
||
{
|
||
if (ShouldHideCombatantAfterDeathVisual(combatant))
|
||
{
|
||
_visuallyRemovedCombatants.Add(combatant);
|
||
_heldDeathUptime.Remove(combatant);
|
||
_deathBeatStartedCombatants.Remove(combatant);
|
||
RefreshEnemies();
|
||
}
|
||
|
||
GameEvents.RaiseCombatantDeathVisualCompleted(new CombatantDeathVisualCompletedEvent(combatant));
|
||
}
|
||
|
||
private bool ShouldHideCombatantAfterDeathVisual(CombatantState combatant)
|
||
{
|
||
if (combatant == null || combatant == _combatManager.PlayerState)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
IReadOnlyList<EnemyInstance> enemies = _combatManager.Enemies;
|
||
for (int i = 0; i < enemies.Count; i++)
|
||
{
|
||
if (enemies[i].State == combatant)
|
||
{
|
||
return !enemies[i].PendingRevive;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private void HandleDeathSpawnedEnemy(DeathSpawnedEnemyEvent payload)
|
||
{
|
||
ScheduleFeedback(() =>
|
||
{
|
||
SpawnFloatingText(payload.Enemy?.State, "spawned", "float-status");
|
||
if (TryGetCombatantElement(payload.Enemy?.State, out VisualElement target))
|
||
{
|
||
PlayElementBeat(target, "feedback-spawned", CombatTuning.SpawnMaterializeMs);
|
||
}
|
||
}, 0);
|
||
}
|
||
|
||
private void HandleEnemyWouldAct(EnemyWouldActEvent payload)
|
||
{
|
||
if (TryGetCombatantElement(payload.Enemy?.State, out VisualElement enemy))
|
||
PlayElementBeat(enemy, "enemy-anticipating", 340);
|
||
}
|
||
|
||
private void HandlePlayerDamaged(PlayerDamagedEvent payload)
|
||
{
|
||
// DamageDealt carries richer mitigation data and owns the visual hit beat.
|
||
}
|
||
|
||
private void HandleStatusApplied(StatusAppliedEvent payload)
|
||
{
|
||
{
|
||
StatusDescriptor descriptor = StatusEffectController.GetDescriptor(payload.StatusType);
|
||
if (TryGetCombatantElement(payload.Target, out VisualElement target))
|
||
{
|
||
ApplyStatusStateClass(target, payload.StatusType, true);
|
||
PlayElementBeat(target, descriptor.IsBeneficial ? "feedback-boost" : "feedback-status", 220);
|
||
}
|
||
|
||
SpawnFloatingText(payload.Target, $"{descriptor.IconKey} x{payload.Stacks}", descriptor.IsBeneficial ? "float-heal" : "float-status");
|
||
AppendCombatLog($"{CombatantName(payload.Target)}: {payload.StatusType} / {payload.Target.StacksOf(payload.StatusType)} stacks.", "journal-status");
|
||
}
|
||
}
|
||
|
||
private void HandleStatusEnded(StatusExpiredEvent payload)
|
||
{
|
||
ApplyStatusStateClass(CombatantElement(payload.Target), payload.StatusType, false);
|
||
}
|
||
|
||
private void HandleStatusEnded(StatusCleansedEvent payload)
|
||
{
|
||
ApplyStatusStateClass(CombatantElement(payload.Target), payload.StatusType, false);
|
||
}
|
||
|
||
private void HandleUbuntuAptUpdatePeeked(UbuntuAptUpdatePeekedEvent payload)
|
||
{
|
||
if (payload.Peeked == null || payload.Peeked.Count == 0 || payload.Chosen == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
int minCost = int.MaxValue;
|
||
for (int i = 0; i < payload.Peeked.Count; i++)
|
||
{
|
||
minCost = Mathf.Min(minCost, payload.Peeked[i].Cost);
|
||
}
|
||
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
string summary = string.Empty;
|
||
for (int i = 0; i < payload.Peeked.Count; i++)
|
||
{
|
||
PeekedCardInfo info = payload.Peeked[i];
|
||
summary += (i > 0 ? ", " : string.Empty) + $"{DisplayName(info.Card.Definition)} {info.Cost}c";
|
||
}
|
||
|
||
string prefix = payload.WasTie ? "apt update tie" : "apt update peeked";
|
||
SpawnStaticInfoLabel(_turnResourceGrid, $"{prefix}: {summary} -> added {DisplayName(payload.Chosen.Definition)}", 900);
|
||
return;
|
||
}
|
||
|
||
if (!TryGetElementWorldRect(_turnResourceGrid, out Rect turnResourceRect)
|
||
|| !TryGetFeedbackLocalRect(turnResourceRect, out Rect anchorRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
List<VisualElement> stageElements = new(payload.Peeked.Count);
|
||
for (int i = 0; i < payload.Peeked.Count; i++)
|
||
{
|
||
PruneFeedbackLayer();
|
||
VisualElement stageCard = CardFaceView(payload.Peeked[i].Card);
|
||
stageCard.AddToClassList("peek-card");
|
||
stageCard.style.position = Position.Absolute;
|
||
stageCard.style.left = anchorRect.x + (i * 96f);
|
||
stageCard.style.top = anchorRect.y - 128f;
|
||
stageCard.style.width = 88f;
|
||
stageCard.style.height = 108f;
|
||
stageCard.style.opacity = 0f;
|
||
_feedbackLayer.Add(stageCard);
|
||
stageElements.Add(stageCard);
|
||
}
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
for (int i = 0; i < stageElements.Count; i++)
|
||
{
|
||
stageElements[i].style.opacity = 1f;
|
||
}
|
||
}, 20);
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
for (int i = 0; i < payload.Peeked.Count; i++)
|
||
{
|
||
if (payload.Peeked[i].Cost != minCost)
|
||
{
|
||
continue;
|
||
}
|
||
|
||
stageElements[i].AddToClassList("peek-card-marked");
|
||
stageElements[i].EnableInClassList("peek-card-tie", payload.WasTie);
|
||
}
|
||
}, 180);
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
for (int i = 0; i < payload.Peeked.Count; i++)
|
||
{
|
||
VisualElement stage = stageElements[i];
|
||
if (payload.Peeked[i].Card == payload.Chosen)
|
||
{
|
||
FlyCardGhost(payload.Chosen, stage, _handRow, "feedback-card-route");
|
||
stage.style.opacity = 0f;
|
||
ScheduleFeedback(() => stage.RemoveFromHierarchy(), 40);
|
||
}
|
||
else
|
||
{
|
||
stage.style.opacity = 0f;
|
||
ScheduleFeedback(() => stage.RemoveFromHierarchy(), 220);
|
||
}
|
||
}
|
||
}, 340);
|
||
}
|
||
|
||
private void HandleFedoraBleedingEdgeTriggered(FedoraBleedingEdgeEvent payload)
|
||
{
|
||
if (payload.Card == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
VisualElement anchor = _handCardElements.TryGetValue(payload.Card, out VisualElement cardElement)
|
||
? cardElement
|
||
: CombatantElement(_combatManager.PlayerState);
|
||
|
||
if (payload.Crashed)
|
||
{
|
||
SnapFedoraRiskMeter(payload.CrashChanceAfter);
|
||
}
|
||
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
string outcome = payload.Crashed ? "crashed - no effect" : $"hit +{payload.DamageMultiplierPercent - 100}%";
|
||
SpawnStaticInfoLabel(anchor, $"bleeding edge: -1c {outcome}", 700);
|
||
if (!payload.Crashed)
|
||
{
|
||
_pendingFedoraPayoff = true;
|
||
}
|
||
|
||
return;
|
||
}
|
||
|
||
VisualElement windup = CardFaceView(payload.Card);
|
||
windup.AddToClassList("feedback-fedora-windup");
|
||
windup.style.position = Position.Absolute;
|
||
if (!TryGetElementWorldRect(anchor, out Rect anchorWorldRect) || !TryGetFeedbackLocalRect(anchorWorldRect, out Rect anchorRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
windup.style.left = anchorRect.x;
|
||
windup.style.top = anchorRect.y;
|
||
windup.style.width = Mathf.Max(110f, anchorRect.width);
|
||
windup.style.height = Mathf.Max(94f, anchorRect.height);
|
||
PruneFeedbackLayer();
|
||
_feedbackLayer.Add(windup);
|
||
|
||
VisualElement badgeRow = new();
|
||
badgeRow.AddToClassList("tag-row");
|
||
badgeRow.Add(Tag("-1c", "fedora-badge"));
|
||
badgeRow.Add(Tag($"+{payload.DamageMultiplierPercent - 100}%", "fedora-badge"));
|
||
windup.Add(badgeRow);
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (payload.Crashed)
|
||
{
|
||
windup.AddToClassList("feedback-fedora-crash");
|
||
Label stamp = new("CRASHED");
|
||
stamp.AddToClassList("fedora-crash-stamp");
|
||
windup.Add(stamp);
|
||
SpawnFloatingText(anchor, "no effect", "float-crash");
|
||
ScheduleFeedback(() => windup.style.opacity = 0.15f, 60);
|
||
ScheduleFeedback(() => windup.style.opacity = 0.85f, 120);
|
||
ScheduleFeedback(() => windup.style.opacity = 0f, 220);
|
||
ScheduleFeedback(() => windup.RemoveFromHierarchy(), 320);
|
||
return;
|
||
}
|
||
|
||
_pendingFedoraPayoff = true;
|
||
windup.style.opacity = 0f;
|
||
ScheduleFeedback(() => windup.RemoveFromHierarchy(), 220);
|
||
}, 200);
|
||
}
|
||
|
||
private void SnapFedoraRiskMeter(float chanceAfter)
|
||
{
|
||
float clamped = Mathf.Clamp(chanceAfter, 0f, 100f);
|
||
if (_fedoraRiskValueLabel != null)
|
||
{
|
||
_fedoraRiskValueLabel.text = $"{clamped:0.#}%";
|
||
}
|
||
|
||
if (_fedoraRiskFillElement != null)
|
||
{
|
||
_fedoraRiskFillElement.style.width = Length.Percent(clamped);
|
||
_fedoraRiskFillElement.RemoveFromClassList("meter-fill-warning");
|
||
_fedoraRiskFillElement.RemoveFromClassList("meter-fill-danger");
|
||
_fedoraRiskFillElement.AddToClassList(FedoraRiskFillClass(clamped));
|
||
PlayElementBeat(_fedoraRiskFillElement, "fedora-risk-snap", 260);
|
||
}
|
||
}
|
||
|
||
private void HandleArchBtwTurnEnded(ArchBtwTurnEndedEvent payload)
|
||
{
|
||
if (_archBtwCounterLabel == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
if (payload.Persisted)
|
||
{
|
||
PlayElementBeat(_archBtwCounterLabel, "arch-btw-persist", 320);
|
||
return;
|
||
}
|
||
|
||
_archBtwCounterLabel.text = "btw ×0";
|
||
PlayElementBeat(_archBtwCounterLabel, "arch-btw-reset", 260);
|
||
}
|
||
|
||
private void SpawnStaticInfoLabel(VisualElement anchor, string text, int holdMs)
|
||
{
|
||
if (_feedbackLayer == null || !TryGetElementWorldRect(anchor, out Rect anchorRect) || !TryGetFeedbackLocalRect(anchorRect, out Rect localRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
PruneFeedbackLayer();
|
||
Label label = new(text);
|
||
label.AddToClassList("float-number");
|
||
label.AddToClassList("float-status");
|
||
label.AddToClassList("float-static");
|
||
label.style.left = localRect.center.x - 80f;
|
||
label.style.top = localRect.y - 26f;
|
||
_feedbackLayer.Add(label);
|
||
ScheduleFeedback(() => label.RemoveFromHierarchy(), holdMs);
|
||
}
|
||
|
||
private void DetectBeneficialResourceFeedback(CombatantState state, VisualElement element)
|
||
{
|
||
if (state == null || element == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
if (_previousUptime.TryGetValue(state, out int oldUptime) && state.CurrentUptime > oldUptime)
|
||
{
|
||
SpawnFloatingText(element, $"+{state.CurrentUptime - oldUptime} HP", "float-heal");
|
||
AppendCombatLog($"{CombatantName(state)}: +{state.CurrentUptime - oldUptime} HP.", "journal-heal");
|
||
PlayElementBeat(element, "feedback-boost", 220);
|
||
}
|
||
|
||
if (_previousShield.TryGetValue(state, out int oldShield) && state.Shield > oldShield)
|
||
{
|
||
SpawnFloatingText(element, $"+{state.Shield - oldShield} shield", "float-shield");
|
||
AppendCombatLog($"{CombatantName(state)}: +{state.Shield - oldShield} shield.", "journal-shield");
|
||
PlayElementBeat(element, "feedback-block", 220);
|
||
}
|
||
|
||
_previousUptime[state] = state.CurrentUptime;
|
||
_previousShield[state] = state.Shield;
|
||
}
|
||
|
||
private static string BuildDamageFloatClasses(HitMagnitudeTier tier, DamageDealtEvent payload, bool shieldOnly)
|
||
{
|
||
string classes = shieldOnly || payload.WasFullyBlocked ? "float-shield" : "float-damage";
|
||
classes += " " + TierFloatClass(tier);
|
||
if (payload.TrueDamage)
|
||
{
|
||
classes += " float-true";
|
||
}
|
||
|
||
return classes;
|
||
}
|
||
|
||
private static string BuildDamageBeatClass(HitMagnitudeTier tier, DamageDealtEvent payload, bool shieldOnly)
|
||
{
|
||
if (shieldOnly || payload.WasFullyBlocked)
|
||
{
|
||
return tier >= HitMagnitudeTier.Major ? "feedback-clang-major" : "feedback-clang";
|
||
}
|
||
|
||
if (payload.WasCritical || tier == HitMagnitudeTier.Massive)
|
||
{
|
||
return "feedback-crit";
|
||
}
|
||
|
||
return tier switch
|
||
{
|
||
HitMagnitudeTier.Minor => "feedback-hit-minor",
|
||
HitMagnitudeTier.Moderate => "feedback-hit",
|
||
HitMagnitudeTier.Major => "feedback-hit-major",
|
||
_ => "feedback-crit"
|
||
};
|
||
}
|
||
|
||
private static string TierFloatClass(HitMagnitudeTier tier)
|
||
{
|
||
return tier switch
|
||
{
|
||
HitMagnitudeTier.Minor => "float-tier-minor",
|
||
HitMagnitudeTier.Moderate => "float-tier-moderate",
|
||
HitMagnitudeTier.Major => "float-tier-major",
|
||
HitMagnitudeTier.Massive => "float-tier-massive",
|
||
_ => "float-tier-moderate"
|
||
};
|
||
}
|
||
|
||
private static string TierImpactClass(HitMagnitudeTier tier)
|
||
{
|
||
return tier switch
|
||
{
|
||
HitMagnitudeTier.Minor => "impact-tier-minor",
|
||
HitMagnitudeTier.Moderate => "impact-tier-moderate",
|
||
HitMagnitudeTier.Major => "impact-tier-major",
|
||
HitMagnitudeTier.Massive => "impact-tier-massive",
|
||
_ => "impact-tier-moderate"
|
||
};
|
||
}
|
||
|
||
private static int HitBeatDuration(HitMagnitudeTier tier, bool mitigated)
|
||
{
|
||
if (mitigated && tier < HitMagnitudeTier.Major)
|
||
{
|
||
return 220;
|
||
}
|
||
|
||
return tier switch
|
||
{
|
||
HitMagnitudeTier.Minor => 120,
|
||
HitMagnitudeTier.Moderate => 220,
|
||
HitMagnitudeTier.Major => 340,
|
||
HitMagnitudeTier.Massive => 460,
|
||
_ => 220
|
||
};
|
||
}
|
||
|
||
private void TrackCombatantFeedbackAnchor(CombatantState state, VisualElement element)
|
||
{
|
||
if (state == null || element == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
TryCacheCombatantFeedbackRect(state, element);
|
||
if (element == _playerPanel)
|
||
{
|
||
if (_playerFeedbackAnchorTracked)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_playerFeedbackAnchorTracked = true;
|
||
}
|
||
|
||
element.RegisterCallback<GeometryChangedEvent>(_ => TryCacheCombatantFeedbackRect(state, element));
|
||
}
|
||
|
||
private bool TryCacheCombatantFeedbackRect(CombatantState state, VisualElement element)
|
||
{
|
||
if (state == null || !TryGetElementWorldRect(element, out Rect rect))
|
||
{
|
||
return false;
|
||
}
|
||
|
||
_lastCombatantFeedbackRects[state] = rect;
|
||
return true;
|
||
}
|
||
|
||
private bool TryGetCombatantFeedbackRect(CombatantState state, out Rect rect)
|
||
{
|
||
if (state != null && _combatantElements.TryGetValue(state, out VisualElement element) && TryGetElementWorldRect(element, out rect))
|
||
{
|
||
_lastCombatantFeedbackRects[state] = rect;
|
||
return true;
|
||
}
|
||
|
||
if (state != null && _lastCombatantFeedbackRects.TryGetValue(state, out rect) && IsValidRect(rect))
|
||
{
|
||
return true;
|
||
}
|
||
|
||
rect = default;
|
||
return false;
|
||
}
|
||
|
||
private bool TryGetCombatantElement(CombatantState state, out VisualElement element)
|
||
{
|
||
if (state != null && _combatantElements.TryGetValue(state, out element))
|
||
{
|
||
return element != null;
|
||
}
|
||
|
||
element = state == _combatManager.PlayerState ? _playerPanel : null;
|
||
return element != null;
|
||
}
|
||
|
||
private bool TryGetElementWorldRect(VisualElement element, out Rect rect)
|
||
{
|
||
rect = default;
|
||
if (element == null || element.panel == null)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
rect = element.worldBound;
|
||
return IsValidRect(rect);
|
||
}
|
||
|
||
private bool TryGetFeedbackLocalRect(Rect worldRect, out Rect localRect)
|
||
{
|
||
localRect = default;
|
||
if (_feedbackLayer == null || !IsValidRect(worldRect) || !TryGetElementWorldRect(_feedbackLayer, out Rect layerRect))
|
||
{
|
||
return false;
|
||
}
|
||
|
||
localRect = new Rect(worldRect.x - layerRect.x, worldRect.y - layerRect.y, worldRect.width, worldRect.height);
|
||
return IsValidRect(localRect);
|
||
}
|
||
|
||
private static bool IsValidRect(Rect rect)
|
||
{
|
||
return rect.width > 0f
|
||
&& rect.height > 0f
|
||
&& IsFinite(rect.x)
|
||
&& IsFinite(rect.y)
|
||
&& IsFinite(rect.width)
|
||
&& IsFinite(rect.height)
|
||
&& IsFinite(rect.center.x)
|
||
&& IsFinite(rect.center.y);
|
||
}
|
||
|
||
private static bool IsFinite(float value)
|
||
{
|
||
return !float.IsNaN(value) && !float.IsInfinity(value);
|
||
}
|
||
|
||
private VisualElement CombatantElement(CombatantState state)
|
||
{
|
||
if (state != null && _combatantElements.TryGetValue(state, out VisualElement element))
|
||
{
|
||
return element;
|
||
}
|
||
|
||
return state == _combatManager.PlayerState ? _playerPanel : _enemyRow;
|
||
}
|
||
|
||
private VisualElement FirstTargetElement(CardInstance card)
|
||
{
|
||
if (card?.TargetSnapshot == null)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
for (int i = 0; i < card.TargetSnapshot.Count; i++)
|
||
{
|
||
if (TryGetCombatantElement(card.TargetSnapshot[i], out VisualElement element))
|
||
{
|
||
return element;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
private void PlayElementBeat(VisualElement element, string className, int durationMs)
|
||
{
|
||
if (element == null || string.IsNullOrWhiteSpace(className))
|
||
{
|
||
return;
|
||
}
|
||
|
||
int version = ++_feedbackBeatVersion;
|
||
_feedbackBeatVersions[element] = version;
|
||
RemoveFeedbackBeatClasses(element);
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (!_feedbackBeatVersions.TryGetValue(element, out int currentVersion) || currentVersion != version)
|
||
{
|
||
return;
|
||
}
|
||
|
||
element.AddToClassList(className);
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (!_feedbackBeatVersions.TryGetValue(element, out int removeVersion) || removeVersion != version)
|
||
{
|
||
return;
|
||
}
|
||
|
||
element.RemoveFromClassList(className);
|
||
_feedbackBeatVersions.Remove(element);
|
||
}, UIPreferences.ReducedMotion ? 80 : durationMs);
|
||
}, 0);
|
||
}
|
||
|
||
private void SpawnFloatingText(VisualElement anchor, string text, string className, int cascadeOffset = 0)
|
||
{
|
||
if (!TryGetElementWorldRect(anchor, out Rect anchorRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
SpawnFloatingText(anchorRect, text, className, cascadeOffset);
|
||
}
|
||
|
||
private void SpawnFloatingText(CombatantState anchor, string text, string className, int cascadeOffset = 0)
|
||
{
|
||
if (!TryGetCombatantFeedbackRect(anchor, out Rect anchorRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
SpawnFloatingText(anchorRect, text, className, cascadeOffset);
|
||
}
|
||
|
||
private void SpawnFloatingText(Rect anchorRect, string text, string className, int cascadeOffset = 0)
|
||
{
|
||
if (_feedbackLayer == null || !TryGetFeedbackLocalRect(anchorRect, out Rect localRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
PruneFeedbackLayer();
|
||
Label label = new(text);
|
||
label.AddToClassList("float-number");
|
||
if (!string.IsNullOrWhiteSpace(className))
|
||
{
|
||
string[] classes = className.Split(' ');
|
||
for (int i = 0; i < classes.Length; i++)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(classes[i]))
|
||
{
|
||
label.AddToClassList(classes[i]);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Reserve separate readout lines for rapid hits, healing and shields on the same actor.
|
||
// No animation or gameplay waits: each line appears at the event boundary.
|
||
int lane = 0;
|
||
foreach (var existing in _feedbackLayer.Children())
|
||
if (existing.ClassListContains("float-number") && existing.userData is Vector2 origin &&
|
||
Vector2.Distance(origin, localRect.center) < 20f) lane++;
|
||
label.userData = localRect.center;
|
||
float offsetY = (lane % 4) * 26f;
|
||
float startY = Mathf.Clamp(localRect.center.y - 26f + offsetY, 8f, Mathf.Max(8f, _root.layout.height - 30f));
|
||
label.style.left = Mathf.Clamp(localRect.center.x - 65f, 8f, Mathf.Max(8f, _root.layout.width - 200f));
|
||
label.style.top = startY;
|
||
_feedbackLayer.Add(label);
|
||
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
label.AddToClassList("float-static");
|
||
ScheduleFeedback(() => label.RemoveFromHierarchy(), 420);
|
||
return;
|
||
}
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
label.style.top = Mathf.Max(8f, startY - 26f);
|
||
label.style.opacity = 0f;
|
||
}, 20);
|
||
ScheduleFeedback(() => label.RemoveFromHierarchy(), 520);
|
||
}
|
||
|
||
private void SpawnImpactMarker(VisualElement anchor, bool critical, bool mitigated, int cascadeOffset, HitMagnitudeTier tier = HitMagnitudeTier.Moderate, bool shieldOnly = false)
|
||
{
|
||
if (!TryGetElementWorldRect(anchor, out Rect anchorRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
SpawnImpactMarker(anchorRect, critical, mitigated, cascadeOffset, tier, shieldOnly);
|
||
}
|
||
|
||
private void SpawnImpactMarker(CombatantState anchor, bool critical, bool mitigated, int cascadeOffset, HitMagnitudeTier tier = HitMagnitudeTier.Moderate, bool shieldOnly = false)
|
||
{
|
||
if (!TryGetCombatantFeedbackRect(anchor, out Rect anchorRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
SpawnImpactMarker(anchorRect, critical, mitigated, cascadeOffset, tier, shieldOnly);
|
||
}
|
||
|
||
private void SpawnImpactMarker(Rect anchorRect, bool critical, bool mitigated, int cascadeOffset, HitMagnitudeTier tier = HitMagnitudeTier.Moderate, bool shieldOnly = false)
|
||
{
|
||
if (_feedbackLayer == null || !TryGetFeedbackLocalRect(anchorRect, out Rect localRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
PruneFeedbackLayer();
|
||
Label marker = new(shieldOnly ? "shield" : critical ? "crit" : mitigated ? "clang" : "hit");
|
||
marker.AddToClassList("impact-marker");
|
||
marker.AddToClassList(shieldOnly || mitigated ? "impact-marker-clang" : critical ? "impact-marker-crit" : "impact-marker-hit");
|
||
marker.AddToClassList(TierImpactClass(tier));
|
||
|
||
float lane = (cascadeOffset % 4) * 18f;
|
||
marker.style.left = localRect.xMax - 54f;
|
||
marker.style.top = localRect.y + 8f + lane;
|
||
_feedbackLayer.Add(marker);
|
||
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
ScheduleFeedback(() => marker.RemoveFromHierarchy(), 260);
|
||
return;
|
||
}
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
marker.style.left = localRect.xMax - 34f;
|
||
marker.style.opacity = 0f;
|
||
}, 20);
|
||
ScheduleFeedback(() => marker.RemoveFromHierarchy(), 420);
|
||
}
|
||
|
||
private void TriggerHitStop(HitMagnitudeTier tier)
|
||
{
|
||
if (UIPreferences.ReducedMotion || tier < HitMagnitudeTier.Major || Time.frameCount == _lastHitStopFrame)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_lastHitStopFrame = Time.frameCount;
|
||
int version = ++_hitStopVersion;
|
||
float duration = tier == HitMagnitudeTier.Massive ? 0.16f : 0.09f;
|
||
Time.timeScale = 0.04f;
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (_hitStopVersion == version)
|
||
{
|
||
Time.timeScale = 1f;
|
||
}
|
||
}, Mathf.RoundToInt(duration * 1000f));
|
||
}
|
||
|
||
private void TriggerRootShake(HitMagnitudeTier tier, bool playerHit)
|
||
{
|
||
if (UIPreferences.ReducedMotion || tier < HitMagnitudeTier.Major || _root == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
int version = ++_rootShakeVersion;
|
||
_root.RemoveFromClassList("root-shake-major");
|
||
_root.RemoveFromClassList("root-shake-massive");
|
||
_root.RemoveFromClassList("root-shake-player");
|
||
_root.AddToClassList(tier == HitMagnitudeTier.Massive ? "root-shake-massive" : "root-shake-major");
|
||
_root.EnableInClassList("root-shake-player", playerHit);
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (_rootShakeVersion != version)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_root.RemoveFromClassList("root-shake-major");
|
||
_root.RemoveFromClassList("root-shake-massive");
|
||
_root.RemoveFromClassList("root-shake-player");
|
||
}, tier == HitMagnitudeTier.Massive ? 220 : 140);
|
||
}
|
||
|
||
private void PruneFeedbackLayer()
|
||
{
|
||
if (_feedbackLayer == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
while (_feedbackLayer.childCount >= MaxFeedbackElements)
|
||
{
|
||
_feedbackLayer.ElementAt(0).RemoveFromHierarchy();
|
||
}
|
||
}
|
||
|
||
private void FlyCardGhost(CardInstance card, VisualElement source, VisualElement destination, string className)
|
||
{
|
||
if (_feedbackLayer == null
|
||
|| card == null
|
||
|| !TryGetElementWorldRect(source, out Rect sourceWorldRect)
|
||
|| !TryGetElementWorldRect(destination, out Rect destinationWorldRect)
|
||
|| !TryGetFeedbackLocalRect(sourceWorldRect, out Rect sourceRect)
|
||
|| !TryGetFeedbackLocalRect(destinationWorldRect, out Rect destinationRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
VisualElement ghost = CardFaceView(card);
|
||
ghost.AddToClassList("feedback-card-ghost");
|
||
ghost.AddToClassList(className);
|
||
ghost.style.position = Position.Absolute;
|
||
ghost.style.left = sourceRect.x;
|
||
ghost.style.top = sourceRect.y;
|
||
ghost.style.width = Mathf.Max(110f, sourceRect.width);
|
||
ghost.style.height = Mathf.Max(94f, sourceRect.height);
|
||
_feedbackLayer.Add(ghost);
|
||
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
ghost.AddToClassList("feedback-card-instant");
|
||
ScheduleFeedback(() => ghost.RemoveFromHierarchy(), 140);
|
||
return;
|
||
}
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
ghost.style.left = destinationRect.center.x - (sourceRect.width * 0.5f);
|
||
ghost.style.top = destinationRect.center.y - (sourceRect.height * 0.5f);
|
||
ghost.style.opacity = 0f;
|
||
}, 20);
|
||
ScheduleFeedback(() => ghost.RemoveFromHierarchy(), 360);
|
||
}
|
||
|
||
private void SpawnDeathGhost(Rect sourceRect)
|
||
{
|
||
if (_feedbackLayer == null || !TryGetFeedbackLocalRect(sourceRect, out Rect localRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
float ghostWidth = Mathf.Min(sourceRect.width, 156f);
|
||
float ghostHeight = Mathf.Min(sourceRect.height, 132f);
|
||
VisualElement ghost = new();
|
||
ghost.AddToClassList("death-ghost");
|
||
ghost.style.position = Position.Absolute;
|
||
ghost.style.left = localRect.center.x - (ghostWidth * 0.5f);
|
||
ghost.style.top = localRect.center.y - (ghostHeight * 0.5f);
|
||
ghost.style.width = ghostWidth;
|
||
ghost.style.height = ghostHeight;
|
||
_feedbackLayer.Add(ghost);
|
||
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
ScheduleFeedback(() => ghost.RemoveFromHierarchy(), 180);
|
||
return;
|
||
}
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
ghost.style.opacity = 0f;
|
||
ghost.style.scale = new Scale(new Vector3(0.92f, 0.92f, 1f));
|
||
}, 20);
|
||
ScheduleFeedback(() => ghost.RemoveFromHierarchy(), 360);
|
||
}
|
||
|
||
private void SpawnOverflowTravel(CombatantState source, CombatantState destination, int amount)
|
||
{
|
||
if (_feedbackLayer == null
|
||
|| !TryGetCombatantFeedbackRect(source, out Rect sourceWorldRect)
|
||
|| !TryGetCombatantFeedbackRect(destination, out Rect destinationWorldRect)
|
||
|| !TryGetFeedbackLocalRect(sourceWorldRect, out Rect sourceRect)
|
||
|| !TryGetFeedbackLocalRect(destinationWorldRect, out Rect destinationRect))
|
||
{
|
||
return;
|
||
}
|
||
|
||
PruneFeedbackLayer();
|
||
Label spill = new($"> {Mathf.Max(0, amount)}");
|
||
spill.AddToClassList("overflow-travel");
|
||
spill.style.position = Position.Absolute;
|
||
spill.style.left = sourceRect.center.x - 20f;
|
||
spill.style.top = sourceRect.center.y - 12f;
|
||
_feedbackLayer.Add(spill);
|
||
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
ScheduleFeedback(() => spill.RemoveFromHierarchy(), CombatTuning.ReducedMotionOverflowTravelMs);
|
||
return;
|
||
}
|
||
|
||
ScheduleFeedback(() =>
|
||
{
|
||
spill.style.left = destinationRect.center.x - 20f;
|
||
spill.style.top = destinationRect.center.y - 12f;
|
||
spill.style.opacity = 0f;
|
||
}, 20);
|
||
ScheduleFeedback(() => spill.RemoveFromHierarchy(), CombatTuning.OverflowTravelMs + 80);
|
||
}
|
||
|
||
private void FlashDamageVignette(HitMagnitudeTier tier)
|
||
{
|
||
if (_damageVignette == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
string className = tier >= HitMagnitudeTier.Massive
|
||
? "damage-vignette-massive"
|
||
: tier >= HitMagnitudeTier.Major
|
||
? "damage-vignette-crit"
|
||
: "damage-vignette-on";
|
||
PlayElementBeat(_damageVignette, className, UIPreferences.ReducedMotion ? 120 : tier >= HitMagnitudeTier.Massive ? 360 : tier >= HitMagnitudeTier.Major ? 300 : 180);
|
||
}
|
||
|
||
private static void RemoveFeedbackBeatClasses(VisualElement element)
|
||
{
|
||
element.RemoveFromClassList("feedback-hit-minor");
|
||
element.RemoveFromClassList("feedback-hit");
|
||
element.RemoveFromClassList("feedback-hit-major");
|
||
element.RemoveFromClassList("feedback-crit");
|
||
element.RemoveFromClassList("feedback-clang");
|
||
element.RemoveFromClassList("feedback-clang-major");
|
||
element.RemoveFromClassList("feedback-block");
|
||
element.RemoveFromClassList("feedback-status");
|
||
element.RemoveFromClassList("feedback-boost");
|
||
element.RemoveFromClassList("feedback-killed");
|
||
element.RemoveFromClassList("enemy-anticipating");
|
||
element.RemoveFromClassList("enemy-acting");
|
||
element.RemoveFromClassList("phase-pulse");
|
||
element.RemoveFromClassList("cycles-spent-beat");
|
||
element.RemoveFromClassList("feedback-denied");
|
||
element.RemoveFromClassList("queue-chip-resolve");
|
||
element.RemoveFromClassList("stack-chip-resolve");
|
||
element.RemoveFromClassList("hand-card-drawn");
|
||
element.RemoveFromClassList("damage-vignette-on");
|
||
element.RemoveFromClassList("damage-vignette-crit");
|
||
element.RemoveFromClassList("damage-vignette-massive");
|
||
element.RemoveFromClassList("damage-vignette-rolling-release");
|
||
element.RemoveFromClassList("feedback-fedora-payoff");
|
||
element.RemoveFromClassList("feedback-spawned");
|
||
element.RemoveFromClassList("fedora-risk-snap");
|
||
element.RemoveFromClassList("arch-btw-pop");
|
||
element.RemoveFromClassList("arch-btw-reset");
|
||
element.RemoveFromClassList("arch-btw-persist");
|
||
}
|
||
|
||
private int ScheduleCombatBeat(Action action, int holdMs = 0)
|
||
{
|
||
return ScheduleCombatBeat(_ => action?.Invoke(), holdMs);
|
||
}
|
||
|
||
private int ScheduleCombatBeat(Action<int> action, int holdMs = 0)
|
||
{
|
||
if (action == null)
|
||
{
|
||
return 0;
|
||
}
|
||
|
||
int beatIndex = _feedbackCascadeIndex++;
|
||
int delay = _combatBeatCursorMs;
|
||
int step = CombatBeatStepMs(holdMs);
|
||
_combatBeatCursorMs += step;
|
||
int version = ++_combatBeatCursorVersion;
|
||
ScheduleFeedback(() => action(beatIndex), delay);
|
||
ScheduleFeedback(() =>
|
||
{
|
||
if (_combatBeatCursorVersion == version)
|
||
{
|
||
_combatBeatCursorMs = 0;
|
||
}
|
||
}, delay + step + CombatTuning.CombatBeatSettleMs);
|
||
return delay + step;
|
||
}
|
||
|
||
private static int CombatBeatStepMs(int holdMs)
|
||
{
|
||
if (UIPreferences.ReducedMotion)
|
||
{
|
||
int compressed = holdMs <= 0 ? CombatTuning.ReducedMotionCombatBeatDefaultMs : holdMs / 4;
|
||
return Mathf.Clamp(compressed, CombatTuning.ReducedMotionCombatBeatMinMs, CombatTuning.ReducedMotionCombatBeatMaxMs);
|
||
}
|
||
|
||
return Mathf.Max(CombatTuning.CombatBeatDefaultMs, holdMs);
|
||
}
|
||
|
||
private void ScheduleFeedback(Action action, int delayMs)
|
||
{
|
||
if (action == null || _root == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
IVisualElementScheduledItem scheduled = null;
|
||
scheduled = _root.schedule.Execute(() =>
|
||
{
|
||
_scheduledFeedback.Remove(scheduled);
|
||
if (isActiveAndEnabled) action();
|
||
}).StartingIn(Mathf.Max(0, delayMs));
|
||
_scheduledFeedback.Add(scheduled);
|
||
}
|
||
|
||
private static void ApplyStatusStateClasses(VisualElement element, CombatantState state)
|
||
{
|
||
if (element == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
RemoveStatusStateClasses(element);
|
||
if (state == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
for (int i = 0; i < state.Statuses.Count; i++)
|
||
{
|
||
ApplyStatusStateClass(element, state.Statuses[i].Type, true);
|
||
}
|
||
}
|
||
|
||
private static void ApplyStatusStateClass(VisualElement element, StatusType statusType, bool enabled)
|
||
{
|
||
string className = StatusStateClass(statusType);
|
||
if (element == null || string.IsNullOrEmpty(className))
|
||
{
|
||
return;
|
||
}
|
||
|
||
element.EnableInClassList(className, enabled);
|
||
}
|
||
|
||
private static void RemoveStatusStateClasses(VisualElement element)
|
||
{
|
||
ApplyStatusStateClass(element, StatusType.MemoryLeak, false);
|
||
ApplyStatusStateClass(element, StatusType.Segfault, false);
|
||
ApplyStatusStateClass(element, StatusType.RaceCondition, false);
|
||
ApplyStatusStateClass(element, StatusType.Deprecated, false);
|
||
ApplyStatusStateClass(element, StatusType.DependencyError, false);
|
||
ApplyStatusStateClass(element, StatusType.Deadlock, false);
|
||
ApplyStatusStateClass(element, StatusType.UnattendedUpgrades, false);
|
||
}
|
||
|
||
private void HandleCombatLog(string message) => AppendCombatLog(message);
|
||
|
||
private void AppendCombatLog(string message, string tone = null)
|
||
{
|
||
if (string.IsNullOrEmpty(message) || message.Contains("would resolve:")) return;
|
||
if (_journalEntries != null)
|
||
{
|
||
bool atLatest = _journalScroll.verticalScroller.highValue - _journalScroll.scrollOffset.y < 24;
|
||
_journal.text = message ?? "journal / recent combat events";
|
||
string line = $"[{TimeSpan.FromSeconds(Time.realtimeSinceStartup - _journalStartedAt):mm\\:ss}] {message}";
|
||
_recentLog.Enqueue(line);
|
||
while (_recentLog.Count > 64) _recentLog.Dequeue();
|
||
var entry = SoftwareCardView.Text(line, "journal-entry");
|
||
if (tone != null) entry.AddToClassList(tone);
|
||
_journalEntries.Add(entry);
|
||
while (_journalEntries.childCount > 64) _journalEntries.RemoveAt(0);
|
||
if (atLatest) ScheduleFeedback(() => _journalScroll.scrollOffset = new Vector2(0, _journalScroll.verticalScroller.highValue), 0);
|
||
}
|
||
}
|
||
|
||
private string CombatantName(CombatantState state)
|
||
{
|
||
if (state == _combatManager.PlayerState) return "host";
|
||
foreach (var enemy in _combatManager.Enemies) if (enemy.State == state) return enemy.Name;
|
||
return "process";
|
||
}
|
||
|
||
private VisualElement CardChip(CardInstance card)
|
||
{
|
||
VisualElement chip = new();
|
||
chip.AddToClassList("card-chip");
|
||
chip.AddToClassList(LanguageClass(card.Definition.Language));
|
||
Label name = new(DisplayName(card.Definition));
|
||
name.AddToClassList("card-chip-name");
|
||
Label meta = new($"{GetDisplayCardCost(card)}c / {TrackText(card.Definition.ResolutionTrack)}");
|
||
meta.AddToClassList("card-chip-meta");
|
||
chip.Add(name);
|
||
chip.Add(meta);
|
||
return chip;
|
||
}
|
||
|
||
private static VisualElement EmptyState(string text)
|
||
{
|
||
Label label = new(text);
|
||
label.AddToClassList("empty-state");
|
||
return label;
|
||
}
|
||
|
||
private int GetDisplayCardCost(CardInstance card)
|
||
{
|
||
return _combatManager == null ? CombatManager.GetCardCost(card) : _combatManager.GetDisplayedPlayCost(card);
|
||
}
|
||
|
||
private static VisualElement CreatePanel(string title, string subtitle, float width)
|
||
{
|
||
VisualElement panel = new();
|
||
panel.AddToClassList("panel");
|
||
if (width > 0f)
|
||
{
|
||
panel.style.width = width;
|
||
panel.style.minWidth = width;
|
||
}
|
||
|
||
panel.Add(PanelHeader(title, subtitle));
|
||
return panel;
|
||
}
|
||
|
||
private static VisualElement PanelHeader(string title, string subtitle)
|
||
{
|
||
VisualElement header = new();
|
||
header.AddToClassList("panel-header");
|
||
Label titleLabel = new(title);
|
||
titleLabel.AddToClassList("panel-title");
|
||
Label subtitleLabel = new(subtitle);
|
||
subtitleLabel.AddToClassList("panel-subtitle");
|
||
header.Add(titleLabel);
|
||
header.Add(subtitleLabel);
|
||
return header;
|
||
}
|
||
|
||
private void ApplyAccent(VisualElement element)
|
||
{
|
||
element.style.borderTopColor = _distroAccent;
|
||
}
|
||
|
||
private static VisualElement TurnStat(string labelText, string valueText)
|
||
{
|
||
return TerminalLayout.StatRow(labelText, valueText, rowClass: "turn-stat-row",
|
||
keyClass: "turn-stat-label", valueClass: "turn-stat-value");
|
||
}
|
||
|
||
private static Label OverlayTitle(string text)
|
||
{
|
||
return TerminalLayout.Heading(text, className: "overlay-title");
|
||
}
|
||
|
||
private static Label OverlayLine(string text)
|
||
{
|
||
return TerminalLayout.BodyText(text, className: "overlay-line");
|
||
}
|
||
|
||
private static VisualElement DeathStat(string labelText, string valueText)
|
||
{
|
||
return TerminalLayout.StatRow(labelText, valueText, rowClass: "death-stat-row",
|
||
keyClass: "death-stat-label", valueClass: "death-stat-value");
|
||
}
|
||
|
||
private static VisualElement RewardReadout(string iconText, int amount, string currencyName, bool subdued)
|
||
{
|
||
VisualElement item = new();
|
||
item.AddToClassList("death-reward-item");
|
||
item.AddToClassList($"death-reward-{currencyName}");
|
||
item.EnableInClassList("death-reward-subdued", subdued);
|
||
|
||
Label icon = new(iconText);
|
||
icon.AddToClassList("death-reward-icon");
|
||
Label value = new($"+{amount}");
|
||
value.AddToClassList("death-reward-value");
|
||
Label name = new(currencyName);
|
||
name.AddToClassList("death-reward-name");
|
||
|
||
item.Add(icon);
|
||
item.Add(value);
|
||
item.Add(name);
|
||
return item;
|
||
}
|
||
|
||
private static VisualElement Tag(string text, string className)
|
||
{
|
||
Label tag = new(text);
|
||
tag.AddToClassList("tag");
|
||
if (!string.IsNullOrEmpty(className))
|
||
{
|
||
tag.AddToClassList(className);
|
||
}
|
||
|
||
return tag;
|
||
}
|
||
|
||
private static string BuildPips(int current, int max)
|
||
{
|
||
int safeMax = Mathf.Max(0, max);
|
||
int safeCurrent = Mathf.Clamp(current, 0, safeMax);
|
||
return string.Concat(Repeat(FilledCycle, safeCurrent), Repeat(EmptyCycle, safeMax - safeCurrent));
|
||
}
|
||
|
||
private static string Repeat(string value, int count)
|
||
{
|
||
if (count <= 0)
|
||
{
|
||
return string.Empty;
|
||
}
|
||
|
||
string result = string.Empty;
|
||
for (int i = 0; i < count; i++)
|
||
{
|
||
result += value;
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
private static string DurationText(int duration)
|
||
{
|
||
return duration == -1 ? "inf" : $"{duration}t";
|
||
}
|
||
|
||
private static string PhaseText(TurnPhase phase)
|
||
{
|
||
return phase switch
|
||
{
|
||
TurnPhase.Boot => "boot",
|
||
TurnPhase.Allocate => "allocate",
|
||
TurnPhase.Execute => "execute",
|
||
TurnPhase.Interpret => "interpret",
|
||
TurnPhase.EnemyProcess => "enemy",
|
||
TurnPhase.GarbageCollection => "cleanup",
|
||
_ => phase.ToString()
|
||
};
|
||
}
|
||
|
||
private static string FormatWalletWithAccrual(int walletAmount, int accruedAmount)
|
||
{
|
||
return accruedAmount > 0 ? $"{walletAmount} (+{accruedAmount})" : walletAmount.ToString();
|
||
}
|
||
|
||
private static string TrackText(ResolutionTrack track)
|
||
{
|
||
return track switch
|
||
{
|
||
ResolutionTrack.Native => "Native",
|
||
ResolutionTrack.InterpreterQueue => "Queue",
|
||
ResolutionTrack.LazyStack => "Stack",
|
||
_ => track.ToString()
|
||
};
|
||
}
|
||
|
||
private static string IntentIcon(EnemyIntent intent)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(intent.IconKey))
|
||
{
|
||
return intent.IconKey;
|
||
}
|
||
|
||
return intent.Kind switch
|
||
{
|
||
EnemyIntentKind.Attack => "!",
|
||
EnemyIntentKind.StatusAttack => "!",
|
||
EnemyIntentKind.Defend => "#",
|
||
EnemyIntentKind.Buff => "+",
|
||
EnemyIntentKind.Special => "*",
|
||
_ => "?"
|
||
};
|
||
}
|
||
|
||
private static string IntentText(EnemyIntent intent)
|
||
{
|
||
return intent.Kind switch
|
||
{
|
||
EnemyIntentKind.Attack => intent.TrueDamage ? "bypasses Shield" : "attack",
|
||
EnemyIntentKind.StatusAttack => $"{intent.DisplayLabel} x{intent.StatusStacks}",
|
||
EnemyIntentKind.Defend => "defend",
|
||
EnemyIntentKind.Buff => "buff",
|
||
EnemyIntentKind.Special => intent.DisplayLabel,
|
||
_ => intent.DisplayLabel
|
||
};
|
||
}
|
||
|
||
private static string IntentClass(EnemyIntentKind kind)
|
||
{
|
||
return kind switch
|
||
{
|
||
EnemyIntentKind.Attack => "intent-attack",
|
||
EnemyIntentKind.StatusAttack => "intent-attack",
|
||
EnemyIntentKind.Defend => "intent-defend",
|
||
_ => "intent-special"
|
||
};
|
||
}
|
||
|
||
private static string StatusStateClass(StatusType statusType)
|
||
{
|
||
return statusType switch
|
||
{
|
||
StatusType.MemoryLeak => "status-state-leaking",
|
||
StatusType.Segfault => "status-state-segfault",
|
||
StatusType.RaceCondition => "status-state-race",
|
||
StatusType.Deprecated => "status-state-deprecated",
|
||
StatusType.DependencyError => "status-state-dependency-error",
|
||
StatusType.Deadlock => "status-state-deadlock",
|
||
StatusType.UnattendedUpgrades => "status-state-upgrading",
|
||
_ => string.Empty
|
||
};
|
||
}
|
||
|
||
private static string OfferKindText(RepositoryOfferKind kind)
|
||
{
|
||
return kind switch
|
||
{
|
||
RepositoryOfferKind.NewCard => "card",
|
||
RepositoryOfferKind.CardUpgrade => "upgrade",
|
||
RepositoryOfferKind.StatUpgrade => "stat",
|
||
_ => "offer"
|
||
};
|
||
}
|
||
|
||
private static string OfferKindIcon(RepositoryOfferKind kind)
|
||
{
|
||
return kind switch
|
||
{
|
||
RepositoryOfferKind.NewCard => "+",
|
||
RepositoryOfferKind.CardUpgrade => "▲",
|
||
RepositoryOfferKind.StatUpgrade => "◆",
|
||
_ => "?"
|
||
};
|
||
}
|
||
|
||
private static string OfferTileClass(RepositoryOfferKind kind)
|
||
{
|
||
return kind switch
|
||
{
|
||
RepositoryOfferKind.NewCard => "repository-tile-card",
|
||
RepositoryOfferKind.CardUpgrade => "repository-tile-upgrade",
|
||
RepositoryOfferKind.StatUpgrade => "repository-tile-stat",
|
||
_ => "repository-tile-generic"
|
||
};
|
||
}
|
||
|
||
private static string StatOfferIcon(RunStatUpgradeKind kind)
|
||
{
|
||
return kind switch
|
||
{
|
||
RunStatUpgradeKind.Heal => "♥",
|
||
RunStatUpgradeKind.MaxCycles => "●",
|
||
RunStatUpgradeKind.MaxUptime => "▰",
|
||
RunStatUpgradeKind.Ram => "RAM",
|
||
_ => "◆"
|
||
};
|
||
}
|
||
|
||
private static string OfferCommandText(RepositoryOffer offer)
|
||
{
|
||
return offer.Kind switch
|
||
{
|
||
RepositoryOfferKind.CardUpgrade => $"apt upgrade {offer.CommandName}",
|
||
RepositoryOfferKind.StatUpgrade => $"apt install {offer.CommandName}",
|
||
_ => $"apt install {offer.CommandName}"
|
||
};
|
||
}
|
||
|
||
private static string OfferActionText(RepositoryOfferKind kind)
|
||
{
|
||
return kind switch
|
||
{
|
||
RepositoryOfferKind.CardUpgrade => "apt upgrade",
|
||
RepositoryOfferKind.StatUpgrade => "apt apply",
|
||
_ => "apt install"
|
||
};
|
||
}
|
||
|
||
private static string MeterFillClass(MeterTone tone, float ratio)
|
||
{
|
||
if (tone == MeterTone.Uptime)
|
||
{
|
||
if (ratio <= 0.25f)
|
||
{
|
||
return "meter-fill-danger";
|
||
}
|
||
|
||
if (ratio <= 0.5f)
|
||
{
|
||
return "meter-fill-warning";
|
||
}
|
||
}
|
||
|
||
return tone switch
|
||
{
|
||
MeterTone.Beneficial => "meter-fill-beneficial",
|
||
MeterTone.Muted => "metric-value-muted",
|
||
_ => "meter-fill"
|
||
};
|
||
}
|
||
|
||
private static string LanguageClass(Language language)
|
||
{
|
||
return language switch
|
||
{
|
||
Language.C => "language-c",
|
||
Language.CPlusPlus => "language-cpp",
|
||
Language.Rust => "language-rust",
|
||
Language.Python => "language-python",
|
||
Language.JavaScript => "language-javascript",
|
||
Language.TypeScript => "language-typescript",
|
||
Language.Haskell => "language-haskell",
|
||
Language.Assembly => "language-assembly",
|
||
Language.Java => "language-java",
|
||
Language.Go => "language-go",
|
||
Language.Ruby => "language-ruby",
|
||
Language.Php => "language-php",
|
||
_ => "track-tag"
|
||
};
|
||
}
|
||
|
||
private static string CardRarityClass(Rarity rarity)
|
||
{
|
||
return rarity switch
|
||
{
|
||
Rarity.Rare => "hand-card-rare",
|
||
Rarity.Epic => "hand-card-epic",
|
||
Rarity.Legendary => "hand-card-legendary",
|
||
_ => string.Empty
|
||
};
|
||
}
|
||
|
||
private static string RarityTagClass(Rarity rarity)
|
||
{
|
||
return rarity switch
|
||
{
|
||
Rarity.Rare => "rarity-rare",
|
||
Rarity.Epic => "rarity-epic",
|
||
Rarity.Legendary => "rarity-legendary",
|
||
_ => "track-tag"
|
||
};
|
||
}
|
||
|
||
private static string DisplayName(DistroDefinition distro)
|
||
{
|
||
return distro == null ? "--" : string.IsNullOrWhiteSpace(distro.DisplayName) ? distro.Id : distro.DisplayName;
|
||
}
|
||
|
||
private static string DisplayName(CardDefinition card)
|
||
{
|
||
return card == null ? "--" : string.IsNullOrWhiteSpace(card.DisplayName) ? card.Id : card.DisplayName;
|
||
}
|
||
|
||
private enum MeterTone
|
||
{
|
||
Uptime,
|
||
Beneficial,
|
||
Muted
|
||
}
|
||
}
|
||
}
|