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
| Where | What you see | Good for |
|---|---|---|
| Sim Lab window (Tools > Home Run Derby > Sim Lab > Open Sim Lab) | A grid of 1x1 to 5x5 tiles, each playing a full run | Watching 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, results | Soak 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).
- 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). - Swing or take. Looks a strike: swing chance
1 - takeInZone(with two strikes1 - takeInZone x 0.3). Looks a ball: swing chancechase, orchaseTwoStrikeswith two strikes. - Pick a target. The real plate location, or, when the pitch carries decoys and a roll beats
decoyFool, one decoy’s position (Special Balls). - Timing.
sigma = timingSigmaMs (+ movingTimingMs if it moves) (+ ghostTimingMs if Ghost);bias = timingBiasMs (+ superFastLateMs if Super Fast).press = ArrivalTime + IdealPressOffset + (bias + Gauss x sigma) / 1000. - 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)
| Tier | timingSigmaMs | timingBiasMs | aimSigmaM | judgeSigmaM | chase | chaseTwoStrikes | takeInZone | movingTimingMs | movingAimM | ghostTimingMs | decoyFool | superFastLateMs |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| NOVICE | 60 | 12 | 0.15 | 0.18 | 0.45 | 0.6 | 0.25 | 35 | 0.08 | 40 | 0.6 | 35 |
| ROOKIE | 42 | 6 | 0.10 | 0.12 | 0.35 | 0.5 | 0.2 | 25 | 0.06 | 30 | 0.5 | 25 |
| AVERAGE | 26 | 3 | 0.07 | 0.08 | 0.25 | 0.4 | 0.12 | 16 | 0.04 | 20 | 0.35 | 15 |
| GOOD | 15 | 1 | 0.045 | 0.05 | 0.15 | 0.3 | 0.07 | 10 | 0.025 | 12 | 0.2 | 8 |
| PRO | 8 | 0 | 0.025 | 0.03 | 0.08 | 0.2 | 0.04 | 5 | 0.015 | 6 | 0.08 | 3 |
| YOU | fitted | fitted | fitted | 0.01 | fitted | fitted | fitted | fitted | nearest tier | nearest tier | nearest tier | nearest 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 - IdealPressOffsetwithin +-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 ofbat_aim - platein x and y;- the rest starts from the fixed tier whose
timingSigmaMsis nearest, thenjudgeSigmaM = 0.01(the chase and take rates already hold the misreads),chasefrom pitches outside the zone with under two strikes (needs 10),chaseTwoStrikesfrom those with two strikes (needs 8),takeInZonefrom 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.
| Style | Buys |
|---|---|
| POWER | The affordable offer with the highest worth above MinWorth = 8 |
| SYNERGY | The same, plus +40 for an item that completes a synergy and +12 for one that moves toward it (Synergies) |
| RANDOM | A random affordable offer |
| SAVER | Like 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 realPitcherAIseeded withrun.RoundSeed(node)(the game’s seed, see Seeds and Determinism), the park’s balls andInningContextscales;SimCountfollowsCountTracker’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 (thenclearedstays 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 asRunManagerplays it:OutsPerInning + ExtraOutsouts, stats = run stats + park + pitcher modifiers (SimInning.StatsFor),RunManager.InningCoins, a shop (ShopService.Openon 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 aMetaProgressionis givenRecordMap,AwardRun,AwardXp. Its RNG isnew 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 toSimRun. - New shop behaviour: implement
IShopPolicy. - Rule changes:
SimRun.FinishInningmirrors the private end-of-inning steps ofRunManager(coins, cleared or failed, shop, next inning) andSimInningmirrors the count and inning end. Change those in the game, change them here, then runSimTest. - Run the same seed on
mainand 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’seffect) (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 onContactandTimingWindownow describe the reach (SwingResolver.HitRadius) (Stats System).TimingWindowScanner.Prepare: one swing stepped frame by frame and snapshotted withBatJiggle.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
| What | Value | Where to tune |
|---|---|---|
| YOU needs | 30 swings | YouBot.MinSwings |
| Timing outliers dropped from the fit | over +-250 ms | YouBot.Fit |
| Robust sigma | 1.4826 x median absolute deviation | YouBot.RobustSigma |
| Ideal press fallback | -0.12 s | SimCalibration.Measure |
| Inning safety net | 400 pitches | SimInning.Finish |
| Run step guard | 100,000 steps | SimRun.PlayOut |
| Shop: minimum worth / buys per visit / reroll margin | 8 / 6 / RerollCost + 8 coins | ShopPolicy |
| Batch defaults | 40 runs per cell, 4 careers per tier, 120 runs per career, seed 1 | SimBatchConfig |
| Standard QA batch | 5 parks x 3 difficulties x 5 tiers x 2 shops x 40 = 6,000 runs + 20 careers | SimBatchConfig.Standard |
| Window grid / speed / frame budget | 1 to 5 / about 2 to 4,000 pitches per second per tile / 25 ms (batch 50 ms) | SimLabWindow |
| Window minimum size | 760 x 480 | SimLabWindow.Open |
| AutoPilot waits | 0.8 s per screen, 3 s on results, a click every 0.45 s in cutscenes | AutoPilot.ActAfter, RunOverPause, SkipEvery |
| Hitch | a frame over 50 ms, after 3 s on a screen | AutoPilot.TrackFrames |
| Recent errors kept on the overlay | 4 | AutoPilot.RecentErrors |
| Report findings thresholds | 50 runs; Average < 5% Normal; Rookie > 30% Hard; Novice < 15% first park; Pro >= 99% Hard; won runs > 30 min | SimReportHtml.Findings |
In the code
| File | What it does |
|---|---|
Scripts/Sim/BatterBot.cs | BotTier, BotSkill (the tier table, AllTiers, fitted), BotDecision, IBatterBot, TierBot, SimCalibration.IdealPressOffset, SimRandom (Box-Muller Gaussians). |
Scripts/Sim/YouBot.cs | Reads swings.csv (Parse, Entries, Swings), Fit, UseFile, Reload, EffectBits. |
Scripts/Sim/SimInning.cs | ISwingModel, MainSwingModel, SimBall, SimPlay, InningResult, SimInning.Step, SimCount. |
Scripts/Sim/SimRun.cs | ShopStyle, IShopPolicy, ShopPolicy (Value, Shop), RunResult, SimRun (Step, PlayOut, FinishInning). |
Scripts/Sim/SimCareer.cs | CareerMilestone, CareerResult, SimCareer.Play (Frontier, BestBatter, SpendPoints). |
Scripts/Sim/SimBatch.cs | SimBatchConfig (Standard), SimCell, SimBatchResult, SimBatch.Run / Steps. |
Scripts/Sim/AutoPilot.cs | The in-game bot: Toggle, SwingInput.IBot, screen clicks, the soak counters, LogPath, the overlay. |
Scripts/Batting/SwingInput.cs | IBot, Bot, PollBot; ReadAim / ReadHitAim defer to the bot. |
Scripts/UI/TimingWindowScanner.cs | TrySwing (the sim’s swing through the real bat); the one-swing Prepare. |
Scripts/UI/DevMenu.cs | DrawBot: the BOT tab. |
Editor/SimLab/SimLabWindow.cs | The window: grid, tiles, spray charts, STATS, batch progress, LOAD A LOG. |
Editor/SimLab/SimLabCli.cs | Run (command-line options), RunWith, Write (report + CSVs), the Run Standard Batch menu item, GitBranch. |
Editor/SimLab/SimReportHtml.cs | Build: the HTML report and its SVG charts. |
Editor/SimTest.cs | The checks above. |
docs/SIM-LAB.md | The repo’s own guide (matches the code at b849a3a). |
Gotchas
- The sim and the game share
TimingWindowScanner,SwingResolver,HitPhysics,ScoreCalculator,HitTally,PitcherAI,ShopService,RunStateandMetaProgression, but notAtBatController,CountTrackerorRunManager’s private inning flow. A rule change in those three needs a matching change inSimInning/SimRunor 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. IdealPressOffsetis 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_mscolumn) parses to zero entries, so it plays as AVERAGE.SwingLogmoves such a file aside asswings-until-<date>.csvon 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.OnDisableappends tosoak-log.txtwithout thetry / catchthe 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; sharereport.htmlby hand.
Related
- Dev Menu and Shortcuts: the BOT tab
- Editor Tools and Tests: the Sim Lab menu items and
SimTest - Testing: when to run a batch or a soak test
- Swing Log: what YOU is fitted from
- Swing and Timing and Batting Explained: the bat and the swing model the bots go through
- Shop and Economy and Upgrades and Synergies: what the shop styles weigh
- Run Structure and Meta Progression: what
SimRunandSimCareermirror - Seeds and Determinism: why the same seed replays