Sim Lab

In short

The Sim Lab is a set of bots that play Roguelike Home Run Derby so a change can be judged over thousands of runs instead of one playtest. Two of its three forms never render anything: they run the game’s own rules (pitcher AI, the real bat, ball flight, scoring, coins, shop, unlocks) in plain code from Scripts/Sim/, either on a live grid in the Editor window or as a headless batch that writes an HTML report. The third, AutoPilot (F1 > BOT), lets a bot play the real game end to end and counts errors, hitches and frame rate. Batches are seeded: the same seed on the same code plays exactly the same runs.

How it works

Three ways to run it

WhereWhat you seeGood for
Sim Lab window (Tools > Home Run Derby > Sim Lab > Open Sim Lab)A grid of 1x1 to 5x5 tiles, each playing a full runWatching a setup play out; comparing skills, parks, difficulties or shop styles side by side
Batch + report (RUN BATCH (report) in the window, Tools > Home Run Derby > Sim Lab > Run Standard Batch (report), or headless SimLabCli.Run)report.html plus runs.csv, innings.csv, careers.csv in SimResults/<date-time>/Balance numbers: win rates per park / difficulty / skill, where runs end, items, economy, pace, career pacing
AutoPilot in the real game (Play mode, F1 > BOT)The game playing itself: cutscenes, camera, replays, shop, resultsSoak testing: leave it running, it counts errors and exceptions, hitches and FPS, and writes soak-log.txt

How a bot bats (TierBot.Decide)

Every pitch, the bot gets the PitchData, the CountState and a System.Random, and returns a BotDecision: take, or swing at time press with aim aim (plate plane, metres) and hitAim (the held A / D, W / S direction; always zero for TierBot).

  1. Read the location. seen = PlateLocation2D + Gauss2 x judgeSigmaM (x1.5 when the ball moves late: Wiffle, Anti-Gravity, Sticky, Headwind, Tailwind). looksStrike = StrikeZone.Contains(seen).
  2. Swing or take. Looks a strike: swing chance 1 - takeInZone (with two strikes 1 - takeInZone x 0.3). Looks a ball: swing chance chase, or chaseTwoStrikes with two strikes.
  3. Pick a target. The real plate location, or, when the pitch carries decoys and a roll beats decoyFool, one decoy’s position (Special Balls).
  4. Timing. sigma = timingSigmaMs (+ movingTimingMs if it moves) (+ ghostTimingMs if Ghost); bias = timingBiasMs (+ superFastLateMs if Super Fast). press = ArrivalTime + IdealPressOffset + (bias + Gauss x sigma) / 1000.
  5. Aim. aim = target + Gauss2 x (aimSigmaM + movingAimM if it moves).

SimCalibration.IdealPressOffset is measured once per session from the real bat: for every pitcher, six pitches at 10 s, the in-zone ones scanned by TimingWindowScanner.Scan, and the median of bestPress - ArrivalTime is kept (fallback -0.12 s if nothing scans). The docs quote about -121 ms; SimTest only requires it to fall between -40 and -250 ms.

In the sim the swing itself goes through the real bat: TimingWindowScanner.Prepare(pitch, stats, aim) then TrySwing(press, out contact) (the scanner’s frame-by-frame test swing, made public in #47). A contact goes to the swing model (MainSwingModel = SwingResolver.FromContact), then HitPhysics.Simulate, ScoreCalculator.Score and HitTally.Build (for the big-moment count), exactly as in the game (Batting Explained, Hit Physics, Scoring).

The skill tiers (BotSkill.For)

TiertimingSigmaMstimingBiasMsaimSigmaMjudgeSigmaMchasechaseTwoStrikestakeInZonemovingTimingMsmovingAimMghostTimingMsdecoyFoolsuperFastLateMs
NOVICE60120.150.180.450.60.25350.08400.635
ROOKIE4260.100.120.350.50.2250.06300.525
AVERAGE2630.070.080.250.40.12160.04200.3515
GOOD1510.0450.050.150.30.07100.025120.28
PRO800.0250.030.080.20.0450.01560.083
YOUfittedfittedfitted0.01fittedfittedfittedfittednearest tiernearest tiernearest tiernearest tier

Timing in ms (one standard deviation; bias + is late), distances in metres. The class comment calibrates the aim numbers to a player who can see where the ball will cross (the TIMING RING, off by default); NOVICE is a first-timer without it. The comment also says a GREEN window is about 14 ms wide at centre and that SwingResolver’s own tuning note puts a casual player at about 35 ms and 7 cm, between ROOKIE and AVERAGE.

The YOU bot (YouBot)

YOU is fitted to a real player’s Swing Log (swings.csv, read by column name from SwingLog.Header, so later columns never shift it). It needs MinSwings = 30 swings; under that BotSkill.For(You) returns an AVERAGE bot renamed YOU with fitted = false, and the window and report say “no log yet: plays as Average”.

The fit (YouBot.Fit):

  • swings on pitches that don’t move late (or all swings if fewer than 15), timing errors press_ms / 1000 - IdealPressOffset within +-250 ms; if fewer than 15 usable timing samples remain the fit also gives up (plays as Average); timingBiasMs = median, timingSigmaMs = robust sigma (1.4826 x median absolute deviation);
  • aimSigmaM = root-mean of the robust sigmas of bat_aim - plate in x and y;
  • the rest starts from the fixed tier whose timingSigmaMs is nearest, then judgeSigmaM = 0.01 (the chase and take rates already hold the misreads), chase from pitches outside the zone with under two strikes (needs 10), chaseTwoStrikes from those with two strikes (needs 8), takeInZone from in-zone pitches under two strikes (needs 10), movingTimingMs = extra robust sigma on moving pitches (needs 12).

YouBot.UseFile(path) points it at someone else’s swings.csv (the window’s LOAD A LOG; MINE goes back). The log is re-read whenever the file’s length or write time changes, and the window reloads it on focus.

Shop styles (ShopPolicy)

Value(upgrade) sums a rough hitting value per modifier: Power x300, HomeRunMultiplier x250, Contact x90, TimingWindow x90 (Percent) or x800 (Add), LaunchBonus x6, GreenBonus x60, GreenStreakBonus x60, ExtraOuts x25, CoinBonus x12, RerollDiscount x4. A non-stacking item is worth only the difference over what’s in its slot.

StyleBuys
POWERThe affordable offer with the highest worth above MinWorth = 8
SYNERGYThe same, plus +40 for an item that completes a synergy and +12 for one that moves toward it (Synergies)
RANDOMA random affordable offer
SAVERLike POWER but never a Common item, and never rerolls

Up to 6 buys per visit; one reroll when nothing is worth it and Coins >= RerollCost + 8 (not SAVER).

An inning, a run, a career

  • SimInning: the real PitcherAI seeded with run.RoundSeed(node) (the game’s seed, see Seeds and Determinism), the park’s balls and InningContext scales; SimCount follows CountTracker’s rules (three strikes out, a foul is never strike three, ball four resets, a home run or batted out resets) without raising events. The inning ends at the goal or out of outs, or as a safety net after 400 pitches (then cleared stays false). It also estimates screen time from the game’s constants: walk-in 5.4 s, windup 1 s, flight + timeBetweenPitches + extra pause, play card 1.2 s, flight shown at 1.6x up to landing + 3 s roll, settle 1.2 s, stack and dock 1.3 s, contact replay 2.85 s, tracer replay 3.6 s (big moments), inning end 1.5 s.
  • SimRun: the run as RunManager plays it: OutsPerInning + ExtraOuts outs, stats = run stats + park + pitcher modifiers (SimInning.StatsFor), RunManager.InningCoins, a shop (ShopService.Open on the meta pool, or the default-unlocked upgrades without one) after every cleared inning but the last (+0.4 min), results +0.5 min, RunManager.Summarize, and when a MetaProgression is given RecordMap, AwardRun, AwardXp. Its RNG is new System.Random(seed x 7919 + 17).
  • SimCareer: a fresh in-memory save (MetaProgression(persist: false)) played run after run: before each run buys every affordable batter, locked upgrade and cosmetic; plays the furthest open map that isn’t beaten on all three difficulties, at its highest open difficulty, with the newest unlocked batter; records milestones (“BOUGHT …”, “UNLOCKED …”, the run’s unlocks), points and account level after every run, and the run after which nothing was left to buy (Meta Progression).

The Sim Lab window (SimLabWindow)

Left panel: Batter, Park, Difficulty, Skill (the five tiers and YOU (n swings) or YOU (no log yet: Average)), Shop, Swing model (every non-abstract ISwingModel with a parameterless constructor, Main first), Vary by row (Nothing / Skill / Park / Difficulty / Shop; YOU joins the Skill list only with 30+ swings), Grid 1 to 5, Speed (10^lerp(0.3, 3.6, speed) = about 2 to 4000 pitches a second per tile), Seed, Keep playing. Buttons: RUN GRID / RESTART GRID, STOP, RESET STATS. BATCH: Plays (ThisSetup or StandardQA), Runs each, RUN BATCH (report), a progress bar with STOP BATCH, OPEN REPORT, FOLDER. YOUR SWINGS (or SWINGS: <folder>/<file>): the fit line, LOAD A LOG, MINE, FOLDER.

Each tile: VARIANT #run, park and difficulty, the 9 inning pips (green cleared, red lost, light blue current, grey ahead, a gold cap on bosses), score bar against the goal, out squares and the count, the last play (gold for a home run), a spray chart (wall outline; gold home runs, bright green GREEN home runs, grey fair outs, red fouls; earlier innings faded) and SCORE, HR, LONG, COINS, ITEMS, MIN. A finished tile is stamped WON or OUT IN n, then restarts after a pause when Keep playing is on. Tile seed: seed x 100003 + tile x 7919 + runNumber. The sim gets at most 25 ms per Editor frame (50 ms for a batch).

STATS tab: per variant RUNS, WON, WIN %, INNINGS, SCORE, HR / RUN, MIN / RUN, LONGEST, then WHERE RUNS END bars (innings 1 to 9B, then WON) and the last batch’s line.

Batches (SimBatchConfig, SimBatch, SimLabCli)

Defaults: runsPerCell = 40, careers = 4 per tier, careerRuns = 120, seed = 1, batters empty = the first batter, parks empty = every ballpark. Standard() = Normal / Medium / Hard x the five fixed tiers x POWER and SYNERGY shops, on every park: 5 x 3 x 5 x 2 x 40 = 6,000 runs plus 20 careers. Cell seed: seed x 1000003 + cellIndex x 1009 + i; career seed seed x 7 + i x 31 + tier. Careers always shop POWER. A ThisSetup batch from the window plays no careers.

unity run . -- -executeMethod HomeRunDerby.EditorTools.SimLabCli.Run
    [-simRuns 40] [-simTiers novice,average,pro,you] [-simParks sandlot,moon] [-simDiffs normal,hard]
    [-simShops power,synergy] [-simBatters rookie] [-simCareers 4] [-simCareerRuns 120] [-simSeed 1] [-simOut path]

Output goes to SimResults/<yyyy-MM-dd_HHmmss>/ under the current directory (git-ignored since #47) unless -simOut says otherwise. Headless it exits 0, or 1 after SimLab FAILED. The Console gets SimLab DONE n runs, m careers in s s -> folder.

report.html (SimReportHtml, one self-contained page, light and dark): header with date, git branch, run count, seconds, swing model and the ideal press; Flagged findings (a synergy never active or a default item never bought in 50+ runs, an AVERAGE bot under 5% on Normal, a ROOKIE over 30% on Hard, a NOVICE under 15% on the first park on Normal, a PRO winning 99%+ of every Hard cell, more than a quarter of won runs over 30 minutes, a career with nothing left to buy); The bots table; Win rate heat maps per tier; Where runs end; How close innings come to their goal; At the plate (pitches per inning, swing rate, contact on swings, GREEN on contact, strikeouts and HR per inning, HR and fouls on contact, big moments per run); Home-run distances in 20 ft buckets with medians; Pace; Economy; Items (bought-in rate, copies held, win rate with and without, lift); Synergies; Careers (runs to beat everything, when the shop ran dry, points banked over time, milestones).

CSV columns. runs.csv: park, difficulty, tier, shop, batter, won, innings_cleared, died_in, score, home_runs, longest_ft, coins_earned, coins_spent, minutes, items, synergies. innings.csv: park, difficulty, tier, shop, inning, boss, pitcher, cleared, score, target, home_runs, pitches, swings, contacts, greens, whiffs, fouls, batted_outs, strikeouts, walks, outs_left, big_moments, seconds. careers.csv: tier, run, points_banked, account_level, park, difficulty, won, score.

AutoPilot (F1 > BOT)

AutoPilot is a component added to [Game] by AutoPilot.Toggle(game) from the dev menu’s BOT tab (Dev Menu and Shortcuts). It sets SwingInput.Bot = this, so the game asks it once a frame TryPress(out pressTime) and reads Aim / HitAim instead of the mouse and keys (the player’s own clicks still count). Batting: on PitchThrown it asks a TierBot of its tier and presses at max(decision.press, releaseTime + 1 ms). Screens, after 0.8 s on each (ActAfter): MainMenu / MapSelect → StartRandomRun(SelectedBatter, park, difficulty); RunMap → PlayCurrentRound; Shop → its ShopPolicy then LeaveShop 0.8 s later; RunOver → a new run after 3 s when RUN IT BACK is on; Intro / Outro → a click every 0.45 s when CUTSCENES: CLICK ON. It sits out co-op, waits while the dev menu is open, and plays on when the window loses focus (UIRoot.OnApplicationFocus no longer pauses while a bot bats).

The corner overlay (GUI.depth -20, above the pitch pill) shows BOT: TIER · STYLE SHOP, runs / won / innings / HR / minutes, FPS (green 55+, yellow 30+, red below), WORST frame ms and HITCHES (frames over 50 ms, ignoring the first 3 s on each screen), and NO ERRORS or n ERRORS (soak-log.txt) with the last error line. soak-log.txt (next to the save, Application.persistentDataPath) gets a “bot on” line (with the game version) and a “bot off” line (with the summary), every inning (cleared or lost, score / target, HR, pitches, seconds from the first pitch), every run, and every Error, Exception or Assert with its stack.

AutoPilot plays on the real save

Its runs record maps, points and XP like yours. Use a dev save (Tools > Home Run Derby > Delete Save File resets it). The swing log skips its pitches (SwingInput.Bot != null), so it never pollutes the YOU fit.

Testing a new mechanic on a branch

  • New batting (contact to batted ball): a class with a public parameterless constructor implementing ISwingModel.Resolve(pitch, contact, stats, batter, hitAim, rng). It appears in the window’s Swing model list; in code, SimBatchConfig.model. The report’s header names the model.
  • New controls: implement IBatterBot.Decide(pitch, count, rng) and pass it to SimRun.
  • New shop behaviour: implement IShopPolicy.
  • Rule changes: SimRun.FinishInning mirrors the private end-of-inning steps of RunManager (coins, cleared or failed, shop, next inning) and SimInning mirrors the count and inning end. Change those in the game, change them here, then run SimTest.
  • Run the same seed on main and on the branch and compare the two reports (the branch name is in each report’s header).

SimTest

Tools > Home Run Derby > Sim Lab > Run Sim Test, or headless -executeMethod HomeRunDerby.EditorTools.SimTest.Run (Editor Tools and Tests). Checks: SimCount follows the count rules; the ideal press is between -40 and -250 ms; seed 42 plays the same run twice; 24 runs per tier at Sandlot Normal all finish, cleared means the goal was reached, a failed inning used every out (or hit the 400-pitch net), coins add up to startingCoins + earned - spent and never go negative, one item per non-charm slot; PRO clears more innings than ROOKIE, GOOD is within 0.5 inning of AVERAGE, NOVICE within 0.5 of ROOKIE; a 30-run PRO career never overspends and account levels only rise; a 2-cell batch of 3 runs fills every cell and plays one career per tier; a ROOKIE bot’s 1,500 pitches written in the swing log’s own CSV layout read back whole and fit a YOU bot within 25% on timing spread, 8 ms on bias, 30% on aim spread, with a chase rate between 0.15 and 0.7, and 20 swings fit nothing. Uses ContentDatabase.LoadOrDefault().

QA fixes shipped in #47

  • HitTally: the $$$ MONEY BALL chip and its coins now fire for a pitcher’s own Money ball too (pitch.Has(Money), not just the map’s effect) (Hit Show).
  • SettingsView.Row: one font size for a whole row of toggles, shrunk until the longest label fits (TIMING RING overflowed its button).
  • ShopView: item names shrink to fit the card (UIDraw.FitText, 19 down to 13; HOT STREAK WRISTBAND ran past the edges).
  • DefaultContent: Sweet Spot Sticker is a Charm, not a Glove, so it can sit beside a Contact glove: the only way to two Contact tags for Barrel Master (Upgrades, Synergies).
  • StatType: the stale comments on Contact and TimingWindow now describe the reach (SwingResolver.HitRadius) (Stats System).
  • TimingWindowScanner.Prepare: one swing stepped frame by frame and snapshotted with BatJiggle.CopyFrom, instead of re-simulating the first k-1 frames for every frame k (the sim calls it every pitch).
  • UIRoot.OnApplicationFocus: no auto-pause while the dev bot bats.
  • SwingInput: the press frame is tracked in both input paths, so a bot press and a real press read the same way.

Numbers

WhatValueWhere to tune
YOU needs30 swingsYouBot.MinSwings
Timing outliers dropped from the fitover +-250 msYouBot.Fit
Robust sigma1.4826 x median absolute deviationYouBot.RobustSigma
Ideal press fallback-0.12 sSimCalibration.Measure
Inning safety net400 pitchesSimInning.Finish
Run step guard100,000 stepsSimRun.PlayOut
Shop: minimum worth / buys per visit / reroll margin8 / 6 / RerollCost + 8 coinsShopPolicy
Batch defaults40 runs per cell, 4 careers per tier, 120 runs per career, seed 1SimBatchConfig
Standard QA batch5 parks x 3 difficulties x 5 tiers x 2 shops x 40 = 6,000 runs + 20 careersSimBatchConfig.Standard
Window grid / speed / frame budget1 to 5 / about 2 to 4,000 pitches per second per tile / 25 ms (batch 50 ms)SimLabWindow
Window minimum size760 x 480SimLabWindow.Open
AutoPilot waits0.8 s per screen, 3 s on results, a click every 0.45 s in cutscenesAutoPilot.ActAfter, RunOverPause, SkipEvery
Hitcha frame over 50 ms, after 3 s on a screenAutoPilot.TrackFrames
Recent errors kept on the overlay4AutoPilot.RecentErrors
Report findings thresholds50 runs; Average < 5% Normal; Rookie > 30% Hard; Novice < 15% first park; Pro >= 99% Hard; won runs > 30 minSimReportHtml.Findings

In the code

FileWhat it does
Scripts/Sim/BatterBot.csBotTier, BotSkill (the tier table, AllTiers, fitted), BotDecision, IBatterBot, TierBot, SimCalibration.IdealPressOffset, SimRandom (Box-Muller Gaussians).
Scripts/Sim/YouBot.csReads swings.csv (Parse, Entries, Swings), Fit, UseFile, Reload, EffectBits.
Scripts/Sim/SimInning.csISwingModel, MainSwingModel, SimBall, SimPlay, InningResult, SimInning.Step, SimCount.
Scripts/Sim/SimRun.csShopStyle, IShopPolicy, ShopPolicy (Value, Shop), RunResult, SimRun (Step, PlayOut, FinishInning).
Scripts/Sim/SimCareer.csCareerMilestone, CareerResult, SimCareer.Play (Frontier, BestBatter, SpendPoints).
Scripts/Sim/SimBatch.csSimBatchConfig (Standard), SimCell, SimBatchResult, SimBatch.Run / Steps.
Scripts/Sim/AutoPilot.csThe in-game bot: Toggle, SwingInput.IBot, screen clicks, the soak counters, LogPath, the overlay.
Scripts/Batting/SwingInput.csIBot, Bot, PollBot; ReadAim / ReadHitAim defer to the bot.
Scripts/UI/TimingWindowScanner.csTrySwing (the sim’s swing through the real bat); the one-swing Prepare.
Scripts/UI/DevMenu.csDrawBot: the BOT tab.
Editor/SimLab/SimLabWindow.csThe window: grid, tiles, spray charts, STATS, batch progress, LOAD A LOG.
Editor/SimLab/SimLabCli.csRun (command-line options), RunWith, Write (report + CSVs), the Run Standard Batch menu item, GitBranch.
Editor/SimLab/SimReportHtml.csBuild: the HTML report and its SVG charts.
Editor/SimTest.csThe checks above.
docs/SIM-LAB.mdThe repo’s own guide (matches the code at b849a3a).

Gotchas

  • The sim and the game share TimingWindowScanner, SwingResolver, HitPhysics, ScoreCalculator, HitTally, PitcherAI, ShopService, RunState and MetaProgression, but not AtBatController, CountTracker or RunManager’s private inning flow. A rule change in those three needs a matching change in SimInning / SimRun or the sim quietly drifts.
  • Pace numbers are estimates from constants, not measured; AutoPilot’s per-inning log line (pitches and seconds) exists to check them against the real game.
  • IdealPressOffset is cached for the Editor session; a batting change that moves the ideal press needs a domain reload (or a restart) before the bots re-measure it.
  • YOU with a log from before #47 (no press_ms column) parses to zero entries, so it plays as AVERAGE. SwingLog moves such a file aside as swings-until-<date>.csv on the first new line (Swing Log).
  • The window lists YOU always; the dev menu’s BOT tab and Vary by row: Skill add it only with 30+ swings.
  • AutoPilot.OnDisable appends to soak-log.txt without the try / catch the other writes have; a locked file would throw on disable.
  • The docs and README say the sim plays “about 100 runs a second”. That is not determined from the code; the report’s header gives the real seconds for each batch.
  • SimResults/ is git-ignored; share report.html by hand.