Revamp UI a whole lot

This commit is contained in:
2026-11-18 19:42:44 +01:00
parent 260abc2c98
commit fdde7f9d80
57 changed files with 2667 additions and 935 deletions
+78 -14
View File
@@ -26,13 +26,24 @@ namespace KernelPanic.Meta
/// <summary>One persistent, rolling 24-hour window. All time comes from the caller for deterministic tests.</summary>
public static class DailyQuests
{
public const int Count = 3;
public const int Count = 5;
public const int CompletionBonusBandwidth = 250;
public const int CompletionBonusEntropy = 125;
public const int CompletionBonusCommits = 2;
public const long PeriodTicks = TimeSpan.TicksPerDay;
public static readonly IReadOnlyList<DailyQuestKind> Pool = Array.AsReadOnly((DailyQuestKind[])Enum.GetValues(typeof(DailyQuestKind)));
private static readonly DailyQuestKind[] LegacySelection = { DailyQuestKind.Waves, DailyQuestKind.Cards, DailyQuestKind.Damage };
private const int CompletionBonusBit = 1 << 8;
private static readonly DailyQuestKind[] FallbackSelection =
{
DailyQuestKind.Waves,
DailyQuestKind.Cards,
DailyQuestKind.Damage,
DailyQuestKind.BlockDamage,
DailyQuestKind.NativeCards
};
public static IReadOnlyList<DailyQuestKind> Active(DailyQuestState state) =>
ValidSelection(state.selectedQuests) ? state.selectedQuests : LegacySelection;
ValidSelection(state.selectedQuests) ? state.selectedQuests : FallbackSelection;
public static bool IsActive(DailyQuestState state, DailyQuestKind kind)
{
@@ -51,6 +62,28 @@ namespace KernelPanic.Meta
return true;
}
private static bool EnsureFiveQuestSelection(DailyQuestState state)
{
if (ValidSelection(state.selectedQuests)) return false;
var expanded = new List<DailyQuestKind>(Count);
if (state.selectedQuests != null)
{
foreach (var kind in state.selectedQuests)
{
if (!Enum.IsDefined(typeof(DailyQuestKind), kind) || expanded.Contains(kind)) continue;
expanded.Add(kind);
if (expanded.Count == Count) break;
}
}
foreach (var kind in Pool)
{
if (!expanded.Contains(kind)) expanded.Add(kind);
if (expanded.Count == Count) break;
}
state.selectedQuests = expanded.ToArray();
return true;
}
private static void PickQuests(DailyQuestState state)
{
if (state.selectionSeed == 0)
@@ -101,6 +134,20 @@ namespace KernelPanic.Meta
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
// Commits are earned by objectives that represent sustained play or a run milestone.
public static int CommitReward(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => 1,
DailyQuestKind.ShieldDamage => 1,
DailyQuestKind.SurviveRounds => 1,
DailyQuestKind.WaveFive => 2,
DailyQuestKind.Cards => 0,
DailyQuestKind.NativeCards => 0,
DailyQuestKind.Damage => 0,
DailyQuestKind.BlockDamage => 0,
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
public static string Description(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => "Clear 3 waves",
@@ -130,19 +177,25 @@ namespace KernelPanic.Meta
public static bool Claimed(DailyQuestState state, DailyQuestKind kind) =>
(state.claimedMask & (1 << (int)kind)) != 0;
public static bool CompletionBonusClaimed(DailyQuestState state) =>
(state.claimedMask & CompletionBonusBit) != 0;
public static bool AllClaimed(DailyQuestState state)
{
foreach (var kind in Active(state)) if (!Claimed(state, kind)) return false;
return true;
}
public static bool Refresh(DailyQuestState state, DateTime utcNow)
{
long now = utcNow.ToUniversalTime().Ticks;
if (state.refreshAtUtcTicks > now && state.refreshAtUtcTicks <= DateTime.MaxValue.Ticks)
{
if (ValidSelection(state.selectedQuests)) return false;
// Schema 7 had three fixed quests. Preserve that day's progress and rewards.
state.selectedQuests = (DailyQuestKind[])LegacySelection.Clone();
return true;
// Expand older three-task periods in place so their progress and claims survive migration.
return EnsureFiveQuestSelection(state);
}
// Advance by whole periods, retaining the original reset time even after days away.
if (state.refreshAtUtcTicks > 0 && !ValidSelection(state.selectedQuests))
state.selectedQuests = (DailyQuestKind[])LegacySelection.Clone();
if (state.refreshAtUtcTicks > 0) EnsureFiveQuestSelection(state);
state.refreshAtUtcTicks = state.refreshAtUtcTicks > 0 && state.refreshAtUtcTicks <= now
? state.refreshAtUtcTicks + ((now - state.refreshAtUtcTicks) / PeriodTicks + 1) * PeriodTicks
: now + PeriodTicks;
@@ -181,11 +234,22 @@ namespace KernelPanic.Meta
if (!Enum.IsDefined(typeof(DailyQuestKind), kind) || !IsActive(data.dailyQuests, kind) || data.dailyQuests.refreshAtUtcTicks != expectedRefresh
|| Claimed(data.dailyQuests, kind) || Progress(data.dailyQuests, kind) < Target(kind)) return false;
var reward = Reward(kind);
if (data.bandwidthBalance > int.MaxValue - reward.Bandwidth
|| data.entropyBalance > int.MaxValue - reward.Entropy) return false;
data.dailyQuests.claimedMask |= 1 << (int)kind;
data.bandwidthBalance += reward.Bandwidth;
data.entropyBalance += reward.Entropy;
int commits = CommitReward(kind);
int questBit = 1 << (int)kind;
int nextMask = data.dailyQuests.claimedMask | questBit;
bool awardsCompletionBonus = !CompletionBonusClaimed(data.dailyQuests);
foreach (var activeKind in Active(data.dailyQuests))
awardsCompletionBonus &= (nextMask & (1 << (int)activeKind)) != 0;
int bandwidth = reward.Bandwidth + (awardsCompletionBonus ? CompletionBonusBandwidth : 0);
int entropy = reward.Entropy + (awardsCompletionBonus ? CompletionBonusEntropy : 0);
int totalCommits = commits + (awardsCompletionBonus ? CompletionBonusCommits : 0);
if (data.bandwidthBalance > int.MaxValue - bandwidth
|| data.entropyBalance > int.MaxValue - entropy
|| data.commitsBalance > int.MaxValue - totalCommits) return false;
data.dailyQuests.claimedMask = nextMask | (awardsCompletionBonus ? CompletionBonusBit : 0);
data.bandwidthBalance += bandwidth;
data.entropyBalance += entropy;
data.commitsBalance += totalCommits;
return true;
}
+28
View File
@@ -32,4 +32,32 @@ namespace KernelPanic.Meta
guaranteedDistroIds ??= new List<string>();
}
}
/// <summary>Persistent, bounded receipt rendered by <c>git log --pulls</c>.</summary>
[Serializable]
public sealed class GachaPullHistoryEntry
{
public string pulledUtc;
public string bannerId;
public int currencySpent;
public int entropySpent;
public List<GachaPullHistoryRewardEntry> rewards = new();
public void EnsureLists()
{
rewards ??= new List<GachaPullHistoryRewardEntry>();
}
}
[Serializable]
public sealed class GachaPullHistoryRewardEntry
{
public int stars;
public string displayName;
public GachaRewardType rewardType;
public PullOutcomeKind outcomeKind;
public int duplicateValue;
public bool guaranteed;
public bool pityTriggered;
}
}
+191 -1
View File
@@ -17,7 +17,11 @@ namespace KernelPanic.Meta
public const int BeginnerTenPullCost = 8;
public const int StandardSinglePullCost = 1;
public const int StandardTenPullCost = 10;
public const int LimitedSinglePullCost = 1;
public const int LimitedTenPullCost = 10;
public const int StandardFiveStarSelectorInterval = 200;
public const int MaxPullHistoryEntries = 100;
public const string LimitedFeaturedFiveStarDistroId = "nixos";
public const int FourStarHardPity = 10;
public const int FiveStarSoftPityStart = 66;
public const int FiveStarHardPity = 80;
@@ -32,10 +36,12 @@ namespace KernelPanic.Meta
private const double LimitedStandardFiveStarChance = 1d / 3d;
private readonly List<DistroDefinition> _bannerPool = new();
private readonly List<GachaPullHistoryEntry> _pullHistory = new();
private readonly Dictionary<GachaCurrencyType, int> _currencyBalances = new();
private readonly Random _random;
private GachaBannerState _beginnerState = new(BeginnerBannerId);
private GachaBannerState _standardState = new(StandardBannerId);
private GachaBannerState _limitedState = new(LimitedBannerId);
public GachaService()
: this(new Random())
@@ -54,6 +60,8 @@ namespace KernelPanic.Meta
public IReadOnlyList<DistroDefinition> BannerPool => _bannerPool;
public GachaBannerState BeginnerState => _beginnerState;
public GachaBannerState StandardState => _standardState;
public GachaBannerState LimitedState => _limitedState;
public IReadOnlyList<GachaPullHistoryEntry> PullHistory => _pullHistory;
public bool IsBeginnerBannerAvailable => !_beginnerState.exhausted && _beginnerState.totalPulls < BeginnerMaxPulls && _bannerPool.Count > 0;
public int PendingStandardFiveStarSelectors => Math.Max(0, _standardState.totalPulls / StandardFiveStarSelectorInterval - _standardState.fiveStarSelectorsClaimed);
@@ -86,6 +94,19 @@ namespace KernelPanic.Meta
_standardState.fiveStarPityCounter = Math.Max(0, _standardState.fiveStarPityCounter);
_standardState.fiveStarSelectorsClaimed = Math.Max(0, _standardState.fiveStarSelectorsClaimed);
_limitedState = data.limitedBannerState ?? new GachaBannerState(LimitedBannerId);
_limitedState.bannerId = LimitedBannerId;
_limitedState.EnsureLists();
_limitedState.pityCounter = Math.Max(0, _limitedState.pityCounter);
_limitedState.fiveStarPityCounter = Math.Max(0, _limitedState.fiveStarPityCounter);
_pullHistory.Clear();
for (int i = 0; i < data.gachaPullHistory.Count && i < MaxPullHistoryEntries; i++)
{
GachaPullHistoryEntry entry = CloneHistoryEntry(data.gachaPullHistory[i]);
if (entry != null) _pullHistory.Add(entry);
}
Changed?.Invoke();
}
@@ -101,6 +122,10 @@ namespace KernelPanic.Meta
data.commitsBalance = GetCurrencyBalance(GachaCurrencyType.StandardPull);
data.beginnerBannerState = CloneState(_beginnerState);
data.standardBannerState = CloneState(_standardState);
data.limitedBannerState = CloneState(_limitedState);
data.gachaPullHistory.Clear();
for (int i = 0; i < _pullHistory.Count && i < MaxPullHistoryEntries; i++)
data.gachaPullHistory.Add(CloneHistoryEntry(_pullHistory[i]));
}
public int GetCurrencyBalance(GachaCurrencyType currencyType)
@@ -235,7 +260,7 @@ namespace KernelPanic.Meta
return false;
}
}
else if (bannerId != StandardBannerId)
else if (bannerId != StandardBannerId && bannerId != LimitedBannerId)
{
failureReason = $"banner '{bannerId}' not implemented yet";
return false;
@@ -271,6 +296,11 @@ namespace KernelPanic.Meta
return pullCount == 10 ? StandardTenPullCost : StandardSinglePullCost;
}
if (bannerId == LimitedBannerId)
{
return pullCount == 10 ? LimitedTenPullCost : LimitedSinglePullCost;
}
return pullCount;
}
@@ -370,6 +400,64 @@ namespace KernelPanic.Meta
return new GachaPullResult(true, StandardBannerId, GachaCurrencyType.StandardPull, commitSpend, entropySpent, rewards, null);
}
public GachaPullResult PerformLimitedPull(int pullCount, EntropyWallet wallet, PullPaymentSource source)
{
if (!CanAffordPull(pullCount, wallet, source, LimitedBannerId, out string failureReason))
{
return GachaPullResult.Failed(LimitedBannerId, failureReason);
}
if (!PayForPull(pullCount, wallet, source, LimitedBannerId, out int commitSpend, out int entropySpent, out failureReason))
{
return GachaPullResult.Failed(LimitedBannerId, failureReason);
}
List<GachaReward> rewards = new();
for (int i = 0; i < pullCount; i++)
{
_limitedState.totalPulls++;
rewards.Add(RollLimitedReward(_limitedState));
}
Changed?.Invoke();
return new GachaPullResult(true, LimitedBannerId, GachaCurrencyType.StandardPull, commitSpend, entropySpent, rewards, null);
}
public void RecordPullHistory(GachaPullResult result, IReadOnlyList<CompletedGachaReward> completedRewards, DateTime utcNow)
{
if (!result.Success || completedRewards == null || completedRewards.Count == 0)
{
return;
}
GachaPullHistoryEntry entry = new()
{
pulledUtc = utcNow.ToUniversalTime().ToString("O"),
bannerId = result.BannerId,
currencySpent = Math.Max(0, result.CurrencySpent),
entropySpent = Math.Max(0, result.EntropySpent)
};
for (int i = 0; i < completedRewards.Count; i++)
{
CompletedGachaReward reward = completedRewards[i];
entry.rewards.Add(new GachaPullHistoryRewardEntry
{
stars = reward.Stars,
displayName = reward.DisplayName,
rewardType = reward.RewardType,
outcomeKind = reward.OutcomeKind,
duplicateValue = reward.MergesAwarded,
guaranteed = reward.Guaranteed,
pityTriggered = reward.PityTriggered
});
}
_pullHistory.Insert(0, entry);
if (_pullHistory.Count > MaxPullHistoryEntries)
_pullHistory.RemoveRange(MaxPullHistoryEntries, _pullHistory.Count - MaxPullHistoryEntries);
Changed?.Invoke();
}
public int GetStandardFiveStarSelectorProgress()
{
return _standardState.totalPulls % StandardFiveStarSelectorInterval;
@@ -526,6 +614,50 @@ namespace KernelPanic.Meta
return GachaReward.Package(4, "4-star package", pityTriggered, false);
}
private GachaReward RollLimitedReward(GachaBannerState state)
{
if (TryRollFiveStar(state, out bool fiveStarPityTriggered))
{
if (!ResolveFeaturedTierIsDistro())
{
return GachaReward.Package(5, "5-star package", fiveStarPityTriggered, false);
}
bool featuredWasGuaranteed = state.featuredFiveStarGuaranteed;
bool useStandardPool = ResolveLimitedFiveStarUsesStandardPool(state);
DistroDefinition distro = useStandardPool
? FindRandomBannerPoolDistroByStarsExcept(5, LimitedFeaturedFiveStarDistroId)
: FindBannerPoolDistroByStars(LimitedFeaturedFiveStarDistroId, 5) ?? FindRandomBannerPoolDistroByStars(5);
if (distro == null)
{
return GachaReward.Package(5, "5-star package", fiveStarPityTriggered, false);
}
return GachaReward.DistroReward(distro, 5, fiveStarPityTriggered, featuredWasGuaranteed,
featuredWasGuaranteed ? "feature-branch guarantee" : null);
}
bool pityTriggered = state.pityCounter >= FourStarHardPity - 1;
bool hitFourStar = pityTriggered || _random.NextDouble() < FourStarBaseChance;
if (!hitFourStar)
{
state.pityCounter++;
return GachaReward.Package(3, "3-star package", false, false);
}
state.pityCounter = 0;
if (ResolveFeaturedTierIsDistro())
{
DistroDefinition distro = FindLimitedFourStarDistro();
if (distro != null)
{
return GachaReward.DistroReward(distro, 4, pityTriggered, false);
}
}
return GachaReward.Package(4, "4-star package", pityTriggered, false);
}
private bool TryRollFiveStar(GachaBannerState state, out bool pityTriggered)
{
state ??= _beginnerState;
@@ -668,6 +800,35 @@ namespace KernelPanic.Meta
return eligible.Count == 0 ? null : eligible[_random.Next(eligible.Count)];
}
private DistroDefinition FindRandomBannerPoolDistroByStarsExcept(int stars, string excludedId)
{
List<DistroDefinition> eligible = new();
for (int i = 0; i < _bannerPool.Count; i++)
{
DistroDefinition distro = _bannerPool[i];
if (distro != null && GetDistroStars(distro) == stars
&& !string.Equals(distro.Id, excludedId, StringComparison.OrdinalIgnoreCase))
{
eligible.Add(distro);
}
}
return eligible.Count == 0 ? FindRandomBannerPoolDistroByStars(stars) : eligible[_random.Next(eligible.Count)];
}
private DistroDefinition FindLimitedFourStarDistro()
{
string[] featured = { "fedora", "ubuntu" };
List<DistroDefinition> eligible = new();
for (int i = 0; i < featured.Length; i++)
{
DistroDefinition distro = FindBannerPoolDistroByStars(featured[i], 4);
if (distro != null) eligible.Add(distro);
}
return eligible.Count == 0 ? FindRandomBannerPoolDistroByStars(4) : eligible[_random.Next(eligible.Count)];
}
private static int GetDistroStars(DistroDefinition distro)
{
return DistroRarity.Stars(distro);
@@ -694,6 +855,35 @@ namespace KernelPanic.Meta
clone.guaranteedDistroIds.AddRange(state.guaranteedDistroIds);
return clone;
}
private static GachaPullHistoryEntry CloneHistoryEntry(GachaPullHistoryEntry source)
{
if (source == null || string.IsNullOrWhiteSpace(source.bannerId)) return null;
source.EnsureLists();
GachaPullHistoryEntry clone = new()
{
pulledUtc = source.pulledUtc,
bannerId = source.bannerId,
currencySpent = Math.Max(0, source.currencySpent),
entropySpent = Math.Max(0, source.entropySpent)
};
for (int i = 0; i < source.rewards.Count; i++)
{
GachaPullHistoryRewardEntry reward = source.rewards[i];
if (reward == null) continue;
clone.rewards.Add(new GachaPullHistoryRewardEntry
{
stars = Math.Max(3, reward.stars),
displayName = reward.displayName,
rewardType = reward.rewardType,
outcomeKind = reward.outcomeKind,
duplicateValue = Math.Max(0, reward.duplicateValue),
guaranteed = reward.guaranteed,
pityTriggered = reward.pityTriggered
});
}
return clone;
}
}
/// <summary>
+21 -1
View File
@@ -16,7 +16,7 @@ namespace KernelPanic.Meta
public sealed class SaveService
{
private const string SaveFileName = "kernel-panic-save.json";
public const int CurrentSchemaVersion = 10;
public const int CurrentSchemaVersion = 11;
private static readonly object FileLock = new();
public string SavePath { get; }
@@ -300,6 +300,8 @@ namespace KernelPanic.Meta
public List<string> bannerPoolIds = new();
public GachaBannerState beginnerBannerState = new(GachaService.BeginnerBannerId);
public GachaBannerState standardBannerState = new(GachaService.StandardBannerId);
public GachaBannerState limitedBannerState = new(GachaService.LimitedBannerId);
public List<GachaPullHistoryEntry> gachaPullHistory = new();
public LastRunLoadoutSaveEntry lastRunLoadout = new();
public List<RunBuildDraftSaveEntry> runBuildDrafts = new();
public string lastSetupDistroId;
@@ -344,6 +346,24 @@ namespace KernelPanic.Meta
standardBannerState ??= new GachaBannerState(GachaService.StandardBannerId);
standardBannerState.bannerId = GachaService.StandardBannerId;
standardBannerState.EnsureLists();
limitedBannerState ??= new GachaBannerState(GachaService.LimitedBannerId);
limitedBannerState.bannerId = GachaService.LimitedBannerId;
limitedBannerState.EnsureLists();
gachaPullHistory ??= new List<GachaPullHistoryEntry>();
for (int i = gachaPullHistory.Count - 1; i >= 0; i--)
{
GachaPullHistoryEntry entry = gachaPullHistory[i];
if (entry == null || string.IsNullOrWhiteSpace(entry.bannerId))
{
gachaPullHistory.RemoveAt(i);
continue;
}
entry.EnsureLists();
}
if (gachaPullHistory.Count > GachaService.MaxPullHistoryEntries)
gachaPullHistory.RemoveRange(GachaService.MaxPullHistoryEntries,
gachaPullHistory.Count - GachaService.MaxPullHistoryEntries);
lastRunLoadout ??= new LastRunLoadoutSaveEntry();
lastRunLoadout.EnsureLists();
runBuildDrafts ??= new List<RunBuildDraftSaveEntry>();
+28 -41
View File
@@ -216,14 +216,9 @@ namespace KernelPanic.Run
string originalBuild = BuildSignature(combat.RunConfig);
var view = FindFirstObjectByType<CombatSceneController>();
var previewRoot = view.GetComponent<UIDocument>().rootVisualElement;
var executionPreview = previewRoot.Q<Button>("OpenExecutionPreview");
int drawsBeforePreview = RandomRoll.DrawCount;
Submit(executionPreview);
yield return null;
var previewContents = previewRoot.Q("ExecutionPreviewPopup") ?? executionPreview;
Require(RandomRoll.DrawCount == drawsBeforePreview && previewContents.Q<Label>(className: "terminal-body") != null,
"Execution preview changed RNG or did not render its explanation.");
Submit(previewRoot.Q<Button>("CloseExecutionPreview"));
Require(previewRoot.Q<Button>("OpenExecutionPreview") == null &&
previewRoot.Q<Button>("OpenTurnResolution") == null,
"Obsolete combat popup controls are still present.");
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-campaign-smoke"))
{
var campaign = CampaignScenario(combat, view);
@@ -493,15 +488,12 @@ namespace KernelPanic.Run
if (packageFixture)
{
yield return new WaitForSecondsRealtime(1);
var packagePanel = document.rootVisualElement.Q("CombatPackages");
packagePanel.GetFirstAncestorOfType<ScrollView>().ScrollTo(packagePanel);
var packageCapture = CapturePanel(document, "package-readiness");
while (packageCapture.MoveNext()) yield return packageCapture.Current;
Call(view, "HandlePackageActivated", new PackageActivation("pkg_mint_timeshift", "Timeshift", "Full recovery notification with enough detail to overflow a narrow screen if it wraps"));
Call(view, "HandlePackageActivated", new PackageActivation("pkg_mint_cinnamon", "Cinnamon", "JavaScript damage increased for this round"));
yield return null;
packagePanel.GetFirstAncestorOfType<ScrollView>().ScrollTo(packagePanel);
packageCapture = CapturePanel(document, "package-notification");
var hostPanel = document.rootVisualElement.Q(className: "player-panel");
hostPanel.GetFirstAncestorOfType<ScrollView>().ScrollTo(hostPanel);
var packageCapture = CapturePanel(document, "package-notification");
while (packageCapture.MoveNext()) yield return packageCapture.Current;
}
// Isolated fixture gives the presentation time to display persistent state without ending the wave.
@@ -525,11 +517,9 @@ namespace KernelPanic.Run
Require(saveControl.worldBound.height > 0 && document.rootVisualElement.worldBound.Contains(saveControl.worldBound.min)
&& document.rootVisualElement.worldBound.Contains(saveControl.worldBound.max), "Planning save control is clipped.");
var capture = CapturePanel(document, "planning-save"); while (capture.MoveNext()) yield return capture.Current;
Submit(document.rootVisualElement.Q<Button>("OpenExecutionPreview"));
Require(document.rootVisualElement.Q("ExecutionPreviewPopup") != null, "Preview dialog did not open.");
capture = CapturePanel(document, "execution-preview"); while (capture.MoveNext()) yield return capture.Current;
Submit(document.rootVisualElement.Q<Button>("CloseExecutionPreview"));
Require(RandomRoll.DrawCount == draws, "Preview consumed randomness.");
Require(document.rootVisualElement.Q<Button>("OpenExecutionPreview") == null &&
document.rootVisualElement.Q("ExecutionPreviewPopup") == null,
"Execution preview should not interrupt combat.");
Submit(document.rootVisualElement.Q<Button>("SaveCombatButton"));
menu = null;
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
@@ -548,18 +538,17 @@ namespace KernelPanic.Run
Require(combat.Go.Active.Count == 1 && combat.Go.Active[0].RemainingTicks == 2, "Resumed goroutine did not tick exactly once.");
Require(combat.InterpreterQueue.Count == 0, "Resumed FIFO did not drain.");
_stage = "damage explanation";
Submit(document.rootVisualElement.Q<Button>("OpenTurnResolution"));
var resolution = document.rootVisualElement.Q("TurnResolutionPopup");
Require(resolution != null, "Results dialog did not open.");
capture = CapturePanel(document, "turn-resolution"); while (capture.MoveNext()) yield return capture.Current;
var explanation = resolution.Query<Foldout>().ToList().FirstOrDefault(f => f.text == "Damage calculation / recent hits");
Require(explanation != null, "Damage calculation foldout is missing."); explanation.value = true;
var journal = document.rootVisualElement.Q<Foldout>(className: "combat-journal");
Require(journal != null, "Combat journal is missing.");
journal.value = true;
yield return null;
capture = CapturePanel(document, "turn-journal"); while (capture.MoveNext()) yield return capture.Current;
var explanation = journal.Query<Foldout>(className: "journal-action-result").ToList()
.FirstOrDefault(f => f.Q<Label>(className: "journal-action-damage") != null);
Require(explanation != null, "Journal damage calculation is missing."); explanation.value = true;
yield return new WaitForSecondsRealtime(1);
Require(resolution.Q<ScrollView>("ResolutionActions").contentViewport.worldBound.height > 200, "Damage results viewport is too small.");
explanation.GetFirstAncestorOfType<ScrollView>()?.ScrollTo(explanation);
capture = CapturePanel(document, "damage-calculation"); while (capture.MoveNext()) yield return capture.Current;
Submit(document.rootVisualElement.Q<Button>("CloseTurnResolution"));
Require(document.rootVisualElement.Q("TurnResolutionPopup") == null, "Results dialog did not close.");
_stage = "deck analysis and upgrade comparison";
Field<System.Collections.Generic.List<EnemyInstance>>(combat, "_enemies").Clear(); Call(combat, "CheckWin");
while (!combat.AwaitingWaveContinue) yield return null;
@@ -706,14 +695,13 @@ namespace KernelPanic.Run
capturedResolution = true;
var trace = Field<CombatExecutionTrace>(view, "_executionTrace");
Require(trace.Actions.Count > 0 && trace.Actions.Any(a => a.Complete), "Practice has no observed resolution results.");
var resolution = root.Q<Button>("OpenTurnResolution");
Require(resolution != null, "Turn-resolution view is missing.");
Submit(resolution);
for (int frame = 0; frame < 4; frame++) yield return null;
var journal = root.Q<Foldout>(className: "combat-journal");
Require(journal != null, "Combat journal is missing.");
journal.value = true;
for (int frame = 0; frame < 4; frame++) yield return null;
var capture = CapturePanel(document, "training-" + language + "-resolution");
while (capture.MoveNext()) yield return capture.Current;
Submit(root.Q<Button>("CloseTurnResolution"));
journal.value = false;
}
if (combat.PendingGoroutineCard != null)
{
@@ -1121,16 +1109,13 @@ namespace KernelPanic.Run
while (capture.MoveNext()) yield return capture.Current;
var widget = root.Q<Button>("DailyQuestWidget");
var homeScroll = root.Q<ScrollView>(className: "home-scroll");
if (Screen.width >= 1280)
Require(widget.worldBound.yMax <= homeScroll.contentViewport.worldBound.yMax + 1,
"Quest widget must fit below neofetch without scrolling at 1280x720.");
else
if (widget.worldBound.yMax > homeScroll.contentViewport.worldBound.yMax + 1)
{
homeScroll.ScrollTo(widget);
capture = CapturePanel(document, "quest-widget");
while (capture.MoveNext()) yield return capture.Current;
}
Require(root.Q<Label>("DailyQuestCompleted").text == "1/3 completed", "Quest fixture progress is wrong.");
Require(root.Q<Label>("DailyQuestCompleted").text == "1/5 completed", "Quest fixture progress is wrong.");
Require(root.Q<Label>("DailyQuestRewardReady").text == "1 reward ready"
&& root.Q<Label>("DailyQuestInspect").text == "> claim available rewards", "Claimable widget feedback is wrong.");
var widgetPosition = widget.worldBound.center;
@@ -1145,6 +1130,7 @@ namespace KernelPanic.Run
var saved = new SaveService().Load();
var reward = DailyQuests.Reward(DailyQuestKind.Waves);
Require(saved.bandwidthBalance == reward.Bandwidth && saved.entropyBalance == reward.Entropy
&& saved.commitsBalance == DailyQuests.CommitReward(DailyQuestKind.Waves)
&& !root.Q<Button>("ClaimDailyQuestWaves").enabledSelf, "Quest claim did not commit exactly once.");
Require(root.Q<Button>("ClaimDailyQuestWaves").text == "[ CLAIMED ]"
&& root.Q<Label>("DailyQuestFeedback").text.Contains($"+{reward.Bandwidth} Bandwidth, +{reward.Entropy} Entropy deposited."),
@@ -1229,10 +1215,11 @@ namespace KernelPanic.Run
if (!capturedPreview && combat.InterpreterQueue.Count > 0)
{
capturedPreview = true;
Submit(document.rootVisualElement.Q<Button>("OpenExecutionPreview"));
var capture = CapturePanel(document, "execution-preview");
var journal = document.rootVisualElement.Q<Foldout>(className: "combat-journal");
journal.value = true;
var capture = CapturePanel(document, "combat-journal");
while (capture.MoveNext()) yield return capture.Current;
Submit(document.rootVisualElement.Q<Button>("CloseExecutionPreview"));
journal.value = false;
}
if (run.CurrentWaveNumber == RunJourney.BossWave && !capturedBoss)
{
+2 -1
View File
@@ -32,6 +32,7 @@ namespace KernelPanic.Run
public int bits;
public int bandwidth;
public int entropy;
public int commits;
public int maxUptimeBonus;
public int maxCyclesBonus;
public int ramBonus;
@@ -77,7 +78,7 @@ namespace KernelPanic.Run
}
Require(Guid.TryParseExact(runId, "N", out _), "Invalid run identity.");
Require(wave >= (fullCombat == null ? 2 : 1) && wave <= 100000 && wavesCleared == wave - 1, "Invalid checkpoint wave.");
Require(bits >= 0 && bandwidth >= 0 && entropy >= 0 && rerolls >= 0, "Invalid checkpoint balances.");
Require(bits >= 0 && bandwidth >= 0 && entropy >= 0 && commits >= 0 && rerolls >= 0, "Invalid checkpoint balances.");
Require(maxUptimeBonus >= 0 && maxCyclesBonus >= 0 && ramBonus >= 0, "Invalid run upgrades.");
Require(shopRandomDraws >= 0 && shopRandomDraws <= 10000000, "Invalid shop random cursor.");
Require(Enum.IsDefined(typeof(Language), primaryLanguage) && Enum.IsDefined(typeof(Language), secondaryLanguage)
+13 -2
View File
@@ -34,6 +34,7 @@ namespace KernelPanic.Run
private int _wavesCleared;
private int _accruedBandwidth;
private int _accruedEntropy;
private int _accruedCommits;
private bool _repositoryVisitActive;
private bool _rewardsSettled;
@@ -52,6 +53,7 @@ namespace KernelPanic.Run
public int WavesCleared => _wavesCleared;
public int AccruedBandwidth => _accruedBandwidth;
public int AccruedEntropy => _accruedEntropy;
public int AccruedCommits => _accruedCommits;
public bool RewardsSettled => _rewardsSettled;
public string RunId { get; private set; }
public bool IsSuspended { get; private set; }
@@ -242,6 +244,7 @@ namespace KernelPanic.Run
_wavesCleared = 0;
_accruedBandwidth = 0;
_accruedEntropy = 0;
_accruedCommits = 0;
_rewardsSettled = false;
ApplyKernelPackageBonuses(config);
InitializeRunDeck(config);
@@ -266,7 +269,7 @@ namespace KernelPanic.Run
startingCards = CurrentConfig.StartingDeck.Select(card => card.Id).ToList(),
deck = _runDeck.Select(CheckpointCard.Capture).ToList(), soldKeys = _soldOfferKeys.ToList(),
wave = currentWaveNumber, wavesCleared = _wavesCleared, bits = _bits,
bandwidth = _accruedBandwidth, entropy = _accruedEntropy,
bandwidth = _accruedBandwidth, entropy = _accruedEntropy, commits = _accruedCommits,
maxUptimeBonus = _maxUptimeBonus, maxCyclesBonus = _maxCyclesBonus, ramBonus = _ramBonus,
rerolls = _rerollsThisVisit, shopRandomDraws = _repositoryRandom.Draws,
version = 6, journey = Journey.Copy(), performance = Performance.Copy(),
@@ -307,6 +310,7 @@ namespace KernelPanic.Run
_bits = snapshot.bits;
_accruedBandwidth = snapshot.bandwidth;
_accruedEntropy = snapshot.entropy;
_accruedCommits = snapshot.commits;
_maxUptimeBonus = snapshot.maxUptimeBonus;
_maxCyclesBonus = snapshot.maxCyclesBonus;
_ramBonus = snapshot.ramBonus;
@@ -493,7 +497,7 @@ namespace KernelPanic.Run
}
_rewardsSettled = true;
return bandwidth > 0 || entropy > 0;
return bandwidth > 0 || entropy > 0 || _accruedCommits > 0;
}
public void MarkRunRewardsSettled()
@@ -536,6 +540,7 @@ namespace KernelPanic.Run
{
_accruedBandwidth += CalculateBandwidthReward(clearedWave);
_accruedEntropy += CalculateEntropyReward(clearedWave);
_accruedCommits += CalculateCommitReward(clearedWave);
}
currentWaveNumber = Mathf.Max(currentWaveNumber + 1, payload.WaveNumber + 1);
EnsureRouteSelection();
@@ -572,6 +577,12 @@ namespace KernelPanic.Run
return waveNumber >= CombatTuning.EntropyStartWave ? Mathf.Max(0, CombatTuning.EntropyPerWave) : 0;
}
private static int CalculateCommitReward(int waveNumber)
{
if (waveNumber <= 0 || waveNumber % 5 != 0) return 0;
return waveNumber == RunJourney.BossWave ? 2 : 1;
}
private void InitializeRunDeck(RunConfig config)
{
_runDeck.Clear();
+132 -74
View File
@@ -307,10 +307,20 @@ namespace KernelPanic.UI
return;
}
Label title = new("installed units");
title.AddToClassList("detail-section-title");
Label title = new("$ ls -lah ~/collection/units/");
title.AddToClassList("collection-ls-command");
_detail.Add(title);
Label total = new($"total {_units.Count}");
total.AddToClassList("collection-ls-total");
_detail.Add(total);
Label columns = new(LsText($"{"MODE",-12}{"OWNER",-8}{"SIZE",-6}{"VER",-6}{"LANG",-20}NAME"));
columns.AddToClassList("unit-ls-row");
columns.AddToClassList("unit-ls-line");
columns.AddToClassList("unit-ls-header");
_detail.Add(columns);
VisualElement roster = new();
roster.AddToClassList("unit-overview-roster");
_detail.Add(roster);
@@ -604,54 +614,51 @@ namespace KernelPanic.UI
private VisualElement BuildUnitOverviewRow(DistroDefinition unit)
{
int version = GetUnitVersion(unit);
string languages = unit.PrimaryLanguage == unit.SecondaryLanguage
? GetLanguageId(unit.PrimaryLanguage)
: $"{GetLanguageId(unit.PrimaryLanguage)}/{GetLanguageId(unit.SecondaryLanguage)}";
string upgradeMarker = CanUpgradeUnit(unit) ? " *" : string.Empty;
string listing = LsText($"{"drwxr-xr-x",-12}{"player",-8}{$"{GetDistroStars(unit)}★",-6}{$"{version}/{GachaTuning.MaxVersion}",-6}{languages,-20}{unit.Id}/{upgradeMarker}");
Button row = new();
row.AddToClassList("collection-row");
row.AddToClassList("unit-overview-row");
row.AddToClassList(RarityPresentation.ForStars(GetDistroStars(unit)).ClassName);
VisualElement top = new();
top.AddToClassList("unit-overview-top");
Label line = new(listing);
line.AddToClassList("unit-ls-line");
line.style.whiteSpace = WhiteSpace.NoWrap;
line.style.unityTextAlign = TextAnchor.MiddleLeft;
line.style.color = new StyleColor(unit.AccentColor);
row.Add(line);
Label name = new(DistroPresentation.DisplayName(unit));
name.AddToClassList("collection-row-name");
name.style.color = new StyleColor(unit.AccentColor);
top.Add(name);
RarityStyle rarity = RarityPresentation.ForStars(GetDistroStars(unit));
Label rarityLabel = new(rarity.Badge);
rarityLabel.AddToClassList("unit-overview-rarity");
rarityLabel.AddToClassList(rarity.ClassName);
top.Add(rarityLabel);
if (CanUpgradeUnit(unit))
{
Label upgrade = new("upgrade");
upgrade.AddToClassList("unit-overview-upgrade");
top.Add(upgrade);
}
row.Add(top);
VisualElement meta = new();
meta.AddToClassList("unit-overview-meta");
AddLanguageTag(meta, unit.PrimaryLanguage);
AddLanguageTag(meta, unit.SecondaryLanguage);
row.Add(meta);
int version = GetUnitVersion(unit);
Label release = new($"{DistroPresentation.DisplayName(unit)} {DistroVersionCatalog.GetReleaseLabel(unit.Id, version)} · v{version}/{GachaTuning.MaxVersion}");
release.AddToClassList("unit-overview-release");
row.Add(release);
VisualElement slots = new();
slots.AddToClassList("unit-overview-slots");
AddPackageSlotDot(slots, unit, PackageSlot.Kernel);
AddPackageSlotDot(slots, unit, PackageSlot.Runtime);
AddPackageSlotDot(slots, unit, PackageSlot.Daemon);
row.Add(slots);
string system = UnitPackageName(unit, PackageSlot.Kernel);
string tools = UnitPackageName(unit, PackageSlot.Runtime);
string services = UnitPackageName(unit, PackageSlot.Daemon);
Label packages = new($"└─ loadout system={system} tools={tools} services={services}");
packages.AddToClassList("unit-loadout-line");
row.Add(packages);
row.tooltip = $"System: {system}\nTools: {tools}\nServices: {services}";
return row;
}
private string UnitPackageName(DistroDefinition unit, PackageSlot slot)
{
PackageDefinition package = _packageLoadout == null || unit == null
? null
: _packageLoadout.GetEquippedPackage(unit.Id, slot);
return package == null ? "-" : PackageName(package);
}
private static string LsText(string value)
{
// UI Toolkit may wrap ordinary alignment spaces inside Button content.
// Non-breaking spaces preserve shell-style fixed columns at narrow widths.
return (value ?? string.Empty).Replace(' ', '\u00A0');
}
private void AddLanguageTag(VisualElement target, Language language)
{
Label tag = new(language.ToString());
@@ -805,7 +812,7 @@ namespace KernelPanic.UI
_unitDetailReturnsToOverview = returnToOverview;
_mode = CollectionMode.UnitDetail;
CurrentTitle = $"$ cat ~/units/{unit.Id}";
CurrentTitle = $"$ cat /etc/distros/{unit.Id}.conf";
CurrentHint = GetUnitDetailHint();
RenderUnitDetail(unit);
if (notify)
@@ -824,7 +831,7 @@ namespace KernelPanic.UI
TerminalTheme.PreserveFocus(_detail);
_detail.Clear();
_detailScroll.scrollOffset = Vector2.zero;
CurrentTitle = $"$ cat ~/units/{unit.Id}";
CurrentTitle = $"$ cat /etc/distros/{unit.Id}.conf";
CurrentHint = GetUnitDetailHint();
string identity = unit.Id + ":" + GetUnitVersion(unit);
@@ -854,16 +861,13 @@ namespace KernelPanic.UI
VisualElement nameBlock = new();
nameBlock.AddToClassList("unit-detail-header-copy");
int version = GetUnitVersion(unit);
Label name = new($"{DistroPresentation.DisplayName(unit)} {DistroVersionCatalog.GetReleaseLabel(unit.Id, version)} · v{version}/{GachaTuning.MaxVersion}");
Label path = new($"/etc/distros/{unit.Id}.conf");
path.AddToClassList("unit-config-path");
nameBlock.Add(path);
Label name = new($"# {DistroPresentation.DisplayName(unit)} · {DistroVersionCatalog.GetReleaseLabel(unit.Id, version)} · v{version}/{GachaTuning.MaxVersion}");
name.AddToClassList("collection-detail-name");
name.style.color = new StyleColor(unit.AccentColor);
nameBlock.Add(name);
VisualElement languages = new();
languages.AddToClassList("unit-overview-meta");
AddLanguageTag(languages, unit.PrimaryLanguage);
AddLanguageTag(languages, unit.SecondaryLanguage);
nameBlock.Add(languages);
header.Add(nameBlock);
RarityStyle rarity = RarityPresentation.ForStars(GetDistroStars(unit));
@@ -907,36 +911,88 @@ namespace KernelPanic.UI
private void AddUnitOverviewTab(VisualElement target, DistroDefinition unit)
{
VisualElement identity = TerminalLayout.Section("identity",
sectionClass: "unit-info-section unit-identity-section", headingClass: "detail-section-title");
identity.Add(BuildDetailLine("lang", DistroPresentation.FormatLanguages(unit)));
VisualElement identity = new();
identity.AddToClassList("unit-info-section");
identity.AddToClassList("unit-identity-section");
identity.Add(OverviewSectionLabel("[host]"));
Label description = TerminalLayout.BodyText(string.IsNullOrWhiteSpace(unit.Description) ? "--" : unit.Description,
className: "collection-detail-description");
VisualElement facts = new();
facts.AddToClassList("unit-overview-facts");
facts.Add(OverviewFact("languages", DistroPresentation.FormatLanguages(unit), "UnitOverview_languages", true));
facts.Add(OverviewFact("uptime", unit.BaseUptime.ToString(), "UnitOverview_uptime"));
facts.Add(OverviewFact("ram", unit.BaseRam.ToString(), "UnitOverview_ram"));
facts.Add(OverviewFact("cycles", unit.BaseCyclesPerTurn.ToString(), "UnitOverview_cycles"));
identity.Add(facts);
Label description = new(string.IsNullOrWhiteSpace(unit.Description) ? "--" : unit.Description)
{
name = "UnitOverview_description"
};
description.AddToClassList("unit-overview-description");
identity.Add(description);
target.Add(identity);
AddPassiveDetails(target, unit);
VisualElement readout = new();
readout.AddToClassList("collection-detail-readout");
VisualElement passive = new();
passive.AddToClassList("unit-info-section");
passive.AddToClassList("unit-passive-section");
VisualElement passiveHeading = new();
passiveHeading.AddToClassList("unit-passive-heading");
passiveHeading.Add(OverviewSectionLabel("[passive]"));
Label passiveName = new(unit.Passive == null ? "--" : unit.Passive.Name)
{
name = "UnitPassive_name"
};
passiveName.AddToClassList("unit-passive-name");
passiveHeading.Add(passiveName);
passive.Add(passiveHeading);
Label artLabel = new();
DistroArtPresenter.ConfigureArtLabel(artLabel, _monospaceFont);
AsciiArtFitter artFitter = new(artLabel, _monospaceFont);
VisualElement artPlaceholder = DistroArtPresenter.CreatePlaceholder();
artFitter.SetArt(DistroArtPresenter.Render(artLabel, artPlaceholder, unit));
readout.Add(artPlaceholder);
readout.Add(artLabel);
Label rules = new(GetPassiveRules(unit))
{
name = "UnitPassive_rules"
};
rules.AddToClassList("unit-passive-rules");
passive.Add(rules);
if (unit.Passive != null && !string.IsNullOrWhiteSpace(unit.Passive.FlavorText))
{
Label flavor = new("# " + unit.Passive.FlavorText)
{
name = "UnitPassive_flavor"
};
flavor.AddToClassList("unit-passive-flavor");
passive.Add(flavor);
}
target.Add(passive);
}
VisualElement details = new();
details.AddToClassList("collection-detail-values");
details.Add(BuildDetailLine("lang", DistroPresentation.FormatLanguages(unit)));
details.Add(BuildDetailLine("uptime", unit.BaseUptime.ToString()));
details.Add(BuildDetailLine("ram", unit.BaseRam.ToString()));
details.Add(BuildDetailLine("cycles", unit.BaseCyclesPerTurn.ToString()));
private static Label OverviewSectionLabel(string text)
{
Label label = new(text);
label.AddToClassList("unit-overview-section-label");
return label;
}
readout.Add(details);
target.Add(readout);
private static VisualElement OverviewFact(string key, string value, string name, bool wide = false)
{
VisualElement fact = new() { name = name };
fact.AddToClassList("unit-overview-fact");
if (wide) fact.AddToClassList("unit-overview-fact-wide");
Label keyLabel = new(key);
keyLabel.AddToClassList("unit-overview-fact-key");
Label valueLabel = new(value ?? "--");
valueLabel.AddToClassList("unit-overview-fact-value");
fact.Add(keyLabel);
fact.Add(valueLabel);
return fact;
}
private static string GetPassiveRules(DistroDefinition unit)
{
if (unit?.Passive == null) return "--";
if (unit.Id != "nixos") return unit.Passive.RulesText;
var policy = new NixGovernorState();
policy.BeginWave(1);
return "governor modes: " + string.Join("; ", Enum.GetValues(typeof(NixGovernor)).Cast<NixGovernor>().Select(governor =>
$"{governor.ToString().ToLowerInvariant()} {policy.DamageFor(governor)-100:+0;-0;0}% damage / {policy.ShieldFor(governor)-100:+0;-0;0}% shield"));
}
private void AddUnitUpgradeTab(VisualElement target, DistroDefinition unit)
@@ -1268,6 +1324,7 @@ namespace KernelPanic.UI
}, TrickleDown.TrickleDown);
_packageEquipDialog = new VisualElement();
_packageEquipDialog.AddToClassList("package-equip-dialog");
_packageEquipDialog.AddToClassList("terminal-pane");
_packageEquipOverlay.Add(_packageEquipDialog);
_root.Add(_packageEquipOverlay);
}
@@ -1312,7 +1369,8 @@ namespace KernelPanic.UI
VisualElement header = new();
header.AddToClassList("package-equip-header");
Label title = new($"equip: {_equipWindowSlot.DisplayName().ToLowerInvariant()} - {DistroPresentation.DisplayName(_equipWindowUnit)}");
header.AddToClassList("terminal-pane-titlebar");
Label title = new($"[ apt install --configure {_equipWindowSlot.DisplayName().ToLowerInvariant()} :: {DistroPresentation.DisplayName(_equipWindowUnit)} ]");
title.AddToClassList("collection-detail-name");
title.style.color = new StyleColor(_equipWindowUnit.AccentColor);
header.Add(title);
@@ -28,6 +28,10 @@ namespace KernelPanic.UI
VisualElement offers = new();
offers.AddToClassList("repository-offers");
VisualElement packageOperations = new();
packageOperations.AddToClassList("repository-package-operations");
packageOperations.Add(TerminalLayout.Heading("[ package operations ]", className: "repository-section-label"));
packageOperations.Add(TerminalLayout.BodyText("$ apt-cache search --upgradeable", className: "repository-command-heading"));
if (_runManager.RepositoryOffers.Count == 0)
{
offers.Add(EmptyState("repository clean: no offers left this visit"));
@@ -41,42 +45,53 @@ namespace KernelPanic.UI
}
body.Add(DeckAnalysisView.Build(_runManager.RunDeck));
body.Add(offers);
body.Add(RemoveCardBlock());
packageOperations.Add(offers);
packageOperations.Add(RemoveCardBlock());
body.Add(packageOperations);
repo.Add(body);
VisualElement footer = new();
footer.AddToClassList("repository-footer");
footer.AddToClassList("screen-frame-footer");
VisualElement packageControls = new();
packageControls.AddToClassList("repository-footer-group");
packageControls.AddToClassList("repository-package-controls");
packageControls.Add(TerminalLayout.BodyText("package cache", className: "repository-footer-label"));
Button reroll = new(() => _runManager.RerollRepositoryOffers(cardDatabase, languageDeckDatabase))
{
text = $"apt update {_runManager.RerollCost} bits"
text = $"$ apt update {_runManager.RerollCost} bits"
};
reroll.AddToClassList("primary-action");
reroll.AddToClassList("secondary-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);
packageControls.Add(reroll);
footer.Add(packageControls);
Button leave = new(() =>
{
if (_runManager.Journey.campaign) SetRouteSelectionOpen(true);
else _combatManager.ContinueToNextWave();
}) { name = "BootNextWaveButton", text = "> boot next-wave" };
}) { name = "BootNextWaveButton", text = "$ boot --next-wave" };
leave.AddToClassList("primary-action");
leave.AddToClassList("repository-leave-action");
leave.AddToClassList("repository-primary-command");
leave.AddToClassList("repository-recommended-action");
leave.SetEnabled(!_runManager.IsSuspended);
VisualElement leaveBlock = new();
leaveBlock.AddToClassList("repository-leave-block");
leaveBlock.AddToClassList("repository-footer-group");
leaveBlock.Add(TerminalLayout.BodyText("recommended next action", className: "repository-footer-label repository-recommended-label"));
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");
var suspend = new Button(SaveAndExitRun) { name = "SaveAndExitRunButton", text = "$ shutdown --save" };
suspend.AddToClassList("secondary-action");
suspend.AddToClassList("repository-leave-action");
suspend.AddToClassList("repository-save-action");
suspend.SetEnabled(!_runManager.IsSuspended);
leaveBlock.Add(suspend);
if (!string.IsNullOrEmpty(_checkpointError))
@@ -300,7 +315,7 @@ namespace KernelPanic.UI
Button buy = new(() => _runManager.BuyOffer(offer, _combatManager.PlayerState))
{
text = offer.Sold ? "installed" : OfferActionText(offer.Kind)
text = offer.Sold ? "# installed" : "$ " + OfferActionText(offer.Kind)
};
buy.tooltip = OfferCommandText(offer);
buy.AddToClassList("repository-action");
@@ -317,6 +332,7 @@ namespace KernelPanic.UI
VisualElement card = CardFaceView(preview);
card.AddToClassList("repository-card-preview");
content.Add(card);
AddRepositoryRulesToggle(content, card, preview);
if (offer.CardDefinition != null && offer.CardDefinition.IsRunOnly)
{
@@ -335,6 +351,7 @@ namespace KernelPanic.UI
VisualElement target = CardFaceView(offer.TargetCard);
target.AddToClassList("repository-upgrade-card");
content.Add(target);
AddRepositoryRulesToggle(content, target, offer.TargetCard);
}
VisualElement delta = new();
@@ -352,6 +369,31 @@ namespace KernelPanic.UI
return content;
}
private static void AddRepositoryRulesToggle(VisualElement content, VisualElement card, CardInstance instance)
{
string rules = instance?.Definition == null ? "" : CardEffectFactory.GetRulesText(instance);
// Short manifests already scan well. Long cards keep their first authoritative
// sentence visible and put restrictions/edge cases behind an explicit reveal.
if (rules.Length < 140 || card.Q<Label>(className: "software-conditions") == null) return;
card.AddToClassList("repository-card-collapsible");
Button toggle = null;
toggle = new Button(() =>
{
bool expanded = !card.ClassListContains("repository-card-expanded");
card.EnableInClassList("repository-card-expanded", expanded);
toggle.text = expanded ? "▾ hide full rules" : "▸ show full rules";
toggle.EnableInClassList("expanded", expanded);
})
{
name = "RepositoryRulesToggle_" + instance.Definition.Id,
text = "▸ show full rules",
tooltip = "Show or hide the complete card manifest."
};
toggle.AddToClassList("repository-rules-toggle");
content.Add(toggle);
}
private VisualElement StatOfferContent(RepositoryOffer offer)
{
VisualElement content = new();
@@ -42,9 +42,12 @@ namespace KernelPanic.UI
var config = _runManager.CurrentConfig;
VisualElement reportHeader = new();
reportHeader.AddToClassList("death-report-header");
reportHeader.Add(SoftwareCardView.Text("RUN REPORT", "death-eyebrow"));
reportHeader.Add(SoftwareCardView.Text("$ cat /var/log/run-report", "death-eyebrow"));
reportHeader.Add(SoftwareCardView.Text($"seed {config?.RunSeed ?? 0}", "death-seed"));
content.Add(reportHeader);
string exitCode = _combatManager.RunCompleted ? "0" : _runEndedBySurrender ? "130" : "137";
string exitState = _combatManager.RunCompleted ? "[ OK ] objective completed" : _runEndedBySurrender ? "[ WARN ] interrupted by operator" : "[ PANIC ] host terminated";
content.Add(SoftwareCardView.Text($"{exitState} · process exited with code {exitCode}", "death-exit-code"));
content.Add(OverlayTitle(_combatManager.RunCompleted ? "KERNEL SECURED" : _runEndedBySurrender ? "SYSTEM HALTED" : "KERNEL PANIC"));
var report = GetRunHistoryEntry();
@@ -86,10 +89,11 @@ namespace KernelPanic.UI
rewards.AddToClassList("death-rewards");
rewards.Add(RewardReadout("#", _runManager.AccruedBandwidth, "bandwidth", false));
rewards.Add(RewardReadout("*", _runManager.AccruedEntropy, "entropy", _runManager.AccruedEntropy <= 0));
rewards.Add(RewardReadout("+", _runManager.AccruedCommits, "commits", _runManager.AccruedCommits <= 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" };
Button returnButton = new(() => SceneLoader.LoadMainMenu(_root)) { text = "$ cd ~ && clear # return to menu" };
returnButton.AddToClassList("primary-action");
returnButton.AddToClassList("death-return-action");
if (!string.IsNullOrEmpty(_saveError))
@@ -134,6 +138,7 @@ namespace KernelPanic.UI
data.bandwidthBalance = Math.Max(0, data.bandwidthBalance) + _runManager.AccruedBandwidth;
LanguageUnlock.RecordCampaignClear(data, _runManager.CurrentConfig, _runManager.Journey, _runManager.WavesCleared);
data.entropyBalance = Math.Max(0, data.entropyBalance) + _runManager.AccruedEntropy;
data.commitsBalance = Math.Max(0, data.commitsBalance) + _runManager.AccruedCommits;
data.RecordRunStats(_runManager.CurrentConfig?.Distro?.Id,
_combatManager.RunCompleted ? _runManager.WavesCleared : _runManager.CurrentWaveNumber);
if (_combatManager.RunFinished) RunHistory.Record(data.recentRuns, GetRunHistoryEntry());
+267 -94
View File
@@ -41,6 +41,11 @@ namespace KernelPanic.UI
private VisualElement _statusBar;
private Label _waveLabel;
private Label _phaseLabel;
private VisualElement _commandPrompt;
private Label _commandPromptUser;
private Label _commandPromptCommand;
private Label _commandPromptArgs;
private Label _commandPromptResult;
private Label _entropyLabel;
private Label _bitsLabel;
private Label _bandwidthLabel;
@@ -51,15 +56,16 @@ namespace KernelPanic.UI
private VisualElement _lazyStackPile;
private VisualElement _tokenArea;
private VisualElement _enemyRow;
private VisualElement _processTableHeader;
private VisualElement _combatPaneTabs;
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 VisualElement _journalActionResults;
private Foldout _journal;
private Button _endTurnButton;
private Button _prefetchButton;
@@ -69,15 +75,17 @@ namespace KernelPanic.UI
private ScrollView _journalScroll;
private ExecutionTrackView _queueView;
private ExecutionTrackView _stackView;
private ExecutionPreviewView _executionPreview;
private TurnResolutionView _turnResolution;
private CombatExecutionTrace _executionTrace;
private Label _encounterBrief;
private float _journalStartedAt;
private readonly Dictionary<EnemyInstance, Button> _enemyCards = new();
private readonly Dictionary<EnemyInstance, int> _enemyPids = new();
private int _nextEnemyPid = 1042;
private string _activeCombatPane = "processes";
private readonly HashSet<EnemyInstance> _restartingEnemies = new();
private readonly HashSet<IVisualElementScheduledItem> _scheduledFeedback = new();
private readonly Queue<string> _recentLog = new();
private readonly HashSet<ExecutionAction> _expandedJournalActions = new();
private readonly Dictionary<CardInstance, VisualElement> _retainedHandCards = new();
private int _executionSequence;
private Button _surrenderButton;
@@ -158,9 +166,11 @@ namespace KernelPanic.UI
{
_campaignUnlocksSaved = false;
_campaignUnlockNotice = _campaignUnlockError = null;
if (_executionTrace != null) _executionTrace.Changed -= RefreshJournalActionResults;
_executionTrace?.Dispose();
_executionTrace = new CombatExecutionTrace(_combatManager);
_turnResolution?.Bind(_executionTrace);
_executionTrace.Changed += RefreshJournalActionResults;
RefreshJournalActionResults();
_runTelemetry?.Dispose();
_runTelemetry = new CombatRunTelemetry(() => _combatManager.PlayerState, DescribeDamageSource)
{
@@ -308,8 +318,7 @@ namespace KernelPanic.UI
_feedbackLayer?.Clear();
_runTelemetry?.Dispose();
_runTelemetry = null;
_turnResolution?.Dispose();
_executionPreview?.Close();
if (_executionTrace != null) _executionTrace.Changed -= RefreshJournalActionResults;
_executionTrace?.Dispose();
_executionTrace = null;
}
@@ -325,17 +334,6 @@ namespace KernelPanic.UI
if (evt.keyCode == KeyCode.E && _tutorial.Guide.CanEndTurn) _combatManager.EndPlayerTurn();
evt.StopPropagation(); return;
}
if (_turnResolution?.IsOpen == true)
{
if (evt.keyCode == KeyCode.Escape) _turnResolution.Close();
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();
@@ -465,6 +463,8 @@ namespace KernelPanic.UI
{
_root.Clear();
_lastCombatantFeedbackRects.Clear();
_enemyPids.Clear();
_nextEnemyPid = 1042;
_heldDeathUptime.Clear();
_deathBeatStartedCombatants.Clear();
_visuallyRemovedCombatants.Clear();
@@ -475,6 +475,11 @@ namespace KernelPanic.UI
_statusBar = BuildStatusBar();
_root.Add(_statusBar);
_commandPrompt = BuildCombatCommandPrompt();
_statusBar.Add(_commandPrompt);
_combatPaneTabs = BuildCombatPaneTabs();
_root.Add(_combatPaneTabs);
var workspace = new ScrollView(ScrollViewMode.Vertical);
workspace.AddToClassList("combat-workspace");
@@ -483,50 +488,37 @@ namespace KernelPanic.UI
workspace.Add(_firstBattleGuide.Element);
_encounterBrief = TerminalLayout.BodyText("", "EncounterBrief");
workspace.Add(_encounterBrief);
_executionPreview = new ExecutionPreviewView();
_turnResolution = new TurnResolutionView();
VisualElement main = new();
main.AddToClassList("main-layout");
workspace.Add(main);
_playerPanel = CreatePanel("host", "distro", 0);
_playerPanel = CreatePanel("[1] host", "distro", 0);
_playerPanel.AddToClassList("player-panel");
main.Add(_playerPanel);
VisualElement enemiesPanel = CreatePanel("process table", "select a process to target", 0);
VisualElement enemiesPanel = CreatePanel("[2] /proc/enemies", "select a process to target", 0);
enemiesPanel.AddToClassList("process-panel");
main.Add(enemiesPanel);
_targetHint = SoftwareCardView.Text("", "target-hint");
enemiesPanel.Add(_targetHint);
_processTableHeader = BuildProcessTableHeader();
enemiesPanel.Add(_processTableHeader);
_enemyRow = new();
_enemyRow.AddToClassList("enemy-row");
enemiesPanel.Add(_enemyRow);
var packages = new VisualElement { name = "CombatPackages" };
packages.AddToClassList("combat-packages");
packages.Add(TerminalLayout.Heading("installed packages", className: "package-loadout-title"));
_packageReadinessStrip = new VisualElement { name = "PackageReadiness" };
_packageReadinessStrip.AddToClassList("package-readiness-strip");
_packageReadinessChips.Clear();
packages.Add(_packageReadinessStrip);
_packageActivationLabel = SoftwareCardView.Text("", "package-activation");
_packageActivationLabel.name = "PackageActivation";
_packageActivationLabel.style.display = DisplayStyle.None;
packages.Add(_packageActivationLabel);
_playerPanel.Add(packages);
_playerPanel.Add(_packageActivationLabel);
VisualElement scheduler = new();
VisualElement scheduler = new() { name = "SchedulerPane" };
scheduler.AddToClassList("scheduler");
VisualElement schedulerHeader = PanelHeader("execution scheduler", "");
VisualElement schedulerHeader = PanelHeader("[3] scheduler", "");
_schedulerActivity = schedulerHeader.Q<Label>(className: "panel-subtitle");
_schedulerActivity.AddToClassList("scheduler-activity");
_schedulerActivity.text = "No operations dispatched.";
scheduler.Add(schedulerHeader);
var preview = new Button(() => { _turnResolution?.Close(); _executionPreview?.Open(_root); })
{ name = "OpenExecutionPreview", text = "preview turn" };
preview.AddToClassList("combat-status-action");
preview.tooltip = "Inspect the execution order and estimates before ending your turn.";
schedulerHeader.Add(preview);
BuildGoScheduler(scheduler);
_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");
@@ -544,7 +536,7 @@ namespace KernelPanic.UI
VisualElement bottom = new();
bottom.AddToClassList("bottom-layout");
_root.Add(bottom);
VisualElement handPanel = CreatePanel("executable buffer", "Tab / Enter to select · E end turn", 0);
VisualElement handPanel = CreatePanel("[4] ~/hand", "Tab / Enter to select · E end turn", 0);
handPanel.AddToClassList("hand-panel");
bottom.Add(handPanel);
_handScroll = new ScrollView(ScrollViewMode.VerticalAndHorizontal);
@@ -574,7 +566,7 @@ namespace KernelPanic.UI
});
}, TrickleDown.TrickleDown);
VisualElement commandPanel = CreatePanel("dispatch", "turn controls", 0);
VisualElement commandPanel = CreatePanel("[5] dispatch", "turn controls", 0);
commandPanel.AddToClassList("turn-panel");
bottom.Add(commandPanel);
_turnResourceGrid = new();
@@ -615,22 +607,30 @@ namespace KernelPanic.UI
_surrenderCancelButton.AddToClassList("hidden");
commandPanel.Add(_surrenderCancelButton);
var log = new Foldout { text = "journal / recent combat events", value = false };
// The latest event remains in the foldout title; open the full journal only
// when its history is useful so it does not permanently consume the playfield.
var log = new Foldout { text = "[6] journalctl -f", value = false };
_journal = log;
log.AddToClassList("combat-journal");
_journalEntries = new VisualElement();
_journalActionResults = new VisualElement { name = "JournalActionResults" };
_journalActionResults.AddToClassList("journal-action-results");
var logScroll = new ScrollView(ScrollViewMode.Vertical);
_journalScroll = logScroll;
_journalStartedAt = Time.realtimeSinceStartup;
logScroll.AddToClassList("journal-scroll");
logScroll.Add(_journalEntries);
logScroll.Add(_journalActionResults);
log.Add(logScroll);
log.RegisterValueChangedCallback(evt =>
{
if (!evt.newValue) return;
ScheduleFeedback(() =>
{
if (_journal.value && _journalEntries.childCount > 0)
if (!_journal.value) return;
if (_journalActionResults.childCount > 0)
_journalScroll.ScrollTo(_journalActionResults.ElementAt(_journalActionResults.childCount - 1));
else if (_journalEntries.childCount > 0)
_journalScroll.ScrollTo(_journalEntries.ElementAt(_journalEntries.childCount - 1));
}, 20);
});
@@ -651,6 +651,79 @@ namespace KernelPanic.UI
TerminalTheme.ConstrainModalFocus(_overlay);
_overlay.style.display = DisplayStyle.None;
_root.Add(_overlay);
SelectCombatPane(_activeCombatPane, false);
}
private VisualElement BuildCombatCommandPrompt()
{
VisualElement prompt = new() { name = "CombatCommandPrompt" };
prompt.AddToClassList("combat-command-prompt");
_commandPromptUser = SoftwareCardView.Text("player@kernel:~$", "syntax-prompt");
_commandPromptCommand = SoftwareCardView.Text("idle", "syntax-command");
_commandPromptArgs = SoftwareCardView.Text("", "syntax-argument");
_commandPromptResult = SoftwareCardView.Text("", "syntax-output");
prompt.Add(_commandPromptUser);
prompt.Add(_commandPromptCommand);
prompt.Add(_commandPromptArgs);
prompt.Add(_commandPromptResult);
return prompt;
}
private VisualElement BuildCombatPaneTabs()
{
VisualElement tabs = new() { name = "CombatPaneTabs" };
tabs.AddToClassList("combat-pane-tabs");
AddCombatPaneTab(tabs, "processes", "[1] processes");
AddCombatPaneTab(tabs, "scheduler", "[2] scheduler");
AddCombatPaneTab(tabs, "hand", "[3] hand");
AddCombatPaneTab(tabs, "log", "[4] log");
return tabs;
}
private void AddCombatPaneTab(VisualElement tabs, string pane, string text)
{
Button button = new(() => SelectCombatPane(pane))
{
name = "CombatPane_" + pane,
text = text,
tooltip = $"Show the {pane} terminal pane."
};
button.AddToClassList("combat-pane-tab");
button.userData = pane;
tabs.Add(button);
}
private void SelectCombatPane(string pane, bool engage = true)
{
_activeCombatPane = pane is "scheduler" or "hand" or "log" ? pane : "processes";
if (engage) _root.AddToClassList("combat-pane-filtered");
foreach (string candidate in new[] { "processes", "scheduler", "hand", "log" })
{
_root.EnableInClassList("combat-pane-" + candidate, candidate == _activeCombatPane);
_combatPaneTabs?.Q<Button>("CombatPane_" + candidate)?.EnableInClassList("selected", candidate == _activeCombatPane);
}
if (_activeCombatPane == "log" && _journal != null) _journal.value = true;
}
private static VisualElement BuildProcessTableHeader()
{
VisualElement row = new() { name = "ProcessTableHeader" };
row.AddToClassList("process-table-header");
row.Add(ProcessColumn("PID", "process-col-pid"));
row.Add(ProcessColumn("STATE", "process-col-state"));
row.Add(ProcessColumn("PROCESS", "process-col-name"));
row.Add(ProcessColumn("UPTIME", "process-col-uptime"));
row.Add(ProcessColumn("SHIELD", "process-col-shield"));
row.Add(ProcessColumn("NEXT", "process-col-intent"));
row.Add(ProcessColumn("RESULT", "process-col-result"));
return row;
}
private static Label ProcessColumn(string text, string className)
{
Label label = SoftwareCardView.Text(text, "process-column");
label.AddToClassList(className);
return label;
}
private VisualElement BuildStatusBar()
@@ -672,10 +745,6 @@ namespace KernelPanic.UI
_seedLabel = new("--");
_seedLabel.AddToClassList("seed-value");
bar.Add(_seedLabel);
var results = new Button(() => { _executionPreview?.Close(); _turnResolution?.Open(_root); }) { name = "OpenTurnResolution", text = "results" };
results.AddToClassList("combat-status-action");
results.tooltip = "Inspect resolved actions and damage calculations.";
bar.Add(results);
var combatSave = new Button(SaveAndExitRun) { name = "SaveCombatButton", text = "save & exit" };
combatSave.AddToClassList("combat-status-action");
combatSave.tooltip = "Save this planning state, including queued cards and persistent work. Finish selections first.";
@@ -743,11 +812,8 @@ namespace KernelPanic.UI
RefreshEnemies();
RefreshHand();
RefreshTurnPanel();
RefreshPackageReadiness();
RefreshCommandPrompt();
RefreshOverlay();
_executionPreview?.Refresh(_combatManager);
_root.Q<Button>("OpenExecutionPreview")?.SetEnabled(!_combatManager.RunFinished && !_combatManager.AwaitingWaveContinue);
if (_combatManager.RunFinished || _combatManager.AwaitingWaveContinue) _turnResolution?.Close();
if (_encounterBrief != null)
{
// Encounter advice belongs to onboarding, not every battle's workspace.
@@ -757,38 +823,39 @@ namespace KernelPanic.UI
_firstBattleGuide?.Refresh(_combatManager.AwaitingWaveContinue, _combatManager.RunFinished);
}
private void RefreshPackageReadiness()
private void RefreshCommandPrompt()
{
if (_packageReadinessStrip == null) return;
var readouts = _combatManager.GetPackageReadouts();
var currentIds = new HashSet<string>();
foreach (var readout in readouts)
if (_commandPrompt == null) return;
bool targeting = _combatManager.PendingTargetCard != null;
bool resolving = _combatManager.CurrentPhase != TurnPhase.Execute;
_root.EnableInClassList("combat-awaiting-target", targeting);
_root.EnableInClassList("combat-resolving", resolving && !_combatManager.AwaitingWaveContinue && !_combatManager.RunFinished);
_root.EnableInClassList("combat-planning", !targeting && !resolving);
string host = _runManager?.CurrentConfig?.Distro?.Id ?? "kernel";
_commandPromptUser.text = $"player@{host}:~$";
if (_combatManager.RunFinished)
SetCommandPrompt("cat", "/var/log/run-report", "# process exited; journal retained");
else if (_combatManager.AwaitingWaveContinue)
SetCommandPrompt("cd", "~/repository", "[OK] wave complete");
else if (targeting)
{
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));
var copy = new VisualElement();
copy.AddToClassList("package-readiness-copy");
copy.Add(SoftwareCardView.Text(readout.Definition.DisplayName, "package-readiness-name"));
copy.Add(SoftwareCardView.Text("", "package-readiness-state"));
chip.Add(copy);
_packageReadinessChips[id] = chip;
_packageReadinessStrip.Add(chip);
}
chip.Q<Label>(className: "package-readiness-state").text = readout.State;
chip.tooltip = readout.Definition.DisplayName + " / " + readout.State + "\n" + readout.Details;
CardInstance pending = _combatManager.PendingTargetCard;
CardPreview preview = CardPreviewService.Build(_combatManager, pending);
SetCommandPrompt("exec", $"{pending.Definition.Id} --target <pid>",
$"# {preview.Summary} · {GetDisplayCardCost(pending)}c");
}
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;
else if (_combatManager.CurrentPhase == TurnPhase.Execute)
SetCommandPrompt("exec", "<card> [--target pid]", "# Tab select · E dispatch");
else
SetCommandPrompt("wait", $"--phase {PhaseText(_combatManager.CurrentPhase)}", _schedulerActivity?.text ?? "# scheduler resolving");
}
private void SetCommandPrompt(string command, string arguments, string result)
{
_commandPromptCommand.text = command;
_commandPromptArgs.text = arguments;
_commandPromptResult.text = result;
}
private void HandlePackageActivated(PackageActivation activation)
@@ -850,7 +917,6 @@ namespace KernelPanic.UI
private void RefreshPlayer()
{
var uptimeMeter = _playerPanel.Q(className: "meter-block");
var packages = _packageReadinessStrip?.parent;
_playerPanel.Clear();
_combatantElements.Remove(_combatManager.PlayerState);
_combatantElements[_combatManager.PlayerState] = _playerPanel;
@@ -886,6 +952,7 @@ namespace KernelPanic.UI
}
_playerPanel.Add(StatusBlock(state, true));
_playerPanel.Add(_packageActivationLabel);
RefreshGovernorPanel();
var compilation = _combatManager.Compilation;
@@ -924,7 +991,6 @@ namespace KernelPanic.UI
{
_playerPanel.Add(ArchBtwCounter(state.ArchBtwStacks));
}
if (packages != null) _playerPanel.Add(packages);
}
private bool IsDistro(string id)
@@ -982,6 +1048,7 @@ namespace KernelPanic.UI
{
_enemyCards[enemy].RemoveFromHierarchy();
_enemyCards.Remove(enemy);
_enemyPids.Remove(enemy);
_combatantElements.Remove(enemy.State);
_restartingEnemies.Remove(enemy);
_previousUptime.Remove(enemy.State);
@@ -1010,6 +1077,7 @@ namespace KernelPanic.UI
if (!_enemyCards.TryGetValue(enemy, out Button card))
{
_enemyPids[enemy] = _nextEnemyPid++;
card = new Button(() =>
{
// Resolve the current index: an earlier process may have exited.
@@ -1017,18 +1085,39 @@ namespace KernelPanic.UI
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));
VisualElement primary = new();
primary.AddToClassList("process-row-primary");
Label pid = SoftwareCardView.Text("", "process-pid");
pid.AddToClassList("process-col-pid");
primary.Add(pid);
Label state = SoftwareCardView.Text("", "process-state");
state.AddToClassList("process-col-state");
primary.Add(state);
Label name = SoftwareCardView.Text("", "enemy-name");
name.AddToClassList("process-col-name");
primary.Add(name);
VisualElement uptime = MeterBlock("uptime", enemy.CurrentUptime, enemy.MaxUptime, MeterTone.Uptime);
uptime.AddToClassList("process-col-uptime");
primary.Add(uptime);
Label shield = SoftwareCardView.Text("", "enemy-shield");
shield.AddToClassList("process-col-shield");
primary.Add(shield);
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" });
intent.AddToClassList("process-col-intent");
primary.Add(intent);
Label result = SoftwareCardView.Text("", "process-result");
result.name = "ProcessResult";
result.AddToClassList("process-col-result");
primary.Add(result);
card.Add(primary);
VisualElement detail = new();
detail.AddToClassList("process-row-detail");
detail.Add(new VisualElement { name = "ProcessSignals" });
var statusSlot = new VisualElement { name = "ProcessStatuses" };
statusSlot.AddToClassList("process-statuses");
card.Add(statusSlot);
detail.Add(statusSlot);
card.Add(detail);
_enemyCards.Add(enemy, card);
_enemyRow.Add(card);
}
@@ -1046,17 +1135,17 @@ namespace KernelPanic.UI
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.Q<Label>(className: "process-pid").text = _enemyPids[enemy].ToString();
card.Q<Label>(className: "process-state").text = EnemyProcessPresentation.Lifecycle(enemy).ToUpperInvariant();
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.Q<Label>(className: "enemy-name").text = $"{EnemyProcessPresentation.Symbol(enemy.ArchetypeId)} {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)
@@ -1105,6 +1194,8 @@ namespace KernelPanic.UI
statuses.Clear();
statuses.EnableInClassList("hidden", enemy.State.Statuses.Count == 0);
if (enemy.State.Statuses.Count > 0) statuses.Add(StatusPipRow(enemy.State));
card.Q(className: "process-row-detail").EnableInClassList("process-row-detail-empty",
!enemy.HasSpecialSignal && enemy.State.Statuses.Count == 0);
if (ReferenceEquals(focusedEnemy, enemy)) card.Focus();
TrackCombatantFeedbackAnchor(enemy.State, card);
}
@@ -2086,6 +2177,7 @@ namespace KernelPanic.UI
string primaryText = text;
if (!shieldOnly && payload.ShieldDamage > 0) text += $" / -{payload.ShieldDamage} shield";
AppendCombatLog($"{CombatantName(payload.Target)}: {text}.", shieldOnly ? "journal-shield" : "journal-damage");
ShowProcessResult(payload.Target, primaryText, shieldOnly ? "shield" : "damage");
string tone = BuildDamageFloatClasses(tier, payload, shieldOnly);
string beatClass = fedoraPayoff ? "feedback-fedora-payoff" : BuildDamageBeatClass(tier, payload, shieldOnly);
if (fedoraPayoff)
@@ -2143,6 +2235,7 @@ namespace KernelPanic.UI
}
SpawnFloatingText(payload.Combatant, restartPending ? "restart pending" : "terminated", "float-kill float-large", 0);
ShowProcessResult(payload.Combatant, restartPending ? "RESTART" : "EXIT 0", restartPending ? "status" : "kill");
AppendCombatLog($"{combatantName}: {(restartPending ? "restart pending" : "terminated")}.", restartPending ? "journal-status" : "journal-damage");
if (!restartPending && TryGetCombatantFeedbackRect(payload.Combatant, out Rect targetBounds))
{
@@ -2480,14 +2573,18 @@ namespace KernelPanic.UI
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");
string result = $"+{state.CurrentUptime - oldUptime} HP";
SpawnFloatingText(element, result, "float-heal");
ShowProcessResult(state, result, "heal");
AppendCombatLog($"{CombatantName(state)}: {result}.", "journal-heal");
PlayElementBeat(element, "feedback-boost", 220);
}
if (_previousShield.TryGetValue(state, out int oldShield) && state.Shield > oldShield)
{
string result = $"+{state.Shield - oldShield} SH";
SpawnFloatingText(element, $"+{state.Shield - oldShield} shield", "float-shield");
ShowProcessResult(state, result, "shield");
AppendCombatLog($"{CombatantName(state)}: +{state.Shield - oldShield} shield.", "journal-shield");
PlayElementBeat(element, "feedback-block", 220);
}
@@ -2496,6 +2593,28 @@ namespace KernelPanic.UI
_previousShield[state] = state.Shield;
}
private void ShowProcessResult(CombatantState state, string text, string tone)
{
if (!TryGetCombatantElement(state, out VisualElement element)) return;
Label result = element.Q<Label>("ProcessResult");
if (result == null) return;
foreach (string className in new[] { "damage", "shield", "heal", "status", "kill" })
result.RemoveFromClassList("process-result-" + className);
result.text = text;
result.AddToClassList("process-result-active");
result.AddToClassList("process-result-" + tone);
int version = ++_feedbackBeatVersion;
_feedbackBeatVersions[result] = version;
ScheduleFeedback(() =>
{
if (!_feedbackBeatVersions.TryGetValue(result, out int current) || current != version) return;
result.text = string.Empty;
result.RemoveFromClassList("process-result-active");
result.RemoveFromClassList("process-result-" + tone);
_feedbackBeatVersions.Remove(result);
}, UIPreferences.ReducedMotion ? 900 : 1200);
}
private static string BuildDamageFloatClasses(HitMagnitudeTier tier, DamageDealtEvent payload, bool shieldOnly)
{
string classes = shieldOnly || payload.WasFullyBlocked ? "float-shield" : "float-damage";
@@ -3160,6 +3279,57 @@ namespace KernelPanic.UI
private void HandleCombatLog(string message) => AppendCombatLog(message);
private void RefreshJournalActionResults()
{
if (_journalActionResults == null) return;
bool atLatest = _journalScroll == null ||
_journalScroll.verticalScroller.highValue - _journalScroll.scrollOffset.y < 24;
IReadOnlyList<ExecutionAction> actions = _executionTrace?.Actions;
_expandedJournalActions.RemoveWhere(action => actions == null || !actions.Contains(action));
_journalActionResults.Clear();
if (actions == null || actions.Count == 0)
{
_journalActionResults.style.display = DisplayStyle.None;
return;
}
_journalActionResults.style.display = DisplayStyle.Flex;
for (int i = 0; i < actions.Count; i++)
{
ExecutionAction action = actions[i];
var metrics = new List<string>();
if (action.UptimeDamage > 0) metrics.Add($"{action.UptimeDamage} damage");
if (action.ShieldDamage > 0) metrics.Add($"{action.ShieldDamage} Shield damage");
if (action.ShieldGranted > 0) metrics.Add($"+{action.ShieldGranted} Shield");
if (action.PlayerUptimeLost > 0) metrics.Add($"-{action.PlayerUptimeLost} host Uptime");
if (action.PlayerShieldBlocked > 0) metrics.Add($"{action.PlayerShieldBlocked} blocked");
string summary = metrics.Count == 0 ? "" : " · " + string.Join(" · ", metrics);
var row = new Foldout
{
name = $"JournalActionResult_{i}",
text = $"[{action.Stage}] {action.Label} · {(action.Complete ? "done" : "resolving")}{summary}",
value = _expandedJournalActions.Contains(action)
};
row.AddToClassList("journal-action-result");
row.EnableInClassList("journal-action-active", !action.Complete);
row.RegisterValueChangedCallback(evt =>
{
if (evt.newValue) _expandedJournalActions.Add(action);
else _expandedJournalActions.Remove(action);
evt.StopPropagation();
});
foreach (string detail in action.Details)
row.Add(SoftwareCardView.Text("> " + detail, "journal-action-detail"));
foreach (string breakdown in action.DamageBreakdowns)
row.Add(SoftwareCardView.Text("calc> " + breakdown, "journal-action-damage"));
_journalActionResults.Add(row);
}
if (atLatest && _journalScroll != null)
ScheduleFeedback(() => _journalScroll.scrollOffset =
new Vector2(0, _journalScroll.verticalScroller.highValue), 0);
}
private void AppendCombatLog(string message, string tone = null)
{
if (string.IsNullOrEmpty(message) || message.Contains("would resolve:")) return;
@@ -3174,6 +3344,9 @@ namespace KernelPanic.UI
if (tone != null) entry.AddToClassList(tone);
_journalEntries.Add(entry);
while (_journalEntries.childCount > 64) _journalEntries.RemoveAt(0);
// CombatExecutionTrace records log details before this UI listener runs.
// Rebuild here so the journal's optional calculation rows include them immediately.
RefreshJournalActionResults();
if (atLatest) ScheduleFeedback(() => _journalScroll.scrollOffset = new Vector2(0, _journalScroll.verticalScroller.highValue), 0);
}
}
+40 -5
View File
@@ -9,12 +9,12 @@ namespace KernelPanic.UI
{
public static Button BuildWidget(DailyQuestState state, DateTime utcNow, Action open)
{
var widget = new Button(open) { name = "DailyQuestWidget", tooltip = "Open daily quests (Enter)" };
var widget = new Button(open) { name = "DailyQuestWidget" };
widget.AddToClassList("daily-quest-widget");
var counts = Counts(state);
var heading = new VisualElement();
heading.AddToClassList("daily-service-summary");
heading.Add(TerminalLayout.Heading("[ cron.daily ]", className: "daily-service-title"));
heading.Add(TerminalLayout.Heading("[ systemctl status cron.daily ]", className: "daily-service-title"));
var reward = TerminalLayout.BodyText(counts.Ready == 1 ? "1 reward ready" : $"{counts.Ready} rewards ready",
"DailyQuestRewardReady", "daily-reward-ready");
reward.style.display = counts.Ready > 0 ? DisplayStyle.Flex : DisplayStyle.None;
@@ -100,12 +100,13 @@ namespace KernelPanic.UI
overlay.AddToClassList("daily-quest-overlay");
var dialog = new VisualElement { name = "DailyQuestDialog" };
dialog.AddToClassList("daily-quest-dialog");
dialog.AddToClassList("terminal-pane");
var header = new VisualElement { name = "DailyQuestHeader" };
header.AddToClassList("daily-detail-header");
header.Add(TerminalLayout.BodyText("$ cat /etc/cron.daily/quests", className: "daily-detail-command"));
header.AddToClassList("terminal-pane-titlebar");
var titleRow = new VisualElement();
titleRow.AddToClassList("daily-service-summary");
titleRow.Add(TerminalLayout.Heading("DAILY TASKS", className: "daily-service-title"));
titleRow.Add(TerminalLayout.Heading("[ crontab -l ]", className: "daily-service-title"));
titleRow.Add(TerminalLayout.BodyText("", "DailyQuestDetailCountdown", "daily-service-meta"));
header.Add(titleRow);
header.Add(TerminalLayout.BodyText("", "DailyQuestDetailSummary", "daily-service-meta"));
@@ -148,6 +149,7 @@ namespace KernelPanic.UI
bool complete = progress >= DailyQuests.Target(kind);
row.EnableInClassList("daily-quest-complete", complete);
row.EnableInClassList("daily-quest-claimed", claimed);
row.Add(TerminalLayout.BodyText($"0 0 * * * /etc/cron.daily/{JobName(kind)}", className: "daily-cron-entry"));
row.Add(TerminalLayout.BodyText(DailyQuests.Description(kind), className: "daily-quest-name"));
int filled = progress * 10 / DailyQuests.Target(kind);
var progressRow = new VisualElement();
@@ -157,7 +159,13 @@ namespace KernelPanic.UI
progressRow.Add(TerminalLayout.BodyText($"{progress}/{DailyQuests.Target(kind)}", className: "daily-detail-values"));
row.Add(progressRow);
var reward = DailyQuests.Reward(kind);
row.Add(TerminalLayout.BodyText($"+{reward.Bandwidth} Bandwidth / +{reward.Entropy} Entropy"));
int commits = DailyQuests.CommitReward(kind);
string commitText = commits > 0 ? $" / +{commits} Commit{(commits == 1 ? string.Empty : "s")}" : string.Empty;
row.Add(TerminalLayout.BodyText($"+{reward.Bandwidth} Bandwidth / +{reward.Entropy} Entropy{commitText}"));
string status = claimed ? "status=exited exit=0 reward=committed"
: complete ? "status=exited exit=0 reward=pending"
: "status=running exit=--";
row.Add(TerminalLayout.BodyText(status, className: "daily-exit-status"));
var button = new Button(() => claim(kind, period))
{ name = "ClaimDailyQuest" + kind, text = claimed ? "[ CLAIMED ]" : complete ? "> CLAIM REWARD" : "[ in progress ]" };
button.AddToClassList("terminal-button");
@@ -168,7 +176,34 @@ namespace KernelPanic.UI
row.Add(button);
quests.Add(row);
}
var bonus = new VisualElement { name = "DailyQuestCompletionBonus" };
bonus.AddToClassList("daily-quest");
bonus.AddToClassList("daily-quest-completion-bonus");
bool bonusClaimed = DailyQuests.CompletionBonusClaimed(state);
int claimedCount = Counts(state).Claimed;
bonus.EnableInClassList("daily-quest-claimed", bonusClaimed);
bonus.Add(TerminalLayout.BodyText("[Service]", className: "daily-quest-name"));
bonus.Add(TerminalLayout.BodyText("ExecStartPost=/usr/bin/award-all-clear"));
bonus.Add(TerminalLayout.BodyText($"ConditionPathExists=/run/cron.daily/all-{DailyQuests.Count}.ok"));
bonus.Add(TerminalLayout.BodyText($"# claim all {DailyQuests.Count} task rewards ({claimedCount}/{DailyQuests.Count})"));
bonus.Add(TerminalLayout.BodyText($"+{DailyQuests.CompletionBonusBandwidth} Bandwidth / +{DailyQuests.CompletionBonusEntropy} Entropy / +{DailyQuests.CompletionBonusCommits} Commits"));
bonus.Add(TerminalLayout.BodyText(bonusClaimed ? "status=exited exit=0 reward=committed" : "status=waiting exit=-- # waiting for all five jobs to exit 0",
"DailyQuestCompletionBonusStatus", "daily-service-meta"));
quests.Add(bonus);
return panel;
}
private static string JobName(DailyQuestKind kind) => kind switch
{
DailyQuestKind.Waves => "clear-waves",
DailyQuestKind.Cards => "play-cards",
DailyQuestKind.Damage => "deal-uptime",
DailyQuestKind.BlockDamage => "block-damage",
DailyQuestKind.NativeCards => "run-native",
DailyQuestKind.ShieldDamage => "break-shields",
DailyQuestKind.SurviveRounds => "survive-rounds",
DailyQuestKind.WaveFive => "reach-wave-five",
_ => kind.ToString().ToLowerInvariant()
};
}
}
@@ -19,23 +19,5 @@ namespace KernelPanic.UI
: enemy.Archetype.Tier == EnemyTier.Boss ? "BOSS PROCESS"
: enemy.HasRevived ? "RUNNING / RESTART USED" : enemy.HasEliteSignal ? "ELITE PROCESS" : "RUNNING";
public static string Behavior(EnemyInstance enemy)
{
if (enemy.ArchetypeId == "process_supervisor") return "2 workers > Shield > interrupt / 8-process cap / attacks +3 below half Uptime";
if (enemy.ArchetypeId == "oom_reaper") return "-2 RAM / charge > 14-damage burst > recovery / attacks +3 below half Uptime";
if (enemy.ArchetypeId == "process_broker") return "Worker > attack / 8-process cap / attacks +3 below half Uptime";
if (enemy.HasBehavior(EnemyBehaviorFlags.BossCycle))
return "Shield > probe > heavy interrupt / next attacks +3 below half uptime";
if (enemy.HasBehavior(EnemyBehaviorFlags.Revive))
return enemy.PendingRevive ? "Revives next exchange" : enemy.HasRevived ? "Revival spent" : "Revival available / can be reaped";
if (enemy.HasBehavior(EnemyBehaviorFlags.Grow))
return $"Growing attack / {enemy.TurnsAlive} turns survived";
if (enemy.HasBehavior(EnemyBehaviorFlags.Countdown)) return $"Countdown: {enemy.CountdownRemaining}";
if (enemy.HasBehavior(EnemyBehaviorFlags.DefendAllies)) return "Shields self and adjacent processes";
if (enemy.HasBehavior(EnemyBehaviorFlags.ObfuscateIntent)) return enemy.IntentRevealed
? "Exposed this round / hides next round"
: "Hit to reveal / surge, Shield or bypass";
return "";
}
}
}
+1 -1
View File
@@ -51,6 +51,7 @@ namespace KernelPanic.UI
_emptyHintLabel = root.Q<Label>("FeaturedUnitEmptyHint");
_populatedState = root.Q<VisualElement>("FeaturedUnitPopulatedState");
_emptyState = root.Q<VisualElement>("FeaturedUnitEmptyState");
_panel.tooltip = string.Empty;
DistroArtPresenter.ConfigureArtLabel(_asciiLabel, _monospaceFont);
_asciiFitter = new AsciiArtFitter(_asciiLabel, _monospaceFont);
@@ -141,7 +142,6 @@ namespace KernelPanic.UI
_emptyState.AddToClassList("hidden");
_currentUnit = unit;
TerminalTheme.SetDistro(_panel, unit);
_panel.tooltip = "[F2] next distro / [Enter] inspect";
_titleLabel.text = "[ neofetch ]";
_asciiFitter.SetArt(DistroArtPresenter.Render(_asciiLabel, _asciiPlaceholder, unit));
+228 -28
View File
@@ -37,6 +37,10 @@ namespace KernelPanic.UI
private VisualElement _selectorOverlay;
private VisualElement _selectorDialog;
private VisualElement _selectorReturnFocus;
private Button _pullHistoryButton;
private VisualElement _pullHistoryOverlay;
private ScrollView _pullHistoryDialog;
private VisualElement _pullHistoryReturnFocus;
private DistroDatabase _distroDatabase;
private PackageDatabase _packageDatabase;
private FontAsset _monospaceFont;
@@ -76,6 +80,9 @@ namespace KernelPanic.UI
_requestPullCutscene = pullCutsceneCallback;
_bannerList = root.Q<VisualElement>("GachaBannerList");
_bannerDetail = root.Q<VisualElement>("GachaBannerDetail");
if (_pullHistoryButton != null) _pullHistoryButton.clicked -= OpenPullHistory;
_pullHistoryButton = root.Q<Button>("GachaPullHistoryButton");
if (_pullHistoryButton != null) _pullHistoryButton.clicked += OpenPullHistory;
}
public void Open()
@@ -89,6 +96,17 @@ namespace KernelPanic.UI
Refresh();
}
public void OpenPullHistory()
{
if (_root == null || _gachaService == null) return;
EnsurePullHistoryOverlay();
_pullHistoryReturnFocus = _root.focusController?.focusedElement as VisualElement;
RenderPullHistory();
_pullHistoryOverlay.RemoveFromClassList("hidden");
_pullHistoryOverlay.AddToClassList("modal-open");
_pullHistoryDialog.Q<Button>("ClosePullHistory")?.Focus();
}
public void Refresh()
{
if (_bannerList == null || _bannerDetail == null || _gachaService == null)
@@ -98,6 +116,12 @@ namespace KernelPanic.UI
_bannerRows.Clear();
_bannerList.Clear();
if (_pullHistoryButton != null)
_pullHistoryButton.text = $"git log --pulls\n{_gachaService.PullHistory.Count} saved";
Label branchCommand = new("$ git branch --list");
branchCommand.AddToClassList("gacha-branch-command");
_bannerList.Add(branchCommand);
for (int i = 0; i < _bannerIds.Length; i++)
{
@@ -119,7 +143,7 @@ namespace KernelPanic.UI
for (var target = evt.target as VisualElement; target != null && target != _root; target = target.parent)
if (target.ClassListContains("gacha-last-pull")) return;
if (evt.keyCode != KeyCode.UpArrow && evt.keyCode != KeyCode.DownArrow) return;
SelectBanner((_selectedBannerIndex + 1) % 2);
SelectBanner((_selectedBannerIndex + 1) % _bannerRows.Count);
_bannerRows[_selectedBannerIndex].Focus();
evt.StopPropagation();
}
@@ -127,13 +151,13 @@ namespace KernelPanic.UI
private VisualElement BuildBannerRow(string bannerId)
{
Button row = new();
row.SetEnabled(bannerId != GachaService.LimitedBannerId);
row.SetEnabled(true);
row.AddToClassList("gacha-banner-row");
row.Add(new Label(">") { name = $"GachaBannerCursor_{bannerId}" });
row.Add(new Label(" ") { name = $"GachaBannerCursor_{bannerId}" });
row.ElementAt(0).AddToClassList("command-cursor");
row.Add(new Label(GetBannerTitle(bannerId)) { name = $"GachaBannerName_{bannerId}" });
row.Add(new Label(GetBannerRef(bannerId)) { name = $"GachaBannerName_{bannerId}" });
row.ElementAt(1).AddToClassList("command-text");
row.Add(new Label(GetBannerStatus(bannerId)) { name = $"GachaBannerStatus_{bannerId}" });
@@ -162,7 +186,9 @@ namespace KernelPanic.UI
{
bool selected = i == _selectedBannerIndex;
_bannerRows[i].EnableInClassList(SelectedClassName, selected);
_bannerRows[i].Q<Label>(className: "command-cursor").visible = selected;
Label cursor = _bannerRows[i].Q<Label>(className: "command-cursor");
cursor.visible = true;
cursor.text = selected ? "*" : " ";
}
RenderSelectedBanner();
@@ -185,6 +211,12 @@ namespace KernelPanic.UI
return;
}
if (bannerId == GachaService.LimitedBannerId)
{
RenderLimitedBanner();
return;
}
RenderFutureBanner(bannerId);
}
@@ -193,10 +225,6 @@ namespace KernelPanic.UI
GachaBannerState state = _gachaService.BeginnerState;
_bannerDetail.Add(BuildBannerHero("beginner install media"));
Label title = new("beginner install media");
title.AddToClassList("gacha-detail-title");
_bannerDetail.Add(title);
_bannerDetail.Add(BuildInfoLine("Entropy", _wallet == null ? "--" : _wallet.Balance.ToString()));
_bannerDetail.Add(BuildInfoLine("Commits", _gachaService.PullTokens.ToString()));
_bannerDetail.Add(BuildInfoLine("pulls", $"{state.totalPulls}/{GachaService.BeginnerMaxPulls}"));
@@ -248,10 +276,6 @@ namespace KernelPanic.UI
GachaBannerState state = _gachaService.StandardState;
_bannerDetail.Add(BuildBannerHero("stable branch"));
Label title = new("stable branch");
title.AddToClassList("gacha-detail-title");
_bannerDetail.Add(title);
_bannerDetail.Add(BuildInfoLine("Entropy", _wallet == null ? "--" : _wallet.Balance.ToString()));
_bannerDetail.Add(BuildInfoLine("Commits", _gachaService.PullTokens.ToString()));
_bannerDetail.Add(BuildInfoLine("pulls", state.totalPulls.ToString()));
@@ -310,6 +334,149 @@ namespace KernelPanic.UI
}
}
private void RenderLimitedBanner()
{
GachaBannerState state = _gachaService.LimitedState;
_bannerDetail.Add(BuildBannerHero("feature branch: NixOS"));
_bannerDetail.Add(BuildInfoLine("Entropy", _wallet == null ? "--" : _wallet.Balance.ToString()));
_bannerDetail.Add(BuildInfoLine("Commits", _gachaService.PullTokens.ToString()));
_bannerDetail.Add(BuildInfoLine("pulls", state.totalPulls.ToString()));
_bannerDetail.Add(BuildInfoLine("4-star pity", $"{state.pityCounter}/{GachaService.FourStarHardPity}"));
_bannerDetail.Add(BuildInfoLine("5-star pity", $"{state.fiveStarPityCounter}/{GachaService.FiveStarHardPity}"));
_bannerDetail.Add(BuildInfoLine("featured guarantee", state.featuredFiveStarGuaranteed ? "armed" : "not armed"));
_bannerDetail.Add(BuildInfoLine("cost", $"{GachaService.LimitedSinglePullCost} Commit / {GachaService.LimitedTenPullCost} for ten"));
Label rules = new("Featured 5-star distro: NixOS. A 4-star package or featured Fedora/Ubuntu is guaranteed every 10 pulls. Five-star odds ramp from pull 66 and guarantee by pull 80. A 5-star first splits between package and distro; a non-featured 5-star distro arms the next distro hit as guaranteed NixOS.");
rules.AddToClassList("gacha-rules");
_bannerDetail.Add(rules);
VisualElement actions = new();
actions.AddToClassList("gacha-actions");
Button singleButton = new(() => RequestPullSelectedBanner(1))
{
text = $"git pull --single\n{GachaService.LimitedSinglePullCost}x {GachaService.FormatCurrencyName(GachaCurrencyType.StandardPull)}"
};
singleButton.AddToClassList("terminal-button");
singleButton.AddToClassList("gacha-action-button");
singleButton.SetEnabled(CanAttemptLimitedPull(1));
actions.Add(singleButton);
Button tenButton = new(() => RequestPullSelectedBanner(10))
{
text = $"git pull --ten\n{GachaService.LimitedTenPullCost}x {GachaService.FormatCurrencyName(GachaCurrencyType.StandardPull)}"
};
tenButton.AddToClassList("terminal-button");
tenButton.AddToClassList("gacha-action-button");
tenButton.SetEnabled(CanAttemptLimitedPull(10));
actions.Add(tenButton);
_bannerDetail.Insert(_bannerDetail.IndexOf(rules), actions);
if (_pendingPullCount > 0) _bannerDetail.Add(BuildEntropyPrompt());
if (_resultBannerId == GachaService.LimitedBannerId &&
(_resultRewardLines.Count > 0 || !string.IsNullOrWhiteSpace(_resultText)))
_bannerDetail.Add(BuildPullResultReveal());
}
private void RenderPullHistory()
{
if (_pullHistoryDialog == null) return;
TerminalTheme.PreserveFocus(_pullHistoryDialog);
_pullHistoryDialog.Clear();
bool emptyHistory = _gachaService.PullHistory.Count == 0;
_pullHistoryDialog.EnableInClassList("is-empty", emptyHistory);
VisualElement header = new();
header.AddToClassList("package-equip-header");
header.AddToClassList("terminal-pane-titlebar");
Label title = new("[ git log --pulls ]");
title.AddToClassList("gacha-detail-title");
header.Add(title);
Button close = new(ClosePullHistory) { name = "ClosePullHistory", text = "x", focusable = true };
close.AddToClassList("modal-close-button");
header.Add(close);
_pullHistoryDialog.Add(header);
if (emptyHistory)
{
Label command = new("$ git log --pulls --all");
command.AddToClassList("gacha-history-command");
_pullHistoryDialog.Add(command);
Label empty = new("fatal: no committed pulls found\n" +
"hint: completed pull receipts appear after rewards are committed");
empty.AddToClassList("gacha-rules");
empty.AddToClassList("gacha-history-empty");
_pullHistoryDialog.Add(empty);
return;
}
_pullHistoryDialog.Add(BuildInfoLine("retention", $"latest {GachaService.MaxPullHistoryEntries} transactions"));
_pullHistoryDialog.Add(BuildInfoLine("entries", _gachaService.PullHistory.Count.ToString()));
for (int i = 0; i < _gachaService.PullHistory.Count; i++)
{
GachaPullHistoryEntry entry = _gachaService.PullHistory[i];
string payment = entry.entropySpent > 0 ? $"{entry.entropySpent} Entropy" : $"{entry.currencySpent} Commits";
string timestamp = DateTime.TryParse(entry.pulledUtc, out DateTime parsed)
? parsed.ToLocalTime().ToString("yyyy-MM-dd HH:mm")
: entry.pulledUtc;
Foldout transaction = new()
{
text = $"{timestamp} {GetBannerTitle(entry.bannerId)} [{entry.rewards.Count}] -{payment}",
value = i == 0
};
transaction.AddToClassList("gacha-result-block");
for (int rewardIndex = 0; rewardIndex < entry.rewards.Count; rewardIndex++)
{
GachaPullHistoryRewardEntry reward = entry.rewards[rewardIndex];
string duplicateUnit = reward.rewardType == GachaRewardType.Package ? "Cache" : "Merges";
string status = reward.outcomeKind switch
{
PullOutcomeKind.Granted => " NEW",
PullOutcomeKind.Dupe => $" +{reward.duplicateValue} {duplicateUnit}",
PullOutcomeKind.DupeOverflow => $" +{reward.duplicateValue} {duplicateUnit}",
_ => reward.guaranteed ? " guaranteed" : reward.pityTriggered ? " pity" : string.Empty
};
Label line = new($"{rewardIndex + 1:00}: {reward.stars}★ {reward.displayName}{status}");
line.AddToClassList("gacha-result-card");
line.AddToClassList(RarityClassForStars(reward.stars));
transaction.Add(line);
}
_pullHistoryDialog.Add(transaction);
}
}
private void EnsurePullHistoryOverlay()
{
if (_root == null || _pullHistoryOverlay != null) return;
_pullHistoryOverlay = new VisualElement { name = "GachaPullHistoryOverlay" };
TerminalTheme.ConstrainModalFocus(_pullHistoryOverlay);
_pullHistoryOverlay.AddToClassList("modal-overlay");
_pullHistoryOverlay.AddToClassList("gacha-pull-history-overlay");
_pullHistoryOverlay.AddToClassList("hidden");
_pullHistoryOverlay.RegisterCallback<KeyDownEvent>(evt => evt.StopPropagation());
_pullHistoryOverlay.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode != KeyCode.Escape) return;
ClosePullHistory();
evt.StopImmediatePropagation();
}, TrickleDown.TrickleDown);
_pullHistoryDialog = new ScrollView(ScrollViewMode.Vertical) { name = "GachaPullHistoryDialog" };
_pullHistoryDialog.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
_pullHistoryDialog.AddToClassList("gacha-pull-history-dialog");
_pullHistoryDialog.AddToClassList("dialog-scroll");
_pullHistoryDialog.AddToClassList("terminal-pane");
_pullHistoryOverlay.Add(_pullHistoryDialog);
_root.Add(_pullHistoryOverlay);
}
private void ClosePullHistory()
{
_pullHistoryOverlay?.RemoveFromClassList("modal-open");
_pullHistoryOverlay?.AddToClassList("hidden");
if (_pullHistoryReturnFocus?.panel != null) _pullHistoryReturnFocus.Focus();
_pullHistoryReturnFocus = null;
}
private void EnsureSelectorOverlay()
{
if (_root == null || _selectorOverlay != null)
@@ -332,6 +499,7 @@ namespace KernelPanic.UI
_selectorDialog = new ScrollView(ScrollViewMode.Vertical);
_selectorDialog.AddToClassList("five-star-selector-dialog");
_selectorDialog.AddToClassList("dialog-scroll");
_selectorDialog.AddToClassList("terminal-pane");
_selectorOverlay.Add(_selectorDialog);
_root.Add(_selectorOverlay);
}
@@ -376,13 +544,14 @@ namespace KernelPanic.UI
VisualElement header = new();
header.AddToClassList("package-equip-header");
header.AddToClassList("terminal-pane-titlebar");
string stepTitle = _selectorStep switch
{
SelectorStep.Character => "5-star selector: choose a standard character",
SelectorStep.Equipment => "5-star selector: choose standard equipment",
_ => "5-star selector"
};
Label title = new(stepTitle);
Label title = new($"[ {stepTitle} ]");
title.AddToClassList("gacha-detail-title");
header.Add(title);
Button close = new(CloseFiveStarSelector) { text = "x", focusable = true };
@@ -500,7 +669,8 @@ namespace KernelPanic.UI
return;
}
if (bannerId != GachaService.BeginnerBannerId && bannerId != GachaService.StandardBannerId)
if (bannerId != GachaService.BeginnerBannerId && bannerId != GachaService.StandardBannerId
&& bannerId != GachaService.LimitedBannerId)
{
_resultBannerId = bannerId;
_resultText = $"git pull origin {bannerId}: remote not implemented yet";
@@ -511,9 +681,13 @@ namespace KernelPanic.UI
}
PullPaymentSource source = entropyTokenCount > 0 ? PullPaymentSource.Entropy : PullPaymentSource.Commits;
GachaPullResult result = bannerId == GachaService.BeginnerBannerId
? _gachaService.PerformBeginnerPull(pullCount, _wallet, source)
: _gachaService.PerformStandardPull(pullCount, _wallet, source);
GachaPullResult result = bannerId switch
{
GachaService.BeginnerBannerId => _gachaService.PerformBeginnerPull(pullCount, _wallet, source),
GachaService.StandardBannerId => _gachaService.PerformStandardPull(pullCount, _wallet, source),
GachaService.LimitedBannerId => _gachaService.PerformLimitedPull(pullCount, _wallet, source),
_ => GachaPullResult.Failed(bannerId, "remote not implemented yet")
};
if (!result.Success)
{
_resultBannerId = bannerId;
@@ -683,7 +857,8 @@ namespace KernelPanic.UI
private void RequestPullSelectedBanner(int pullCount)
{
string bannerId = _bannerIds[_selectedBannerIndex];
if (bannerId != GachaService.BeginnerBannerId && bannerId != GachaService.StandardBannerId)
if (bannerId != GachaService.BeginnerBannerId && bannerId != GachaService.StandardBannerId
&& bannerId != GachaService.LimitedBannerId)
{
PullSelectedBanner(pullCount, 0);
return;
@@ -796,6 +971,17 @@ namespace KernelPanic.UI
_gachaService.RootCredits > 0);
}
private bool CanAttemptLimitedPull(int pullCount)
{
if (_gachaService.CanAffordPull(pullCount, _wallet, PullPaymentSource.Commits, GachaService.LimitedBannerId, out _))
return true;
int cost = _gachaService.GetPullCost(GachaService.LimitedBannerId, pullCount);
int missingTokens = _gachaService.GetMissingPullTokens(GachaCurrencyType.StandardPull, cost);
return missingTokens > 0 &&
((_wallet != null && _wallet.Balance >= cost * GachaService.EntropyPerCommit) ||
_gachaService.RootCredits > 0);
}
private void ClearEntropyPrompt()
{
_pendingPullCount = 0;
@@ -811,24 +997,25 @@ namespace KernelPanic.UI
artRow.AddToClassList("gacha-hero-art-row");
IReadOnlyList<DistroDefinition> distros = _distroDatabase == null ? Array.Empty<DistroDefinition>() : _distroDatabase.AllDistros;
int artCount = Mathf.Min(3, distros.Count);
for (int i = 0; i < artCount; i++)
List<DistroDefinition> heroDistros = new();
if (bannerTitle.IndexOf("NixOS", StringComparison.OrdinalIgnoreCase) >= 0)
{
artRow.Add(BuildDistroArtCard(distros[i]));
for (int i = 0; i < distros.Count; i++)
if (string.Equals(distros[i]?.Id, GachaService.LimitedFeaturedFiveStarDistroId, StringComparison.OrdinalIgnoreCase))
heroDistros.Add(distros[i]);
}
for (int i = 0; i < distros.Count && heroDistros.Count < 3; i++)
if (distros[i] != null && !heroDistros.Contains(distros[i])) heroDistros.Add(distros[i]);
for (int i = 0; i < heroDistros.Count; i++) artRow.Add(BuildDistroArtCard(heroDistros[i]));
if (artCount == 0)
if (heroDistros.Count == 0)
{
Label empty = new("ascii art unavailable");
empty.AddToClassList("gacha-rules");
artRow.Add(empty);
}
Label title = new(bannerTitle);
title.AddToClassList("gacha-hero-title");
hero.Add(artRow);
hero.Add(title);
return hero;
}
@@ -892,7 +1079,9 @@ namespace KernelPanic.UI
{
GachaService.BeginnerBannerId => _gachaService.IsBeginnerBannerAvailable ? $"{_gachaService.BeginnerState.totalPulls}/{GachaService.BeginnerMaxPulls}" : "closed",
GachaService.StandardBannerId => _gachaService.PendingStandardFiveStarSelectors > 0 ? "selector ready" : $"{_gachaService.GetStandardFiveStarSelectorProgress()}/{GachaService.StandardFiveStarSelectorInterval}",
GachaService.LimitedBannerId => "soon",
GachaService.LimitedBannerId => _gachaService.LimitedState.featuredFiveStarGuaranteed
? "featured guaranteed"
: $"{_gachaService.LimitedState.fiveStarPityCounter}/{GachaService.FiveStarHardPity}",
_ => "--"
};
}
@@ -907,5 +1096,16 @@ namespace KernelPanic.UI
_ => bannerId
};
}
private static string GetBannerRef(string bannerId)
{
return bannerId switch
{
GachaService.BeginnerBannerId => "beginner",
GachaService.StandardBannerId => "stable",
GachaService.LimitedBannerId => "feature/nixos",
_ => "remote/" + bannerId
};
}
}
}
@@ -78,6 +78,7 @@ namespace KernelPanic.UI
{
GachaService.BeginnerBannerId => gacha.PerformBeginnerPull(pending.PullCount, wallet, paymentSource),
GachaService.StandardBannerId => gacha.PerformStandardPull(pending.PullCount, wallet, paymentSource),
GachaService.LimitedBannerId => gacha.PerformLimitedPull(pending.PullCount, wallet, paymentSource),
_ => GachaPullResult.Failed(pending.BannerId, "remote not implemented yet")
};
@@ -138,6 +139,7 @@ namespace KernelPanic.UI
completedRewards.Add(new CompletedGachaReward(i + 1, reward.StarRating, displayName, reward.RewardType, outcomeKind, merges, languages, reward.Guaranteed, reward.PityTriggered, display));
}
gacha.RecordPullHistory(result, completedRewards, DateTime.UtcNow);
WriteState(saveService, saveData, wallet, collection, gacha);
return new CompletedGachaPull(result.BannerId, string.Join(" / ", header), completedRewards, gacha.PendingStandardFiveStarSelectors);
}
+94 -23
View File
@@ -19,6 +19,7 @@ namespace KernelPanic.UI
{
internal static class TerminalFontResolver
{
private const string BundledFontResourcePath = "Fonts/JetBrainsMono-Regular";
private static readonly string[] PreferredMonospaceFontFamilies =
{
"Consolas",
@@ -46,8 +47,12 @@ namespace KernelPanic.UI
return _runtimeMonospaceFont;
}
Font dynamicFont = Font.CreateDynamicFontFromOSFont(PreferredMonospaceFontFamilies, 16);
if (dynamicFont == null)
// Keep metrics and ASCII alignment identical on every supported platform.
// The OS lookup remains as a recovery path for development projects that
// deliberately remove the bundled font.
Font sourceFont = Resources.Load<Font>(BundledFontResourcePath);
sourceFont ??= Font.CreateDynamicFontFromOSFont(PreferredMonospaceFontFamilies, 16);
if (sourceFont == null)
{
if (!_warnedMissingFont)
{
@@ -58,7 +63,7 @@ namespace KernelPanic.UI
return null;
}
_runtimeMonospaceFont = FontAsset.CreateFontAsset(dynamicFont);
_runtimeMonospaceFont = FontAsset.CreateFontAsset(sourceFont);
return _runtimeMonospaceFont;
}
}
@@ -229,12 +234,12 @@ namespace KernelPanic.UI
TerminalTheme.ConstrainModalFocus(_root.Q("RootCreditExchangeModal"));
Toggle motion = _root.Q<Toggle>("ReducedMotionToggle");
motion.SetValueWithoutNotify(UIPreferences.ReducedMotion);
motion.text = UIPreferences.ReducedMotion ? "[ true ]" : "[ false ]";
motion.text = UIPreferences.ReducedMotion ? "true" : "false";
motion.RegisterValueChangedCallback(evt =>
{
UIPreferences.ReducedMotion = evt.newValue;
UIPreferences.Save();
motion.text = evt.newValue ? "[ true ]" : "[ false ]";
motion.text = evt.newValue ? "true" : "false";
_root.EnableInClassList("reduced-motion", evt.newValue);
_shellRoot.EnableInClassList("reduced-motion", evt.newValue);
if (evt.newValue && !_bootIntroPanel.ClassListContains(HiddenClassName)) CompleteBootIntro();
@@ -242,12 +247,13 @@ namespace KernelPanic.UI
});
Button textSize = _root.Q<Button>("TextSizeButton");
Button density = _root.Q<Button>("DensityButton");
_root.Q<Button>("SoundVolumeButton").clicked += () =>
SliderInt soundVolume = _root.Q<SliderInt>("SoundVolumeSlider");
soundVolume.RegisterValueChangedCallback(evt =>
{
UIPreferences.SoundVolume = (UIPreferences.SoundVolume / 25 + 1) % 5 * 25;
UIPreferences.SoundVolume = evt.newValue;
UIPreferences.Save();
RefreshPreferenceControls();
};
RefreshSoundVolumeControl();
});
textSize.clicked += () =>
{
UIPreferences.TextSize = UIPreferences.TextSize == UITextSize.Standard ? UITextSize.Large : UITextSize.Standard;
@@ -267,10 +273,20 @@ namespace KernelPanic.UI
{
Toggle motion = _root.Q<Toggle>("ReducedMotionToggle");
motion.SetValueWithoutNotify(UIPreferences.ReducedMotion);
motion.text = UIPreferences.ReducedMotion ? "[ true ]" : "[ false ]";
_root.Q<Button>("TextSizeButton").text = UIPreferences.TextSize == UITextSize.Large ? "[ large ]" : "[ standard ]";
_root.Q<Button>("DensityButton").text = UIPreferences.Density == UILayoutDensity.Comfortable ? "[ comfortable ]" : "[ compact ]";
_root.Q<Button>("SoundVolumeButton").text = UIPreferences.SoundVolume == 0 ? "[ muted ]" : $"[ {UIPreferences.SoundVolume}% ]";
motion.text = UIPreferences.ReducedMotion ? "true" : "false";
_root.Q<Button>("TextSizeButton").text = UIPreferences.TextSize == UITextSize.Large ? "large" : "standard";
_root.Q<Button>("DensityButton").text = UIPreferences.Density == UILayoutDensity.Comfortable ? "comfortable" : "compact";
RefreshSoundVolumeControl();
}
private void RefreshSoundVolumeControl()
{
SliderInt slider = _root.Q<SliderInt>("SoundVolumeSlider");
slider.SetValueWithoutNotify(UIPreferences.SoundVolume);
int filled = Mathf.RoundToInt(UIPreferences.SoundVolume / 10f);
string meter = new string('#', filled) + new string('-', 10 - filled);
_root.Q<Label>("SoundVolumeValue").text = UIPreferences.SoundVolume == 0
? "[----------] muted" : $"[{meter}] {UIPreferences.SoundVolume}%";
}
private void ComposeMetaServices()
@@ -285,6 +301,10 @@ namespace KernelPanic.UI
private void OnEnable()
{
// A script import can re-enable the scene component before Awake has rebound the
// UIDocument. The next normal Play-mode enable follows the usual Awake -> OnEnable
// order; this guard only protects that editor/domain-reload edge.
if (_root == null) return;
RegisterCallbacks();
_root.Focus();
_root.EnableInClassList("reduced-motion", UIPreferences.ReducedMotion);
@@ -322,7 +342,7 @@ namespace KernelPanic.UI
private void OnDisable()
{
UnregisterCallbacks();
if (_root != null) UnregisterCallbacks();
_blinkSchedule?.Pause();
_backgroundLog?.Stop();
_bootIntroSchedule?.Pause();
@@ -926,9 +946,15 @@ namespace KernelPanic.UI
private void ClaimDailyQuest(DailyQuestKind kind, long period)
{
if (PersistenceBlocked || _runLaunchPending) return;
bool completionBonusWasClaimed = DailyQuests.CompletionBonusClaimed(_saveData.dailyQuests);
bool claimed = DailyQuests.Claim(_saveData, kind, period, DateTime.UtcNow);
bool completionBonusAwarded = claimed && !completionBonusWasClaimed
&& DailyQuests.CompletionBonusClaimed(_saveData.dailyQuests);
if (claimed)
{
_wallet.SetBalance(_saveData.entropyBalance);
_gachaService.SetCurrencyBalance(GachaCurrencyType.StandardPull, _saveData.commitsBalance);
}
// Balances and the claim bit are committed in the same atomic save.
// On failure the existing recovery dialog blocks spending until retry succeeds.
SaveCurrentState();
@@ -939,7 +965,12 @@ namespace KernelPanic.UI
if (feedback != null && claimed && !PersistenceBlocked)
{
var reward = DailyQuests.Reward(kind);
feedback.text = $"[ OK ] Daily task completed.\n[ OK ] +{reward.Bandwidth} Bandwidth, +{reward.Entropy} Entropy deposited.";
int commits = DailyQuests.CommitReward(kind);
string commitText = commits > 0 ? $" +{commits} Commit{(commits == 1 ? string.Empty : "s")} deposited." : string.Empty;
feedback.text = $"[ OK ] Daily task completed.\n[ OK ] +{reward.Bandwidth} Bandwidth, +{reward.Entropy} Entropy deposited.{commitText}";
if (completionBonusAwarded)
feedback.text += $"\n[ BONUS ] All {DailyQuests.Count} tasks: +{DailyQuests.CompletionBonusBandwidth} Bandwidth, "
+ $"+{DailyQuests.CompletionBonusEntropy} Entropy, +{DailyQuests.CompletionBonusCommits} Commits.";
feedback.style.display = DisplayStyle.Flex;
}
else if (feedback != null && PersistenceBlocked) feedback.style.display = DisplayStyle.None;
@@ -2543,6 +2574,12 @@ namespace KernelPanic.UI
_dailyQuestReturnToPrompt = true;
return;
}
if (index == 7)
{
ShowGacha();
gachaScreen.OpenPullHistory();
return;
}
_commandEntries[index].Activate();
_root.Focus();
}
@@ -2587,24 +2624,58 @@ namespace KernelPanic.UI
string detail = valid
? $"{DistroPresentation.DisplayName(distro)} v{last.distroVersion}; {string.Join(" + ", last.languages)}. Uses the saved build and upgrade levels."
: string.IsNullOrWhiteSpace(last?.distroId) ? "No previous build saved. Start a run to enable retries." : failure;
actions.Add(TerminalLayout.Heading("[last build]"));
actions.Add(TerminalLayout.BodyText(detail, "LastRunBuildSummary", "run-archive-summary"));
actions.Add(TerminalLayout.Heading("$ history --runs --format=table"));
var columns = TerminalLayout.BodyText("# TIMESTAMP DISTRO SEED WAVE EXIT", className: "run-archive-columns");
actions.Add(columns);
if (_saveData?.recentRuns == null || _saveData.recentRuns.Count == 0)
{
actions.Add(TerminalLayout.BodyText("history: no completed runs (exit 1)", "RunArchiveEmpty", "run-archive-empty"));
}
else
{
int visible = Mathf.Min(RunHistory.Capacity, _saveData.recentRuns.Count);
for (int i = 0; i < visible; i++)
actions.Add(TerminalLayout.BodyText(FormatRunHistoryRow(i + 1, _saveData.recentRuns[i]),
$"RunArchiveRow{i}", "run-archive-table-row"));
}
actions.Add(TerminalLayout.BodyText("# saved build", className: "run-archive-section-label"));
actions.Add(TerminalLayout.BodyText((valid ? "ready: " : "unavailable: ") + detail,
"LastRunBuildSummary", "run-archive-summary"));
var commandsRow = new VisualElement();
commandsRow.AddToClassList("run-archive-commands");
var same = new Button(() => RetryLastRun(true))
{
name = "RetrySameSeedButton", text = "retry last run / same seed",
name = "RetrySameSeedButton", text = "$ retry --build=last --seed=same",
tooltip = valid && !last.hasRunSeed ? "The previous run has no saved seed. Repeat the build with a new seed instead." : detail
};
same.AddToClassList("terminal-button");
same.AddToClassList("run-archive-command");
same.SetEnabled(valid && last.hasRunSeed);
actions.Add(same);
var fresh = new Button(() => RetryLastRun(false)) { name = "RetryNewSeedButton", text = "repeat build / new seed", tooltip = detail };
commandsRow.Add(same);
var fresh = new Button(() => RetryLastRun(false)) { name = "RetryNewSeedButton", text = "$ retry --build=last --seed=random", tooltip = detail };
fresh.AddToClassList("terminal-button");
fresh.AddToClassList("run-archive-command");
fresh.SetEnabled(valid);
actions.Add(fresh);
commandsRow.Add(fresh);
var history = new Button(OpenRunHistory) { name = "RecentRunsButton", text = "recent runs" };
var history = new Button(OpenRunHistory) { name = "RecentRunsButton", text = "$ history --runs --inspect" };
history.AddToClassList("terminal-button");
actions.Add(history);
history.AddToClassList("run-archive-command");
commandsRow.Add(history);
actions.Add(commandsRow);
}
private static string FormatRunHistoryRow(int index, RunHistoryEntry entry)
{
if (entry == null) return $"{index,2} <corrupt entry>";
string timestamp = DateTimeOffset.TryParse(entry.endedUtc, out var ended)
? ended.ToLocalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)
: "unknown";
string distro = entry.distroName ?? entry.distroId ?? "unknown";
if (distro.Length > 16) distro = distro.Substring(0, 15) + "~";
string exit = entry.victory ? "0" : entry.surrendered ? "130" : "1";
return $"{index,2} {timestamp,-16} {distro,-16} {entry.seed,10} {entry.waveReached,4} {exit}";
}
private void AddResumeRunControl(VisualElement actions)
+12 -5
View File
@@ -23,26 +23,33 @@ namespace KernelPanic.UI
var dialog = new VisualElement();
dialog.AddToClassList("root-credit-dialog");
dialog.AddToClassList("run-history-dialog");
dialog.AddToClassList("terminal-pane");
dialog.style.width = Length.Percent(94);
dialog.style.maxWidth = 760;
dialog.style.maxHeight = Length.Percent(92);
bool empty = entries == null || entries.Count == 0;
dialog.EnableInClassList("is-empty", empty);
overlay.Add(dialog);
dialog.Add(SoftwareCardView.Text($"RECENT RUNS / last {RunHistory.Capacity}", "section-title"));
var titleBar = new VisualElement();
titleBar.AddToClassList("terminal-pane-titlebar");
titleBar.Add(SoftwareCardView.Text("[ history --runs --inspect ]", "section-title"));
dialog.Add(titleBar);
dialog.Add(new Label { name = "RunHistoryNotice", enableRichText = false });
dialog.Q<Label>("RunHistoryNotice").style.whiteSpace = WhiteSpace.Normal;
var scroll = new ScrollView(ScrollViewMode.Vertical);
scroll.style.flexShrink = 1;
scroll.style.flexGrow = 1;
scroll.style.flexGrow = empty ? 0 : 1;
scroll.style.minHeight = 0;
scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
dialog.Add(scroll);
if (entries == null || entries.Count == 0)
scroll.Add(Text("No completed runs yet. Your next run report will appear here."));
if (empty)
scroll.Add(Text("history: No completed runs (exit 1)"));
else for (int index = 0; index < entries.Count; index++)
{
var entry = entries[index];
if (entry == null) continue;
var item = new VisualElement();
item.AddToClassList("run-history-entry");
item.style.marginBottom = 16;
item.Add(Text($"{entry.distroName ?? entry.distroId} V{entry.distroVersion} / {entry.languages}"));
item.Add(Text($"Wave {entry.waveReached} reached / {entry.wavesCleared} cleared / seed {entry.seed}"));
@@ -100,7 +107,7 @@ namespace KernelPanic.UI
item.Add(copySeed);
scroll.Add(item);
}
var dismiss = new Button(close) { text = "Close [Esc]", name = "CloseRunHistory" };
var dismiss = new Button(close) { text = "[ Esc ] close", name = "CloseRunHistory" };
dismiss.AddToClassList("terminal-button");
dismiss.style.flexShrink = 0;
dialog.Add(dismiss);
+13 -3
View File
@@ -72,7 +72,8 @@ namespace KernelPanic.UI
body.AddToClassList("software-body");
// Break at a sentence boundary only. Never reinterpret effect amounts or conditions.
int split = displayRules.IndexOf(". ", System.StringComparison.Ordinal);
body.Add(Text(split < 0 ? displayRules : displayRules.Substring(0, split + 1), "software-effect"));
int lineNumber = 1;
body.Add(CodeLine(lineNumber++, Text(split < 0 ? displayRules : displayRules.Substring(0, split + 1), "software-effect")));
if (split >= 0)
{
string details = displayRules.Substring(split + 2);
@@ -86,10 +87,10 @@ namespace KernelPanic.UI
var rule = new VisualElement();
rule.AddToClassList("software-python-rule");
rule.Add(Text(line, "software-conditions"));
body.Add(rule);
body.Add(CodeLine(lineNumber++, rule));
}
}
else body.Add(Text(details, "software-conditions"));
else body.Add(CodeLine(lineNumber, Text(details, "software-conditions")));
}
target.Add(body);
@@ -111,5 +112,14 @@ namespace KernelPanic.UI
label.AddToClassList(className);
return label;
}
private static VisualElement CodeLine(int number, VisualElement content)
{
var row = new VisualElement();
row.AddToClassList("software-code-line");
row.Add(Text(number.ToString("00"), "software-line-number"));
row.Add(content);
return row;
}
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ namespace KernelPanic.UI
internal static readonly string[] Commands =
{
"./start_run", "ls ~/collection", "curl gacha.sh | sh", "dpkg-reconfigure", "history --runs", "shutdown -h now",
"cat /etc/cron.daily/quests"
"cat /etc/cron.daily/quests", "git log --pulls"
};
private readonly List<string> _history = new();
private readonly TextField _input;
+9 -104
View File
@@ -18,11 +18,14 @@ namespace KernelPanic.UI
if (sheet != null) root.styleSheets.Add(sheet);
StyleSheet readability = Resources.Load<StyleSheet>("Readability");
if (readability != null) root.styleSheets.Add(readability);
StyleSheet program = Resources.Load<StyleSheet>("TerminalProgram");
if (program != null) root.styleSheets.Add(program);
root.RegisterCallback<GeometryChangedEvent>(evt =>
{
root.EnableInClassList("compact", evt.newRect.width < 1100);
root.EnableInClassList("narrow", evt.newRect.width < 760);
root.EnableInClassList("short-screen", evt.newRect.height < 760);
root.EnableInClassList("very-short-screen", evt.newRect.height < 520);
});
AttachPreferences(root);
root.RegisterCallback<FocusInEvent>(evt =>
@@ -35,7 +38,7 @@ namespace KernelPanic.UI
scroll.contentContainer.Contains(control))
scroll.ScrollTo(control);
});
AttachHints(root);
SuppressAutomaticTooltips(root);
}
private static void AttachPreferences(VisualElement root)
@@ -106,110 +109,12 @@ namespace KernelPanic.UI
}, TrickleDown.TrickleDown);
}
// UI Toolkit's editor tooltip window is not available in standalone players.
// Use the same tooltip strings for pointer and keyboard inspection at runtime.
private static void AttachHints(VisualElement root)
// Dense terminal screens should never grow a new row merely because focus or the
// pointer moved. Keep tooltip text on controls for deliberate inspectors and tests,
// but suppress Unity's automatic floating tooltip window as well.
private static void SuppressAutomaticTooltips(VisualElement root)
{
var hint = new ScrollView(ScrollViewMode.Vertical) { focusable = false };
hint.AddToClassList("runtime-hint");
hint.style.display = DisplayStyle.None;
hint.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
hint.verticalScrollerVisibility = ScrollerVisibility.Auto;
hint.contentContainer.focusable = false;
hint.contentViewport.focusable = false;
foreach (var control in new VisualElement[] { hint.verticalScroller, hint.verticalScroller.slider,
hint.verticalScroller.lowButton, hint.verticalScroller.highButton })
control.focusable = false;
var body = new Label { pickingMode = PickingMode.Ignore, enableRichText = false, name = "RuntimeHintText" };
body.style.whiteSpace = WhiteSpace.Normal;
body.style.flexShrink = 0;
hint.Add(body);
VisualElement owner = null;
IVisualElementScheduledItem pending = null;
IVisualElementScheduledItem pendingHide = null;
IVisualElementScheduledItem refresh = null;
bool InsideHint(VisualElement element) => element == hint || (element != null && hint.Contains(element));
void Hide()
{
pending?.Pause();
pendingHide?.Pause();
refresh?.Pause();
owner = null;
hint.style.display = DisplayStyle.None;
}
void RefreshVisible()
{
if (owner?.panel == null || owner.resolvedStyle.display == DisplayStyle.None || string.IsNullOrWhiteSpace(owner.tooltip))
{ Hide(); return; }
body.text = owner.tooltip;
float width = Mathf.Max(1, Mathf.Min(380, root.layout.width - 24));
float heightLimit = Mathf.Max(1, root.layout.height - 24);
// Reserve the vertical scrollbar in the measurement so long descriptions wrap
// inside the viewport instead of growing the popup beyond the window edge.
float measured = body.MeasureTextSize(body.text, Mathf.Max(1, width - 44),
VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined).y;
float height = Mathf.Min(heightLimit, Mathf.Max(44, measured + 24));
hint.style.width = width;
hint.style.maxWidth = width;
hint.style.height = height;
hint.style.maxHeight = heightLimit;
Vector2 point = root.WorldToLocal(owner.worldBound.min);
hint.style.left = Mathf.Clamp(point.x, 12, Mathf.Max(12, root.layout.width - width - 12));
hint.style.top = Mathf.Clamp(point.y - height - 8, 12, Mathf.Max(12, root.layout.height - height - 12));
}
void Inspect(VisualElement element)
{
pendingHide?.Pause();
if (InsideHint(element)) return;
while (element != null && element != root && string.IsNullOrWhiteSpace(element.tooltip)) element = element.parent;
if (element == null || element == root)
{
// Allow the pointer to cross the small gap from the inspected item to its popup.
pendingHide = root.schedule.Execute(Hide).StartingIn(180);
return;
}
if (owner == element) return;
Hide();
owner = element;
pending = root.schedule.Execute(() =>
{
if (owner?.panel == null || owner.resolvedStyle.display == DisplayStyle.None) { Hide(); return; }
if (hint.parent == null) root.Add(hint);
hint.BringToFront();
hint.style.display = DisplayStyle.Flex;
hint.scrollOffset = Vector2.zero;
RefreshVisible();
refresh ??= root.schedule.Execute(RefreshVisible).Every(100);
refresh.Resume();
}).StartingIn(450);
}
root.RegisterCallback<PointerOverEvent>(evt => Inspect(evt.target as VisualElement));
root.RegisterCallback<FocusInEvent>(evt => Inspect(evt.target as VisualElement));
root.RegisterCallback<PointerLeaveEvent>(_ => Hide());
root.RegisterCallback<FocusOutEvent>(_ => Hide());
root.RegisterCallback<PointerDownEvent>(evt => { if (!InsideHint(evt.target as VisualElement)) Hide(); }, TrickleDown.TrickleDown);
root.RegisterCallback<WheelEvent>(evt => { if (!InsideHint(evt.target as VisualElement)) Hide(); }, TrickleDown.TrickleDown);
root.RegisterCallback<KeyDownEvent>(evt =>
{
var focused = root.focusController?.focusedElement as VisualElement;
if (owner != null && hint.style.display.value != DisplayStyle.None &&
(focused == owner || (focused != null && owner.Contains(focused))) &&
(evt.keyCode == KeyCode.PageDown || evt.keyCode == KeyCode.PageUp))
{
float direction = evt.keyCode == KeyCode.PageDown ? 1 : -1;
hint.scrollOffset = new Vector2(0, Mathf.Clamp(hint.scrollOffset.y + direction * hint.contentViewport.layout.height * 0.8f,
0, hint.verticalScroller.highValue));
evt.StopImmediatePropagation();
return;
}
Hide();
}, TrickleDown.TrickleDown);
root.RegisterCallback<DetachFromPanelEvent>(_ => Hide());
root.RegisterCallback<TooltipEvent>(evt => evt.StopImmediatePropagation(), TrickleDown.TrickleDown);
}
public static void SetDistro(VisualElement root, DistroDefinition distro)