Implement more QoL features and rebalances

This commit is contained in:
2026-10-25 02:16:30 +02:00
parent 0578913451
commit 53f831d91e
220 changed files with 14700 additions and 420 deletions
+625
View File
@@ -0,0 +1,625 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using KernelPanic.Combat;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
using KernelPanic.Run;
using KernelPanic.UI;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
namespace KernelPanic.Editor
{
/// <summary>
/// Bounded, repeatable bot benchmarks using the real Play Mode combat loop. Run in an
/// isolated project copy: -batchmode -executeMethod KernelPanic.Editor.BalanceComparison.RunBatch.
/// Omit -quit: this tool exits when Play Mode work and report writes finish.
/// </summary>
[InitializeOnLoad]
public static class BalanceComparison
{
private const string PendingKey = "KernelPanic.BalanceComparison.Pending";
private static Batch _batch;
static BalanceComparison()
{
EditorApplication.playModeStateChanged += OnPlayModeChanged;
EditorApplication.update += Update;
}
public static void RunBatch()
{
if (!Application.isBatchMode || EditorApplication.isPlayingOrWillChangePlaymode)
throw new InvalidOperationException("Run balance comparisons in a separate batch editor, outside Play Mode.");
// Validate arguments before replacing the disposable batch editor's scene.
Options.Parse(Environment.GetCommandLineArgs());
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
SessionState.SetBool(PendingKey, true);
EditorApplication.isPlaying = true;
}
private static void OnPlayModeChanged(PlayModeStateChange state)
{
if (state != PlayModeStateChange.EnteredPlayMode || !SessionState.GetBool(PendingKey, false)) return;
SessionState.SetBool(PendingKey, false);
try { _batch = new Batch(Options.Parse(Environment.GetCommandLineArgs())); }
catch (Exception exception) { Fail(exception); }
}
private static void Update()
{
if (_batch == null || !EditorApplication.isPlaying) return;
try
{
if (!_batch.Tick()) return;
_batch.Dispose();
_batch = null;
EditorApplication.Exit(0);
}
catch (Exception exception) { Fail(exception); }
}
private static void Fail(Exception exception)
{
Debug.LogException(exception);
_batch?.Dispose();
_batch = null;
EditorApplication.Exit(1);
}
[Serializable]
public sealed class Options
{
public int[] seeds = CreateSeeds(30);
public int[] packageLevels = { 0, 5 };
public bool[] shoppingPolicies = { false, true };
public int maxWaves = 10;
public int maxRounds = 100;
public WaveRoute route = WaveRoute.Repair;
public bool prefetch = true;
public string outputDirectory = "Artifacts/Balance";
public static Options Parse(string[] args)
{
var result = new Options();
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "-balanceSeeds": result.seeds = Integers(Value(args, ref i)); break;
case "-balanceSeedCount": result.seeds = CreateSeeds(int.Parse(Value(args, ref i), CultureInfo.InvariantCulture)); break;
case "-balancePackageLevels": result.packageLevels = Integers(Value(args, ref i)); break;
case "-balanceShop":
result.shoppingPolicies = Value(args, ref i).ToLowerInvariant() switch
{
"both" => new[] { false, true },
"none" => new[] { false },
"upgrades" => new[] { true },
_ => throw new ArgumentException("balanceShop must be both, none, or upgrades.")
};
break;
case "-balanceWaves": result.maxWaves = int.Parse(Value(args, ref i), CultureInfo.InvariantCulture); break;
case "-balancePrefetch": result.prefetch = bool.Parse(Value(args, ref i)); break;
case "-balanceRoute":
result.route = Value(args, ref i).ToLowerInvariant() switch
{
"repair" => WaveRoute.Repair,
"challenge" => WaveRoute.Challenge,
_ => throw new ArgumentException("balanceRoute must be repair or challenge.")
};
break;
case "-balanceRounds": result.maxRounds = int.Parse(Value(args, ref i), CultureInfo.InvariantCulture); break;
case "-balanceOutput": result.outputDirectory = Value(args, ref i); break;
}
}
if (result.seeds.Length == 0 || result.maxWaves < 1 || result.maxWaves > 100 || result.maxRounds < 1 || result.maxRounds > 1000)
throw new ArgumentException("Specify at least one seed, 1..100 waves, and 1..1000 total rounds per run.");
if (result.packageLevels.Length == 0 || result.packageLevels.Any(level => level < 0 || level > PackageTuning.MaxPackageLevel))
throw new ArgumentException($"Package levels must be 0..{PackageTuning.MaxPackageLevel}.");
result.outputDirectory = Path.GetFullPath(result.outputDirectory);
return result;
}
// Stable explicit prefix preserves the old three-seed sample. The remaining
// sequence is independent of both Unity's RNG and the runtime RNG algorithm.
public static int[] CreateSeeds(int count)
{
if (count < 1 || count > 1000) throw new ArgumentOutOfRangeException(nameof(count), "Seed count must be 1..1000.");
var result = new int[count];
int[] original = { 17, 101, 2027 };
for (int i = 0; i < count; i++) result[i] = i < original.Length ? original[i] : unchecked((int)(0x6D2B79F5u * (uint)(i - 2)));
return result;
}
private static int[] Integers(string value) => value.Split(',').Select(item => int.Parse(item, CultureInfo.InvariantCulture)).Distinct().ToArray();
private static string Value(string[] args, ref int index)
{
if (++index >= args.Length) throw new ArgumentException("Missing balance option value.");
return args[index];
}
}
[Serializable]
public sealed class Scenario
{
public string distroId;
public int version;
public Language primary;
public Language secondary;
public string[] packages;
public int packageLevel = 5;
public bool shop;
public string Label => $"{distroId} V{version} / {primary}+{secondary} / {(packages.Length == 0 ? "none" : string.Join("+", packages) + " L" + packageLevel)} / {(shop ? "upgrade-shop" : "no-shop")}";
}
public static List<Scenario> CreateScenarios(DistroDatabase distros) => CreateScenarios(distros, new Options());
public static List<Scenario> CreateScenarios(DistroDatabase distros, Options options)
{
var result = new List<Scenario>();
foreach (var distro in distros.AllDistros.Where(d => d != null).OrderBy(d => d.Id, StringComparer.Ordinal))
{
Add(distro.Id, 1, distro.PrimaryLanguage, distro.SecondaryLanguage);
Add(distro.Id, 1, distro.PrimaryLanguage, distro.SecondaryLanguage, "pkg_fedora_dnf");
}
var gentoo = distros.FindById("gentoo") ?? throw new InvalidOperationException("Gentoo is not registered.");
Add("gentoo", 5, gentoo.PrimaryLanguage, gentoo.SecondaryLanguage);
Add("gentoo", 5, gentoo.PrimaryLanguage, gentoo.SecondaryLanguage, "pkg_fedora_dnf");
Add("gentoo", 5, gentoo.PrimaryLanguage, gentoo.SecondaryLanguage, "pkg_zram");
Add("gentoo", 5, gentoo.PrimaryLanguage, gentoo.SecondaryLanguage, "pkg_zram", "pkg_fedora_dnf");
Add("gentoo", 5, Language.C, Language.Rust);
Add("gentoo", 5, Language.C, Language.Rust, "pkg_fedora_dnf");
Add("gentoo", 5, Language.Python, Language.JavaScript);
Add("gentoo", 5, Language.Python, Language.JavaScript, "pkg_fedora_dnf");
return result;
void Add(string distro, int version, Language primary, Language secondary, params string[] packages)
{
// Package-free controls are not duplicated for levels that cannot affect them.
foreach (int level in packages.Length == 0 ? new[] { 0 } : options.packageLevels)
foreach (bool shop in options.shoppingPolicies)
result.Add(new Scenario { distroId = distro, version = version, primary = primary, secondary = secondary,
packages = packages, packageLevel = level, shop = shop });
}
}
public static List<CardDefinition> BuildDeck(DistroDefinition distro, LanguageDeckDatabase languages, Scenario scenario)
{
var cards = distro.ExclusiveCards.Where(card => card != null && !card.IsRunOnly).Take(4).ToList();
if (cards.Count != 4) throw new InvalidOperationException($"{distro.Id} needs four authored exclusive cards.");
foreach (var language in new[] { scenario.primary, scenario.secondary })
{
var starter = languages.FindByLanguage(language) ?? throw new InvalidOperationException($"Missing {language} starter.");
foreach (var entry in starter.Entries)
{
if (entry.Card == null || entry.Card.IsRunOnly || entry.Count < 1)
throw new InvalidOperationException($"Invalid {language} starter entry.");
for (int i = 0; i < entry.Count; i++) cards.Add(entry.Card);
}
}
return cards;
}
[Serializable]
public sealed class RunResult
{
public string scenario;
public int seed;
public string[] startingDeck;
public int rounds;
public int wavesCleared;
public int uptimeRemaining;
public int maxUptime;
public long enemyUptimeDamage;
public long enemyShieldDamage;
public long playerUptimeDamage;
public int cardsPlayed;
public int turnsEnded;
public long unusedCycles;
public int prefetches;
public int turnsWithUnusedCycles;
public int emptyHandTurns;
public int emptyHandWithUnusedCyclesTurns;
public int noUsableCardsWithUnusedCyclesTurns;
public int turnPlayCapHits;
public int repositoryVisits;
public int offersPurchased;
public int drawRidersPurchased;
public long bitsSpent;
public string stopReason;
public string traceHash;
public bool repeatVerified;
public double DamagePerRound => rounds == 0 ? 0 : (double)enemyUptimeDamage / rounds;
}
[Serializable]
public sealed class Report
{
public int schemaVersion = 4;
public string generatedUtc = DateTime.UtcNow.ToString("o");
public string unityVersion = Application.unityVersion;
public string policy = "Greedy preview value per (cost+1), lowest-uptime target, hand-order ties; 64 plays/round cap. First four authored distro exclusives plus both language starter decks. Paired no-shop and upgrade-shop policies, package levels 0 and 5 by default. Upgrade-shop buys affordable offers in this order: healing at <=50% uptime, draw riders, magnitude, cost reduction, max uptime, RAM, Cycles, cards, then useful healing; offer-order ties; no rerolls/removals. Actual Play Mode combat; death visuals acknowledged on the next editor update. First seed repeats for every scenario.";
public string limitations = "A bounded heuristic benchmark, not optimal play or a balance verdict. Conditional/draw/setup effects are undervalued during combat; fixed exclusive choice; upgrade-first shopping is not optimal deckbuilding; different loadouts consume RNG differently. Wave/round caps are censored survivors, not wins. Uptime damage excludes shield and overkill; partial final rounds count. Resource metrics sample explicitly ended Execute turns only: native clears and mid-turn defeats are excluded. Empty hand does not prove lack of draw is the cause of a defeat.";
public Options options;
public List<Scenario> scenarios;
public List<RunResult> runs = new();
public List<EditorDiagnostic> editorDiagnostics = new();
}
[Serializable]
public sealed class EditorDiagnostic
{
public string message;
public string stackTrace;
}
// Unity 6000.4.8f1 can throw this from its delayed search-index startup after
// EnteredPlayMode. Require the complete editor-only call path: a game exception,
// a user-initiated search, or an additional unknown frame must still fail the run.
public static bool IsKnownSearchStartupException(string message, string stackTrace, LogType type)
{
if (type != LogType.Exception || message == null
|| !message.StartsWith("ArgumentOutOfRangeException:", StringComparison.Ordinal)
|| string.IsNullOrWhiteSpace(stackTrace)) return false;
string[] required =
{
"UnityEditor.Search.SearchDatabase+<EnumerateAll>",
"UnityEditor.Search.SearchDatabase.GetDefaultSearchDatabase",
"UnityEditor.Search.SearchInit.IndexationOnStartup",
"UnityEditor.EditorApplication.Internal_CallDelayFunctions"
};
if (required.Any(frame => stackTrace.IndexOf(frame, StringComparison.Ordinal) < 0)) return false;
foreach (string rawLine in stackTrace.Split('\n'))
{
string frame = rawLine.Trim();
if (frame.Length == 0) continue;
if (frame.StartsWith("at ", StringComparison.Ordinal)) frame = frame.Substring(3);
if (frame.StartsWith("System.Collections.Generic.List`1", StringComparison.Ordinal)
|| frame.StartsWith("System.Linq.Enumerable.", StringComparison.Ordinal)
|| required.Any(prefix => frame.StartsWith(prefix, StringComparison.Ordinal))) continue;
return false;
}
return true;
}
public static void RecordTurnEnd(RunResult result, int cycles, int handCount, int usableCardCount, bool playCapReached)
{
int unused = Math.Max(0, cycles);
result.turnsEnded++;
result.unusedCycles += unused;
if (unused > 0) result.turnsWithUnusedCycles++;
if (handCount == 0) result.emptyHandTurns++;
if (unused > 0 && handCount == 0) result.emptyHandWithUnusedCyclesTurns++;
// Usable ignores price: cards that merely cost too much do not become
// evidence of a draw bottleneck. Tokens, broken and locked cards do.
if (unused > 0 && usableCardCount == 0) result.noUsableCardsWithUnusedCyclesTurns++;
if (playCapReached) result.turnPlayCapHits++;
}
public static int RepositoryPriority(RepositoryOffer offer, CombatantState player)
{
if (offer == null || offer.Sold) return 0;
if (offer.Kind == RepositoryOfferKind.CardUpgrade)
return offer.CardUpgradeKind switch
{
CardUpgradeKind.DrawRider => 90,
CardUpgradeKind.MagnitudeUp => 80,
CardUpgradeKind.CostDown => 70,
_ => 0
};
if (offer.Kind == RepositoryOfferKind.NewCard) return 20;
if (offer.Kind != RepositoryOfferKind.StatUpgrade) return 0;
return offer.StatUpgradeKind switch
{
RunStatUpgradeKind.Heal => player == null || player.CurrentUptime >= player.MaxUptime ? 0
: player.CurrentUptime <= player.MaxUptime / 2 ? 100 : 10,
RunStatUpgradeKind.MaxUptime => 60,
RunStatUpgradeKind.Ram => 50,
RunStatUpgradeKind.MaxCycles => 40,
_ => 0
};
}
public static string ToMarkdown(Report report)
{
var text = new StringBuilder("# Seeded combat comparison\n\n");
text.AppendLine(report.policy).AppendLine().AppendLine(report.limitations).AppendLine();
text.AppendLine($"Encounter revision: seeded campaign variants, then endless. Route: {report.options.route}. Repair restores up to {RunJourney.RepairUptime} Uptime on departure; challenge adds a modified Daemon and awards Bits plus a draw rider on clear. Build rewards take Bits. Prefetch enabled: {report.options.prefetch}; used only when the bot cannot play another card. Total prefetches: {report.runs.Sum(run => run.prefetches)}. Milestone automatically continues into endless when the wave cap exceeds five. These results are not directly comparable to the old structural encounter benchmark.").AppendLine();
text.AppendLine($"Seeds: {string.Join(", ", report.options.seeds)}. Limits: {report.options.maxWaves} waves / {report.options.maxRounds} total rounds. Unity {report.unityVersion}.").AppendLine();
text.AppendLine($"Package levels: {string.Join(", ", report.options.packageLevels)}. Shop policies: {string.Join(", ", report.options.shoppingPolicies.Select(shop => shop ? "upgrade-shop" : "no-shop"))}.").AppendLine();
text.AppendLine("| Loadout | Runs | Uptime damage / round | Mean rounds | Mean waves cleared | Wave cap reached | Round cap alive | Died | Repeat checked |");
text.AppendLine("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |");
foreach (var group in report.runs.GroupBy(run => run.scenario))
{
long rounds = group.Sum(run => (long)run.rounds);
double damage = rounds == 0 ? 0 : group.Sum(run => run.enemyUptimeDamage) / (double)rounds;
text.AppendLine(FormattableString.Invariant($"| {group.Key} | {group.Count()} | {damage:0.00} | {group.Average(run => run.rounds):0.00} | {group.Average(run => run.wavesCleared):0.00} | {group.Count(run => run.stopReason == "wave-cap")} | {group.Count(run => run.stopReason == "round-cap")} | {group.Count(run => run.stopReason == "defeat")} | {group.Count(run => run.repeatVerified)} |"));
}
text.AppendLine().AppendLine("Damage/round is total observed enemy uptime damage divided by total rounds, including partial defeat/clear rounds. JSON contains per-seed outcomes, exact starter decks, shield damage, incoming uptime damage, and deterministic event trace hashes. Every scenario's first seed is replayed and must match before this report is written.");
text.AppendLine().AppendLine("## Card flow and repository use").AppendLine();
text.AppendLine("| Loadout | Ended turns | Unused Cycles / ended turn | Empty hand % | Empty hand + unused Cycles % | No usable cards + unused Cycles % | Plays / round | Purchases / run | Draw riders / run | Bits spent / run | Play-cap hits |");
text.AppendLine("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |");
foreach (var group in report.runs.GroupBy(run => run.scenario))
{
long ended = group.Sum(run => (long)run.turnsEnded);
long rounds = group.Sum(run => (long)run.rounds);
double perTurn(long value) => ended == 0 ? 0 : value / (double)ended;
double plays = rounds == 0 ? 0 : group.Sum(run => (long)run.cardsPlayed) / (double)rounds;
text.AppendLine(FormattableString.Invariant($"| {group.Key} | {ended} | {perTurn(group.Sum(run => run.unusedCycles)):0.00} | {100 * perTurn(group.Sum(run => (long)run.emptyHandTurns)):0.0} | {100 * perTurn(group.Sum(run => (long)run.emptyHandWithUnusedCyclesTurns)):0.0} | {100 * perTurn(group.Sum(run => (long)run.noUsableCardsWithUnusedCyclesTurns)):0.0} | {plays:0.00} | {group.Average(run => run.offersPurchased):0.00} | {group.Average(run => run.drawRidersPurchased):0.00} | {group.Average(run => run.bitsSpent):0.00} | {group.Sum(run => run.turnPlayCapHits)} |"));
}
text.AppendLine().AppendLine("All percentages use explicitly ended turns, not rounds or runs. Unused Cycles are sampled immediately before End Turn, before deferred cards can refund resources. No usable cards excludes tokens, broken and locked cards but ignores affordability, so expensive cards are not mistaken for an empty hand. Wave-clearing native plays and mid-turn defeats are not sampled. A positive empty-hand/unused-Cycles rate suggests an investigation, not an automatic draw buff; inspect paired no-shop/shop and level-0/level-5 outcomes, play-cap hits, and per-seed JSON together.");
if (report.editorDiagnostics.Count > 0)
text.AppendLine().AppendLine($"Editor diagnostics: {report.editorDiagnostics.Count} known Unity SearchDatabase startup exception(s) were recorded separately from gameplay failures. Their complete messages and editor-only stacks remain in the JSON and editor log. This benchmark does not validate Unity's search index; all other Error/Exception/Assert logs fail the run.");
return text.ToString();
}
private sealed class Batch : IDisposable
{
private readonly Report _report;
private readonly DistroDatabase _distros = Asset<DistroDatabase>("Assets/Data/Distros/DistroDatabase.asset");
private readonly LanguageDeckDatabase _languages = Asset<LanguageDeckDatabase>("Assets/Data/Cards/Languages/LanguageDeckDatabase.asset");
private readonly PackageDatabase _packages = Asset<PackageDatabase>("Assets/Data/Packages/PackageDatabase.asset");
private readonly CardDatabase _cards = Asset<CardDatabase>("Assets/Data/Cards/CardDatabase.asset");
private readonly bool _previousMotion;
private readonly StringBuilder _trace = new();
private GameObject _owner;
private RunManager _run;
private CombatManager _combat;
private RunResult _current;
private RunResult _repeatOf;
private int _scenarioIndex;
private int _seedIndex;
private double _lastProgress;
private bool _writeComplete;
private bool _roundCapReached;
private int _roundCapUptime;
private string _runtimeError;
public Batch(Options options)
{
_report = new Report { options = options, scenarios = CreateScenarios(_distros, options) };
_previousMotion = UIPreferences.ReducedMotion;
UIPreferences.ReducedMotion = true;
GameEvents.PhaseChanged += OnPhase;
GameEvents.DamageDealt += OnDamage;
GameEvents.CardPlayed += OnCard;
Application.logMessageReceived += OnRuntimeLog;
Begin();
}
public bool Tick()
{
if (_writeComplete) return true;
if (_runtimeError != null) throw new InvalidOperationException("Runtime error during balance comparison: " + _runtimeError);
if (_roundCapReached) { Complete("round-cap"); return false; }
if (EditorApplication.timeSinceStartup - _lastProgress > 60)
throw new TimeoutException($"Combat stalled: {_current.scenario}, seed {_current.seed}, phase {_combat.CurrentPhase}.");
// Replace only the absent presentation acknowledgment, never the death logic.
foreach (var enemy in _combat.Enemies.ToArray())
{
if (!enemy.State.IsDefeated || enemy.PendingRevive) continue;
_combat.QueueDefeatedCombatantForRemoval(enemy.State);
GameEvents.RaiseCombatantDeathVisualCompleted(new CombatantDeathVisualCompletedEvent(enemy.State));
}
if (_combat.RunLost) { Complete("defeat"); return false; }
if (_combat.AwaitingWaveContinue)
{
if (_run.WavesCleared >= _report.options.maxWaves) { Complete("wave-cap"); return false; }
if (_current.rounds >= _report.options.maxRounds) { Complete("round-cap"); return false; }
VisitRepository();
if (_run.CampaignChoicePending) _combat.ContinueEndless();
else _combat.ContinueToNextWave();
Progress();
return false;
}
if (!_combat.CanSurrenderRun) return false;
int targetIndex = FindTarget();
if (targetIndex >= 0) _combat.SelectEnemy(targetIndex);
CardInstance chosen = null;
double best = double.NegativeInfinity;
var target = targetIndex >= 0 ? _combat.Enemies[targetIndex].State : null;
foreach (var card in _combat.HandController.Cards)
{
if (card.Definition == null || card.Definition.IsToken || card.IsBroken || card.IsLocked
|| _combat.GetDisplayedPlayCost(card) > _combat.PlayerState.Cycles) continue;
var preview = CardPreviewService.Build(_combat, card, target);
double damage = (preview.MinimumDamage + (double)preview.MaximumDamage) / 2;
double score = (damage + preview.Shield * 0.7 + preview.Heal * 1.5 + preview.Repairs * 3 + 1) / (preview.Cost + 1);
if (score <= best) continue;
best = score;
chosen = card;
}
if (chosen != null && _combat.CardsPlayedThisRound < 64 && _combat.PlayCard(chosen)) { Progress(); return false; }
if (_report.options.prefetch && _combat.CardsPlayedThisRound < 64 && _combat.TryPrefetch())
{
_current.prefetches++;
_trace.Append("prefetch;");
Progress(); return false;
}
int usableCards = _combat.HandController.Cards.Count(card => card?.Definition != null
&& !card.Definition.IsToken && !card.IsBroken && !card.IsLocked);
RecordTurnEnd(_current, _combat.PlayerState.Cycles, _combat.HandController.Cards.Count, usableCards, _combat.CardsPlayedThisRound >= 64);
_trace.Append("end:").Append(_combat.PlayerState.Cycles).Append(':').Append(_combat.HandController.Cards.Count).Append(':').Append(usableCards).Append(';');
_combat.EndPlayerTurn();
Progress();
return false;
}
private void VisitRepository()
{
_run.GenerateRepositoryOffers(_cards, _languages);
if (_run.BuildRewardPending) _run.ClaimBuildReward(null, CardUpgradeKind.MagnitudeUp, true);
_run.SelectRoute(_report.options.route);
_current.repositoryVisits++;
if (!_report.scenarios[_scenarioIndex].shop) return;
// The real market and public purchase method determine affordability,
// upgrades, deck growth and resource changes. No injected currency.
while (true)
{
var chosen = _run.RepositoryOffers.Where(offer => !offer.Sold && offer.Price <= _run.Bits)
.Select(offer => new { Offer = offer, Priority = RepositoryPriority(offer, _combat.PlayerState) })
.Where(item => item.Priority > 0).OrderByDescending(item => item.Priority).FirstOrDefault();
if (chosen == null) break;
var offer = chosen.Offer;
if (!_run.BuyOffer(offer, _combat.PlayerState))
throw new InvalidOperationException($"Affordable repository offer rejected: {offer.DisplayName}.");
_current.offersPurchased++;
_current.bitsSpent += offer.Price;
if (offer.Kind == RepositoryOfferKind.CardUpgrade && offer.CardUpgradeKind == CardUpgradeKind.DrawRider)
_current.drawRidersPurchased++;
_trace.Append("buy:").Append(offer.Kind).Append(':').Append(offer.CommandName).Append(':')
.Append(offer.CardUpgradeKind).Append(':').Append(offer.StatUpgradeKind).Append(':').Append(offer.Price).Append(';');
}
}
private int FindTarget()
{
int chosen = -1;
for (int i = 0; i < _combat.Enemies.Count; i++)
{
var enemy = _combat.Enemies[i];
if (enemy.State.IsDefeated) continue;
if (chosen < 0 || enemy.State.CurrentUptime < _combat.Enemies[chosen].State.CurrentUptime) chosen = i;
}
return chosen;
}
private void Begin()
{
var scenario = _report.scenarios[_scenarioIndex];
var distro = _distros.FindById(scenario.distroId);
var deck = BuildDeck(distro, _languages, scenario);
var equipment = scenario.packages.Select(id => new PackageInstance(_packages.FindById(id)
?? throw new InvalidOperationException($"Missing package {id}"), scenario.packageLevel)).ToArray();
int seed = _report.options.seeds[_seedIndex];
_current = new RunResult { scenario = scenario.Label, seed = seed, startingDeck = deck.Select(card => card.Id).ToArray() };
_trace.Clear();
_roundCapReached = false;
_owner = new GameObject("Isolated balance comparison");
_run = _owner.AddComponent<RunManager>();
_combat = _owner.AddComponent<CombatManager>();
_combat.SetGeneratedCardPool(_cards.AllCards);
_combat.CombatLog += OnLog;
var config = new RunConfig(distro, scenario.primary, scenario.secondary, deck, equipment, seed, scenario.version);
_run.StartRun(config);
_combat.StartCombat(config);
Progress();
}
private void Complete(string reason)
{
_current.stopReason = reason;
_current.wavesCleared = _run.WavesCleared;
_current.uptimeRemaining = _roundCapReached ? _roundCapUptime : _combat.PlayerState.CurrentUptime;
_current.maxUptime = _combat.PlayerState.MaxUptime;
using (var hash = SHA256.Create())
_current.traceHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(_trace.ToString()))).Replace("-", "").ToLowerInvariant();
DestroyRun();
if (_repeatOf != null)
{
if (JsonUtility.ToJson(_repeatOf) != JsonUtility.ToJson(_current))
throw new InvalidOperationException($"Non-reproducible combat: {_current.scenario}, seed {_current.seed}. First {_repeatOf.traceHash}, repeat {_current.traceHash}.");
_repeatOf.repeatVerified = true;
_repeatOf = null;
}
else
{
_report.runs.Add(_current);
Debug.Log($"Balance: {_current.scenario}, seed {_current.seed}: {reason}, {_current.wavesCleared} waves, {_current.rounds} rounds, {_current.enemyUptimeDamage} uptime damage.");
if (_seedIndex == 0) { _repeatOf = _current; Begin(); return; }
}
if (++_seedIndex >= _report.options.seeds.Length) { _seedIndex = 0; _scenarioIndex++; }
if (_scenarioIndex < _report.scenarios.Count) { Begin(); return; }
Directory.CreateDirectory(_report.options.outputDirectory);
File.WriteAllText(Path.Combine(_report.options.outputDirectory, "balance-comparison.json"), JsonUtility.ToJson(_report, true), new UTF8Encoding(false));
File.WriteAllText(Path.Combine(_report.options.outputDirectory, "balance-comparison.md"), ToMarkdown(_report), new UTF8Encoding(false));
Debug.Log($"Balance comparison complete: {_report.runs.Count} measured runs, {_report.scenarios.Count} verified repeats. {_report.options.outputDirectory}");
_writeComplete = true;
}
private void OnPhase(PhaseChangedEvent payload)
{
if (_current == null || _roundCapReached) return;
// Capture the completed final round before the next allocation's status/draw
// effects. The next editor update disposes the rig; ignore that allocation.
if (payload.NextPhase == TurnPhase.Allocate && _current.rounds >= _report.options.maxRounds)
{
_roundCapUptime = _combat.PlayerState.CurrentUptime;
_roundCapReached = true;
return;
}
if (payload.NextPhase == TurnPhase.Execute) _current.rounds++;
_trace.Append("phase:").Append(payload.NextPhase).Append(';');
Progress();
}
private void OnDamage(DamageDealtEvent payload)
{
if (_combat?.PlayerState == null || _roundCapReached) return;
if (payload.Target == _combat.PlayerState) _current.playerUptimeDamage += payload.UptimeDamage;
else if (_combat.Enemies.Any(enemy => enemy.State == payload.Target))
{
_current.enemyUptimeDamage += payload.UptimeDamage;
_current.enemyShieldDamage += payload.ShieldDamage;
}
_trace.Append("damage:").Append(payload.Target == _combat.PlayerState ? "player" : "enemy")
.Append(':').Append(payload.UptimeDamage).Append(':').Append(payload.ShieldDamage).Append(':').Append(payload.WasCritical).Append(';');
Progress();
}
private void OnCard(CardPlayedEvent payload)
{
_current.cardsPlayed++;
_trace.Append("play:").Append(payload.Card.Definition.Id).Append(':').Append(_combat.SelectedEnemyIndex).Append(';');
}
private void OnLog(string message)
{
if (!_roundCapReached) _trace.Append(message).Append('\n');
}
private void Progress() => _lastProgress = EditorApplication.timeSinceStartup;
private void OnRuntimeLog(string message, string stackTrace, LogType type)
{
if (IsKnownSearchStartupException(message, stackTrace, type))
{
_report.editorDiagnostics.Add(new EditorDiagnostic { message = message, stackTrace = stackTrace });
return;
}
if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert)
_runtimeError ??= message + "\n" + stackTrace;
}
private void DestroyRun()
{
if (_combat != null) _combat.CombatLog -= OnLog;
if (_owner != null) UnityEngine.Object.DestroyImmediate(_owner);
_owner = null;
_run = null;
_combat = null;
}
public void Dispose()
{
GameEvents.PhaseChanged -= OnPhase;
GameEvents.DamageDealt -= OnDamage;
GameEvents.CardPlayed -= OnCard;
Application.logMessageReceived -= OnRuntimeLog;
DestroyRun();
UIPreferences.ReducedMotion = _previousMotion;
}
private static T Asset<T>(string path) where T : UnityEngine.Object =>
AssetDatabase.LoadAssetAtPath<T>(path) ?? throw new InvalidOperationException($"Missing asset: {path}");
}
}
}