diff --git a/.claude/agents/core-engineer.md b/.claude/agents/core-engineer.md index c535867..13c13a1 100644 --- a/.claude/agents/core-engineer.md +++ b/.claude/agents/core-engineer.md @@ -5,17 +5,18 @@ description: Implements game rules in core/ (chart model, parser, validator, tim You build Hexium's `core` and `tools` modules: plain Kotlin, no Minecraft imports. Rules: -1. Read docs/JUDGEMENT.md and docs/CHART_FORMAT.md before changing behaviour. If the +1. Read docs/JUDGEMENT.md, docs/CHART_FORMAT.md and docs/REPLAY_FORMAT.md before changing behaviour. If the task contradicts them, stop and ask; never change a spec silently. 2. Test-first: write or update tests in core/src/test before the code. Cover each rule with a passing and a failing case, plus edge cases at window boundaries. 3. Deterministic: the same chart and replay must give the same judgements and score on - every machine and frame rate. No wall-clock time, randomness or hash-order iteration. + every machine. No wall-clock time, randomness or hash-order iteration. 4. Judgement windows and score weights live only in JudgementConfig. 5. Judge code runs every frame in the mod: no allocation in its per-frame paths (no lambdas, boxed collections, Pair, sequences); use primitive arrays and loops. 6. Golden replays in core/src/test/resources must stay identical unless the task is to - change them on purpose. + change them on purpose. A change that could alter a replay's result raises + JudgementConfig.JUDGE_VERSION. 7. Run `./gradlew :core:test` (and `./gradlew build` before finishing). Finish as CLAUDE.md says: changelog entry, docs check, summary, commit message. Never commit. diff --git a/.claude/agents/reviewer.md b/.claude/agents/reviewer.md index cb05eb5..c0aa041 100644 --- a/.claude/agents/reviewer.md +++ b/.claude/agents/reviewer.md @@ -11,7 +11,7 @@ Check, in order: 2. Judgement/scoring logic outside `core`, or constants not in JudgementConfig. 3. Mixins/hooks missing the HexiumSession.active() guard. 4. New `core` behaviour without tests; tests that only test the happy path. -5. Mismatch with docs/JUDGEMENT.md or docs/CHART_FORMAT.md. +5. Mismatch with docs/JUDGEMENT.md, docs/CHART_FORMAT.md or docs/REPLAY_FORMAT.md. 6. A proposed commit message not following docs/COMMIT_STRUCTURE.md, or a Feature, Improvement or Fix change without its CHANGELOG.md entry. 7. Docs the change affects but doesn't update (code, settings, commands, rules diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..abe0fce --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# The example chart tests compare text exactly, and the spec holds examples they read. +docs/** text eol=lf + +# The test pack's basic.json must match docs/examples/basic.json byte for byte. +mod/src/client/resources/hexium_packs/**/*.json text eol=lf +mod/src/client/resources/hexium_packs/**/*.ogg binary + +# Golden replays and their results must stay byte for byte. +core/src/test/resources/golden/** -text diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f14e32d..e25c8dd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,19 +20,45 @@ jobs: run: chmod +x ./gradlew - name: build and test run: ./gradlew build + - name: lint example charts + run: ./gradlew :tools:run --args="lint docs/examples" - name: capture mod jar uses: actions/upload-artifact@v7 with: name: hexium-dev-build path: mod/build/libs/ - # Turn on from M2, once client game tests exist. Check the task name - # Loom creates for client game tests in the 26.3 toolchain. - # client-gametest: - # runs-on: ubuntu-24.04 - # steps: - # - uses: actions/checkout@v6 - # - uses: actions/setup-java@v5 - # with: { java-version: '25', distribution: 'microsoft' } - # - run: chmod +x ./gradlew - # - run: xvfb-run -a ./gradlew :mod:runClientGameTest + # Runs the game itself on a virtual display with a fake audio device. It + # hasn't passed on a CI machine yet, and a slow software renderer may upset + # its timing, so it can't fail the build until it has proved reliable. + client-gametest: + runs-on: ubuntu-24.04 + continue-on-error: true + timeout-minutes: 30 + steps: + - name: checkout repository + uses: actions/checkout@v6 + - name: validate gradle wrapper + uses: gradle/actions/wrapper-validation@v6 + - name: setup jdk + uses: actions/setup-java@v5 + with: + java-version: '25' + distribution: 'microsoft' + - name: install virtual display + run: sudo apt-get update && sudo apt-get install -y xvfb xauth libgl1 libglx-mesa0 libgl1-mesa-dri libx11-6 libxext6 libxcursor1 libxi6 libxrandr2 libxfixes3 libxss1 + - name: make gradle wrapper executable + run: chmod +x ./gradlew + - name: run client game tests + run: xvfb-run -a ./gradlew :mod:runClientGameTest + env: + ALSOFT_DRIVERS: 'null' + - name: keep screenshots and logs + if: always() + uses: actions/upload-artifact@v7 + with: + name: hexium-gametest-output + path: | + mod/build/run/clientGameTest/screenshots/ + mod/build/run/clientGameTest/crash-reports/ + mod/build/run/clientGameTest/logs/ diff --git a/.gitignore b/.gitignore index d4a664a..0f02cd3 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,6 @@ crash-reports/ # Claude Code: shared settings are committed, personal ones are not .claude/settings.local.json + +# jqwik's record of failed property tests +.jqwik-database diff --git a/CHANGELOG.md b/CHANGELOG.md index 0517c97..9b23110 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,112 @@ # Hexium - Change Log ## Unreleased + +### New Features + +#### Menus + ++ Added a Hexium button on the title screen that opens Hexium's menu. + + The menu lists every chart it finds, including a built-in Test Pattern and any folders in `.minecraft/hexium/charts`. + + Broken charts are marked and show their first problem, and the full list goes to the log. ++ Choosing a difficulty now plays it on the stage, and Esc offers a way back to the menu. + +#### Charts + ++ Defined chart format v1. + + Note times are exact beat fractions, so they never drift. + + BPM changes and the chart offset set where each beat falls in the song. ++ Added reading and writing of chart files. + + A broken chart lists every problem it has and where to find it, instead of stopping at the first one. ++ Added the chart validator. + + Checks charts and packages against every rule in the chart format. + + Warns when a moment is too dense to play with one hand on the keys. ++ Added basic, advanced and expert example charts for charters to learn the format from. ++ The built-in Test Pattern has a new Expert chart: 90 seconds of sky taps, slides and flicks all over the screen, corners included, mixed with ground notes. ++ Added a command-line chart linter, `lint`, that checks chart files and folders against the format. + +#### Gameplay + ++ Ground charts can now be played: press A S D F (the same positions on any keyboard layout) in time with the song, with combo, judgement and score on screen. + + Presses are timed from when the key went down, not when the game got round to it. + + Taps and holds come down the four lanes to a judgement line, with each lane lighting up while its key is down. + + The pause screen sets the note speed, which changes how far away notes appear but never their timing, and a visual offset, which shifts where notes are drawn relative to the music. ++ Pausing is now fair: resuming goes back 3 seconds and plays the song under a 3-2-1 countdown, and judging starts again exactly where you paused. + + Keys you changed while paused count from that moment, so you can get your fingers back in place. ++ Added a results screen with your score, clear lamp, judgement counts and best combo. ++ Added Retry, on the results and pause screens, which starts the chart again without reloading the stage. ++ Finished plays now save a replay in `.minecraft/hexium/replays`. ++ F6 during a play shows timing numbers: clock drift, frame time, how long key presses waited to reach the judge, how many arrived too late to keep their own time, and your offsets. ++ Added calibration, from the Calibrate button in Hexium's menu. + + Tap to clicks with your eyes closed, then to moving notes with no sound, and it suggests a judgement offset and a visual offset that you can adjust before saving. ++ Your note speed and offsets are now remembered, in `.minecraft/hexium/settings.json`. ++ Added the stage: a plain floor with a raised platform you stand on, looking down the lanes, kept apart from your normal worlds. + + You stand 9 blocks from the judgement line, with a sky screen 18 blocks wide and 9 tall whose middle is level with your eyes. + + You can look around, but moving, jumping and action keys are off while you're on it. + + The camera stops just past the sky screen's edges, so you can't turn away from the stage. + + The hunger bar is hidden. ++ Added judging for ground taps and holds, with CHUNITHM's windows. + + Hold ticks are judged on how long ago the key was last down. ++ Added scoring up to 1,010,000, combo and clear lamps (Full Combo, All Justice, All Justice Critical). + +#### Sky Notes + ++ Sky notes can now be played on the screen in front of you: aim with the camera and click. + + Sky taps fly toward the screen and are hit with a left click (orange) or a right click (blue). + + Slides are a trail of beads to follow with the button held, with a ring where the slide crosses the screen, white while you hold the button. + + Flicks are magenta: swipe through them from any direction. + + A faint ring on the screen shows where a coming note will land. ++ Added judging for sky taps, slides and flicks. + + A swipe that jumps over a flick between two frames still hits it, so low frame rates stay fair. ++ Left and right clicks on the stage are now timed from when the button went down and placed where the crosshair meets the sky screen, ready for sky notes. ++ Pausing is fair for sky notes too: a mouse button you changed while paused counts from the moment you paused, and moving the mouse while paused never counts as a swipe through a flick. + +#### Settings + ++ Added comfort settings to the pause screen, kept in `.minecraft/hexium/settings.json`. + + Mouse: your mouse sensitivity during play, on top of Minecraft's own, so menus feel the same. + + FOV: the field of view during play, 70 by default. + + View Assist: slowly brings the camera back to the middle of the sky screen when no sky notes are coming, off by default. + +#### Online + ++ Added replay files, which record every input of a play. + + Re-judging a replay gives exactly the result of the live play, so scores can be checked. + +### Fixes + +#### Charts + ++ Fixed chart files loading with numbers that aren't valid JSON, like `0.5f` or `01`. ++ Fixed charts passing validation with a BPM so small that note times broke. ++ Fixed chart files saved with a byte-order mark failing to load. ++ Fixed very large or badly broken chart files running out of memory. + + Chart files are limited to 2 MiB, and reading one lists at most 100 problems. ++ Fixed whole-number fields accepting forms like `1e0`. ++ Fixed charts with a huge hold being able to run out of memory when their ticks are built. ++ Fixed charts with notes too far away to have a time passing validation. ++ Fixed difficulty files named for another difficulty passing the linter. + +#### Gameplay + ++ Fixed most key presses being timed by the frame that noticed them instead of when they happened. + + Misses and hold ticks now show up to 50 ms later, while hits show as fast as before. + +#### Sky Notes + ++ Fixed an open flick window holding back other notes, so a press could count for a hold tick that had already passed. ++ Fixed a swipe already inside a flick when its window opens missing at some frame rates: it now counts as crossing at that moment. + +#### Misc + ++ Hexium now requires Fabric Language Kotlin 1.14.2 or newer, instead of failing at the first chart load on older versions. + +### Technical Details + ++ Added song playback through Hexium's own OpenAL source and an audio clock that follows it. + + When the audio device changes or sounds reload, the song returns at the right place once the game has reloaded. ++ Added client game tests that load the stage in the real game and check that normal worlds are untouched. ++ Added an Audio Test screen with a debug overlay, for checking that the clock stays with the music over a whole song. ++ Added `rejudge` and `dump` to the command-line tools. ++ Added golden replays and property tests that guard the judge. ++ The build now lints the example charts. diff --git a/CLAUDE.md b/CLAUDE.md index 41ff5b2..9488145 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,8 +2,8 @@ Hexium is a Fabric rhythm game mod for Minecraft 26.3 (Kotlin, Java 25): a 4-lane keyboard track plus a mouse-aimed sky screen, with an in-game editor and online charts. -It is client-only. The project is at Milestone 0 (set-up done); see the roadmap in -docs/DESIGN.md. +It is client-only. Milestone 3 (sky layer) has passed its gate, so the project is at +Milestone 4 (content loop); see the roadmap in docs/DESIGN.md. ## Working with me - Before any non-trivial task, ask clarifying questions about the idea and design @@ -12,7 +12,8 @@ docs/DESIGN.md. - Keep changes scoped to one task. Summarize what changed and why at the end. ## Read first -- docs/DESIGN.md (what Hexium is), docs/JUDGEMENT.md, docs/CHART_FORMAT.md (the specs), +- docs/DESIGN.md (what Hexium is), docs/JUDGEMENT.md, docs/CHART_FORMAT.md, + docs/REPLAY_FORMAT.md (the specs), docs/ARCHITECTURE.md (how the code is built), docs/DEVELOPMENT.md (commands, workflow). - Files in docs/ have upper-case names (docs/COMMIT_STRUCTURE.md), as in TownyMenu. - README.md faces players (what Hexium is, install, how to play, charts). Never put @@ -25,7 +26,7 @@ docs/DESIGN.md. mixins in src/client/java/net/trilleo/hexium/client/mixin. src/main holds only shared constants (net.trilleo.hexium). - `server/` online server (Milestone 7), net.trilleo.hexium.server. -- `tools/` CLI: chart lint, replay re-judge, net.trilleo.hexium.tools. +- `tools/` CLI: chart lint, replay re-judge and dump, net.trilleo.hexium.tools. - Versions live in gradle.properties; `mod_version` is the mod's version. ## Hard rules @@ -48,7 +49,8 @@ docs/DESIGN.md. and Fix, as part of the change (format in docs/RELEASING.md). - After EVERY change, check which documents it affects and update them in the same change: this file, README.md (player-facing facts), CHANGELOG.md, - docs/DESIGN.md, docs/JUDGEMENT.md, docs/CHART_FORMAT.md, docs/DEVELOPMENT.md, + docs/DESIGN.md, docs/JUDGEMENT.md, docs/CHART_FORMAT.md, docs/REPLAY_FORMAT.md, + docs/DEVELOPMENT.md, docs/ARCHITECTURE.md, docs/API.md (server routes, once it exists), docs/RELEASING.md, docs/COMMIT_STRUCTURE.md, .claude/agents/*.md and .github/workflows/*.yml. @@ -78,4 +80,5 @@ docs/DESIGN.md. - Build + all tests: ./gradlew build - Core tests only: ./gradlew :core:test - Run client: ./gradlew :mod:runClient +- Client game tests (opens a game window; tests are in mod/src/gametest): ./gradlew :mod:runClientGameTest - Lint charts (from Milestone 1): ./gradlew :tools:run --args="lint docs/examples" diff --git a/README.md b/README.md index 60b134c..4341d65 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ ## How it plays -- **Ground track:** four lanes under your feet. Press A, S, D or F as notes reach the line. Some notes are holds: keep the key down until they end. +- **Ground track:** four lanes under your feet. Press A, S, D or F (the same positions on any keyboard layout) as notes reach the line. Some notes are holds: keep the key down until they end. - **Sky screen:** a giant screen in front of you. Aim at sky notes and click: left or right click, depending on the note. Slides need you to hold the click and follow a path. Flicks need a quick swipe through the note, no click. - **Timing:** every hit is judged Justice Critical, Justice, Attack or Miss. A perfect play scores 1,010,000. - **Charts:** play built-in charts, make your own in the in-game editor, and share them online with leaderboards (coming later). @@ -19,7 +19,7 @@ Hexium has its own menu on the title screen. Your normal worlds and servers are 2. Put these in your `mods` folder: Hexium, [Fabric API](https://modrinth.com/mod/fabric-api) and [Fabric Language Kotlin](https://modrinth.com/mod/fabric-language-kotlin). 3. Start Minecraft and open **Hexium** from the title screen. -For the smoothest timing, play at 240 FPS or more and run the offset calibration in Hexium's settings once. +For the smoothest timing, play at 240 FPS or more and press Calibrate in Hexium's menu once. ## Links diff --git a/core/build.gradle.kts b/core/build.gradle.kts index ac41b38..8984d10 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -5,5 +5,19 @@ plugins { } dependencies { + // Chart and settings JSON, tree API only. In the mod it comes from Fabric Language Kotlin. + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:${providers.gradleProperty("kotlinx_serialization_version").get()}") + testImplementation(kotlin("test")) + testImplementation("net.jqwik:jqwik:${providers.gradleProperty("jqwik_version").get()}") +} + +tasks.test { + // The tests read the example charts, the spec's examples and the mod's test pack. + inputs.dir(rootProject.file("docs/examples")) + inputs.file(rootProject.file("docs/CHART_FORMAT.md")) + inputs.dir(rootProject.file("mod/src/client/resources/hexium_packs")) + + // Regenerates the golden replays after a deliberate change (docs/DEVELOPMENT.md). + systemProperty("hexium.updateGolden", providers.systemProperty("hexium.updateGolden").getOrElse("false")) } diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/aim/ScreenPlane.kt b/core/src/main/kotlin/net/trilleo/hexium/core/aim/ScreenPlane.kt new file mode 100644 index 0000000..c319fc7 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/aim/ScreenPlane.kt @@ -0,0 +1,116 @@ +package net.trilleo.hexium.core.aim + +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * The sky screen as a flat plane across +Z, at [planeZ], turning a look into the crosshair's place on it + * and back. Places are the chart's normalised screen coordinates: x from 0 at [leftX] to 1 at [rightX], + * y from 0 at [bottomY] to 1 at [topY], and either may be off the screen. Angles are Minecraft's, in + * degrees: yaw 0 looks down +Z and turns toward -X as it grows, pitch looks down as it grows. + * + * This is how the mod reads aim, not a judging rule: replays hold the places, never the angles. Results + * go in [x], [y], [yaw] and [pitch] instead of new objects, so nothing allocates. One thread only. + */ +class ScreenPlane( + private val leftX: Double, + private val rightX: Double, + private val bottomY: Double, + private val topY: Double, + private val planeZ: Double, +) { + /** Where the last [aim] hit, or NaN if it looked away from the screen. */ + var x = Double.NaN + private set + var y = Double.NaN + private set + + /** The look from the last [clampLook] or [lookToward]. */ + var yaw = 0.0 + private set + var pitch = 0.0 + private set + + /** The last [aim]'s look, across and up, for a look that missed. */ + private var lookX = 0.0 + private var lookY = 0.0 + + /** Where a look from the eye meets the plane, into [x] and [y]. False if it looks along or away from it. */ + fun aim(eyeX: Double, eyeY: Double, eyeZ: Double, yaw: Double, pitch: Double): Boolean { + val yawRadians = Math.toRadians(yaw) + val pitchRadians = Math.toRadians(pitch) + val along = cos(pitchRadians) + val dirX = -sin(yawRadians) * along + val dirY = -sin(pitchRadians) + val dirZ = cos(yawRadians) * along + lookX = dirX + lookY = dirY + val distance = planeZ - eyeZ + if (dirZ < MIN_FORWARD || distance <= 0.0) { + x = Double.NaN + y = Double.NaN + return false + } + val t = distance / dirZ + x = (leftX - (eyeX + dirX * t)) / (leftX - rightX) + y = (eyeY + dirY * t - bottomY) / (topY - bottomY) + return true + } + + /** The look from the eye toward a place on the plane, into [yaw] and [pitch]. Yaw is in -180 to 180. */ + fun lookToward(eyeX: Double, eyeY: Double, eyeZ: Double, screenX: Double, screenY: Double) { + val dx = leftX + (rightX - leftX) * screenX - eyeX + val dy = bottomY + (topY - bottomY) * screenY - eyeY + val dz = planeZ - eyeZ + yaw = Math.toDegrees(atan2(-dx, dz)) + pitch = Math.toDegrees(atan2(-dy, sqrt(dx * dx + dz * dz))) + } + + /** + * Keeps a look on the screen, plus [marginX] and [marginY] past its edges in screen units, into [yaw] + * and [pitch]. A look past an edge stops at it. One turned so far it misses the plane, which one frame's + * turn can do, stops at the edges it went past, and stays level with the eye on an axis it didn't turn on. + * The yaw stays on the same whole turn as [yaw] given, since the camera's keeps counting. Returns true + * if the look had to change. + */ + fun clampLook(eyeX: Double, eyeY: Double, eyeZ: Double, yaw: Double, pitch: Double, marginX: Double, marginY: Double): Boolean { + val hits = aim(eyeX, eyeY, eyeZ, yaw, pitch) + val placeX = if (hits) x else pastEdge(lookX * (rightX - leftX), (leftX - eyeX) / (leftX - rightX), marginX) + val placeY = if (hits) y else pastEdge(lookY * (topY - bottomY), (eyeY - bottomY) / (topY - bottomY), marginY) + val clampedX = placeX.coerceIn(-marginX, 1.0 + marginX) + val clampedY = placeY.coerceIn(-marginY, 1.0 + marginY) + if (hits && clampedX == x && clampedY == y) { + this.yaw = yaw + this.pitch = pitch + return false + } + lookToward(eyeX, eyeY, eyeZ, clampedX, clampedY) + this.yaw = yaw + wrapDegrees(this.yaw - yaw) + return true + } + + /** + * For a look that misses the plane, on one axis: [towardOne] is how fast the look heads toward that + * axis's 1 edge. It stops past the edge it heads for, or at the eye's own place, [eye], if it hardly + * heads either way. + */ + private fun pastEdge(towardOne: Double, eye: Double, margin: Double): Double = when { + towardOne > MIN_FORWARD -> 1.0 + margin + towardOne < -MIN_FORWARD -> -margin + else -> eye + } + + private fun wrapDegrees(degrees: Double): Double { + var d = degrees % 360.0 + if (d >= 180.0) d -= 360.0 + if (d < -180.0) d += 360.0 + return d + } + + private companion object { + /** A look this close to along the plane is treated as missing it, so its place can't overflow. */ + const val MIN_FORWARD = 1e-6 + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/calibration/Calibration.kt b/core/src/main/kotlin/net/trilleo/hexium/core/calibration/Calibration.kt new file mode 100644 index 0000000..d650fef --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/calibration/Calibration.kt @@ -0,0 +1,108 @@ +package net.trilleo.hexium.core.calibration + +import kotlin.math.abs +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.roundToInt +import kotlin.math.sin + +/** How far off the beat a player tapped. Positive is late. */ +class TapEstimate(val errorMs: Double, val spreadMs: Double, val tapsUsed: Int, val tapsGiven: Int, val driftMs: Double) { + /** + * False if [errorMs] doesn't mean much: the taps were too scattered, too many were thrown out, or + * they slid steadily off the beat, as they do when the player can't actually hear the clicks. + */ + val isSteady: Boolean + get() = spreadMs <= Calibration.MAX_SPREAD_MS && + tapsUsed * Calibration.MIN_KEPT_QUARTERS >= tapsGiven * Calibration.QUARTERS && + abs(driftMs) <= Calibration.MAX_DRIFT_MS +} + +/** + * The maths behind the two-step calibration in docs/JUDGEMENT.md. The player taps to clicks they can + * only hear, which gives offset B, then to notes they can only see, with no offset applied, which gives A. + */ +object Calibration { + const val MIN_TAPS = 8 + const val MAX_SPREAD_MS = 40.0 + + /** How much the second half of the taps may sit from the first. */ + const val MAX_DRIFT_MS = 25.0 + const val QUARTERS = 3 + const val MIN_KEPT_QUARTERS = 4 + + /** Nobody taps further ahead of a beat than this share of one, so it must be the beat before, heard late. */ + private const val MOST_EARLY_BEATS = 0.25 + + /** A tap this close to the rest is never thrown out, however tight the rest are. */ + private const val MIN_OUTLIER_MS = 50.0 + private const val OUTLIER_SPREADS = 3.0 + private const val TURN = 2.0 * Math.PI + + /** + * Reads the first [count] of [tapsMs], song times with a beat every [beatMs] from time 0, or returns null + * if too few are usable. A tap could belong to either beat around it, so the taps are first gathered + * round where most of them lie, and one stray tap doesn't matter. The result is from a quarter of a beat + * early to three quarters late, since late output such as Bluetooth can be a long way behind. + */ + fun estimate(tapsMs: DoubleArray, count: Int, beatMs: Double): TapEstimate? { + if (count < MIN_TAPS) return null + val centre = centreOfPhases(tapsMs, count, beatMs) + val errors = DoubleArray(count) { wrap(tapsMs[it] - centre, beatMs) + centre } + val middle = median(errors, count) + val limit = maxOf(MIN_OUTLIER_MS, OUTLIER_SPREADS * spread(errors, count, middle)) + var kept = 0 + for (i in 0 until count) { + if (abs(errors[i] - middle) <= limit) errors[kept++] = errors[i] + } + if (kept < MIN_TAPS) return null + val keptMiddle = median(errors, kept) + val error = if (keptMiddle < -MOST_EARLY_BEATS * beatMs) keptMiddle + beatMs else keptMiddle + return TapEstimate(error, spread(errors, kept, keptMiddle), kept, count, drift(errors, kept)) + } + + /** The average of the later half of [values] minus that of the earlier half. */ + private fun drift(values: DoubleArray, count: Int): Double { + val half = count / 2 + var early = 0.0 + var late = 0.0 + for (i in 0 until half) { + early += values[i] + late += values[count - 1 - i] + } + return (late - early) / half + } + + /** Offset B: judgement time is input time minus B, so a player tapping late to sound judges as on time. */ + fun judgementOffsetMs(toSound: TapEstimate): Int = toSound.errorMs.roundToInt() + + /** + * Offset A, from taps to notes drawn with no offset. Drawing a note A later moves the player's tap A + * later, so A = B minus that error makes their tap judge as on time. + */ + fun visualOffsetMs(judgementOffsetMs: Int, toNotes: TapEstimate): Int = (judgementOffsetMs - toNotes.errorMs).roundToInt() + + private fun centreOfPhases(tapsMs: DoubleArray, count: Int, beatMs: Double): Double { + var x = 0.0 + var y = 0.0 + for (i in 0 until count) { + val angle = tapsMs[i] / beatMs * TURN + x += cos(angle) + y += sin(angle) + } + return atan2(y, x) / TURN * beatMs + } + + /** [ms] moved by whole beats to within half a beat of 0. */ + private fun wrap(ms: Double, beatMs: Double): Double = ms - Math.rint(ms / beatMs) * beatMs + + private fun median(values: DoubleArray, count: Int): Double { + val sorted = values.copyOf(count) + sorted.sort() + val half = count / 2 + return if (count % 2 == 1) sorted[half] else (sorted[half - 1] + sorted[half]) / 2.0 + } + + private fun spread(values: DoubleArray, count: Int, middle: Double): Double = + median(DoubleArray(count) { abs(values[it] - middle) }, count) +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/Beat.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/Beat.kt new file mode 100644 index 0000000..6c2483c --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/Beat.kt @@ -0,0 +1,22 @@ +package net.trilleo.hexium.core.chart + +/** + * A time in beats as an exact fraction, stored as `[whole, num, den]` in chart files. + * + * It can hold invalid values so the validator can report them. [compareTo] and [toDouble] + * only mean something when [isValid] is true. + * + * `equals` compares the fields as written, so `[12,2,4]` and `[12,1,2]` aren't equal but + * do compare as the same time. Use [compareTo] for time. + */ +data class Beat(val whole: Int, val num: Int, val den: Int) : Comparable { + val isValid: Boolean + get() = whole >= 0 && den > 0 && num >= 0 && num < den + + override fun compareTo(other: Beat): Int { + if (whole != other.whole) return whole.compareTo(other.whole) + return (num.toLong() * other.den).compareTo(other.num.toLong() * den) + } + + fun toDouble(): Double = whole + num.toDouble() / den +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/Chart.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/Chart.kt new file mode 100644 index 0000000..b28071c --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/Chart.kt @@ -0,0 +1,123 @@ +package net.trilleo.hexium.core.chart + +/* + * The chart format as data, exactly as in docs/CHART_FORMAT.md. These classes can hold + * values the format forbids, so the validator can report them instead of the parser + * failing on the first one. + */ + +enum class Difficulty { BASIC, ADVANCED, EXPERT, MASTER } + +enum class SkyButton { L, R } + +/** Shapes the slide segment leaving a point. */ +enum class Ease(val id: String) { + LINEAR("linear"), + IN("in"), + OUT("out"), + IN_OUT("inOut"), + ; + + /** Where the position is at [t], the progress from 0 to 1 along the segment. */ + fun progress(t: Double): Double = when (this) { + LINEAR -> t + IN -> t * t + OUT -> 1.0 - (1.0 - t) * (1.0 - t) + IN_OUT -> t * t * (3.0 - 2.0 * t) + } +} + +/** One `.json` file. */ +data class DifficultyChart( + val formatVersion: Int, + val difficulty: Difficulty, + val level: Int, + val laneCount: Int, + val offsetMs: Double, + val bpm: List, + val meter: List, + val notes: List, +) { + /** True if every note is on the ground track: no sky taps, slides or flicks. */ + val isGroundOnly: Boolean + get() = notes.all { it is Note.Tap || it is Note.Hold } + + /** When the last note ends, in song milliseconds, or 0 if there are no notes. */ + fun lastNoteEndMs(): Double { + val timing = TimingMap(offsetMs, bpm) + var last = 0.0 + for (note in notes) { + val end = when (note) { + is Note.Tap -> note.t + is Note.Hold -> note.end + is Note.SkyTap -> note.t + is Note.Flick -> note.t + is Note.Slide -> note.points.last().t + } + val endMs = timing.beatToMs(end) + if (endMs > last) last = endMs + } + return last + } +} + +data class BpmChange(val t: Beat, val bpm: Double) + +data class MeterChange(val t: Beat, val num: Int, val den: Int) + +sealed interface Note { + data class Tap(val t: Beat, val lane: Int) : Note + + data class Hold(val t: Beat, val end: Beat, val lane: Int) : Note + + data class SkyTap( + val t: Beat, + val x: Double, + val y: Double, + val button: SkyButton, + val size: Double, + ) : Note + + data class Slide( + val button: SkyButton, + val radius: Double, + val points: List, + ) : Note + + /** Hit by a swipe through it from any direction. */ + data class Flick( + val t: Beat, + val x: Double, + val y: Double, + val size: Double, + ) : Note +} + +data class SlidePoint(val t: Beat, val x: Double, val y: Double, val ease: Ease) + +/** The `meta.json` file. */ +data class ChartMeta( + val formatVersion: Int, + val id: String, + val title: String, + val artist: String, + val charter: String, + val previewStartMs: Int, + val license: License, + val difficulties: List, +) + +data class License(val type: LicenseType, val source: String?) + +enum class LicenseType(val id: String) { + ORIGINAL("original"), + PERMITTED("permitted"), +} + +/** + * The chart data of a `.hexium` package: its `meta.json` and every difficulty file. + * + * It keeps no file names, so whoever reads the files must also call + * [ChartValidator.validateFileName]. + */ +data class ChartPackage(val meta: ChartMeta, val charts: List) diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartFolder.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartFolder.kt new file mode 100644 index 0000000..2f03b41 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartFolder.kt @@ -0,0 +1,92 @@ +package net.trilleo.hexium.core.chart + +/** + * The rules for a folder of chart files, so everything that reads one treats it the same. The + * caller does the file access and passes in what it found. Never throws. + */ +object ChartFolder { + const val META_FILE: String = "meta.json" + const val AUDIO_FILE: String = "audio.ogg" + + /** What a folder's own files add on top of checking each file. */ + private val FOLDER_CODES = setOf( + IssueCode.MISSING_DIFFICULTY_FILE, + IssueCode.UNLISTED_DIFFICULTY_FILE, + IssueCode.DUPLICATE_DIFFICULTY_FILE, + IssueCode.PACKAGE_TOO_LARGE, + ) + + /** [text] is null if it couldn't be read. The caller reports why. */ + class File(val name: String, val text: String?) + + /** One file's contents, if it could be read, and its problems. */ + class FileResult(val meta: ChartMeta?, val chart: DifficultyChart?, val issues: List) + + /** A problem in [file], or in the folder itself if [file] is null. */ + data class Issue(val file: String?, val issue: ChartIssue) + + class Result(val meta: ChartMeta?, val charts: List, val issues: List) + + /** Hidden files like the `._basic.json` that macOS leaves in archives aren't charts. */ + fun isChartFile(name: String): Boolean = name.endsWith(".json") && !name.startsWith(".") + + /** A character is at most 4 bytes, so a longer file can't be within the limit. Don't try to read it. */ + fun isTooLargeToRead(sizeBytes: Long): Boolean = sizeBytes > ChartLimits.MAX_JSON_FILE_CHARS * 4L + + fun readFile(name: String, text: String): FileResult { + if (name == META_FILE) { + val parsed = ChartParser.parseMeta(text) + val meta = parsed.value ?: return FileResult(null, null, parsed.issues) + return FileResult(meta, null, parsed.issues + ChartValidator.validateMeta(meta)) + } + val parsed = ChartParser.parseDifficulty(text) + val chart = parsed.value ?: return FileResult(null, null, parsed.issues) + val issues = parsed.issues + ChartValidator.validateChart(chart) + ChartValidator.validateFileName(chart, name) + return FileResult(null, chart, issues) + } + + /** What's wrong with the folder as a whole. Only meaningful once every file in it could be read. */ + fun folderIssues( + meta: ChartMeta, + charts: List, + fileNames: List, + packageSizeBytes: Long? = null, + ): List { + val issues = ArrayList() + for (issue in ChartValidator.validatePackage(ChartPackage(meta, charts), packageSizeBytes = packageSizeBytes)) { + if (issue.code in FOLDER_CODES) issues += issue + } + if (AUDIO_FILE !in fileNames) { + issues += ChartIssue(Severity.ERROR, IssueCode.MISSING_AUDIO_FILE, "$", "has no $AUDIO_FILE") + } + return issues + } + + /** Reads a whole folder: [files] are its chart files, and [fileNames] names everything in it. */ + fun read(files: List, fileNames: List, packageSizeBytes: Long? = null): Result { + var meta: ChartMeta? = null + val charts = ArrayList() + val issues = ArrayList() + var allRead = true + for (file in files) { + val text = file.text + if (text == null) { + allRead = false + continue + } + val result = readFile(file.name, text) + for (issue in result.issues) issues += Issue(file.name, issue) + if (result.meta == null && result.chart == null) allRead = false + if (result.meta != null) meta = result.meta + if (result.chart != null) charts += result.chart + } + if (META_FILE !in fileNames) { + issues += Issue(null, ChartIssue(Severity.ERROR, IssueCode.MISSING_META_FILE, "$", "has no $META_FILE")) + } + val listed = meta + if (listed != null && allRead) { + for (issue in folderIssues(listed, charts, fileNames, packageSizeBytes)) issues += Issue(null, issue) + } + return Result(listed, charts, issues) + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartIssue.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartIssue.kt new file mode 100644 index 0000000..995e235 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartIssue.kt @@ -0,0 +1,67 @@ +package net.trilleo.hexium.core.chart + +enum class Severity { ERROR, WARNING } + +/** What kind of problem an issue is. Stable, so the editor and tests can act on it. */ +enum class IssueCode { + INVALID_JSON, + WRONG_TYPE, + MISSING_FIELD, + UNKNOWN_FIELD, + UNKNOWN_VALUE, + UNKNOWN_FORMAT_VERSION, + FILE_TOO_LARGE, + TOO_MANY_PROBLEMS, + + BAD_LANE_COUNT, + BAD_LEVEL, + OFFSET_NOT_FINITE, + INVALID_BEAT, + BPM_NOT_POSITIVE, + FIRST_BPM_NOT_AT_ZERO, + BPM_NOT_RISING, + FIRST_METER_NOT_AT_ZERO, + METER_NOT_RISING, + METER_NOT_POSITIVE, + LANE_OUT_OF_RANGE, + HOLD_END_NOT_AFTER_START, + HOLDS_OVERLAP, + TAP_INSIDE_HOLD, + DUPLICATE_TAP, + SLIDE_TOO_FEW_POINTS, + SLIDE_POINTS_NOT_RISING, + POSITION_OUT_OF_RANGE, + SIZE_NOT_POSITIVE, + RADIUS_NOT_POSITIVE, + NOTE_AFTER_AUDIO, + TOO_MANY_JUDGED_OBJECTS, + TIME_NOT_FINITE, + FILE_NAME_MISMATCH, + TOO_DENSE, + + BAD_ID, + BLANK_TEXT, + NEGATIVE_PREVIEW, + NO_DIFFICULTIES, + REPEATED_DIFFICULTY, + MISSING_DIFFICULTY_FILE, + UNLISTED_DIFFICULTY_FILE, + DUPLICATE_DIFFICULTY_FILE, + PACKAGE_TOO_LARGE, + MISSING_META_FILE, + MISSING_AUDIO_FILE, +} + +/** A problem in a chart file. [path] points at it, for example `notes[3].lane`, or `$` for the whole file. */ +data class ChartIssue( + val severity: Severity, + val code: IssueCode, + val path: String, + val message: String, +) { + override fun toString(): String = "$severity $path: $message" +} + +/** Cuts file text repeated in an issue, so a hostile file can't make huge messages. */ +internal fun shortened(text: String): String = + if (text.length <= ChartLimits.MAX_ISSUE_TEXT_CHARS) text else text.take(ChartLimits.MAX_ISSUE_TEXT_CHARS) + "…" diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartParser.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartParser.kt new file mode 100644 index 0000000..e609ec3 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartParser.kt @@ -0,0 +1,420 @@ +package net.trilleo.hexium.core.chart + +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.doubleOrNull +import kotlinx.serialization.json.intOrNull +import net.trilleo.hexium.core.HexiumCore + +/** [value] is null when [issues] holds an error. */ +data class ParseResult(val value: T?, val issues: List) + +/** + * Reads chart files. Never throws: every problem in the file comes back as an issue. + * + * This only checks a file's shape (fields, types, known names). Whether the values follow + * the format's rules is the validator's job. + */ +object ChartParser { + fun parseDifficulty(text: String): ParseResult = parse(text, FileReader::readDifficulty) + + fun parseMeta(text: String): ParseResult = parse(text, FileReader::readMeta) + + private fun parse(fileText: String, read: FileReader.(JsonObject) -> T?): ParseResult { + val reader = FileReader() + if (fileText.length > ChartLimits.MAX_JSON_FILE_CHARS) { + reader.error( + IssueCode.FILE_TOO_LARGE, + ROOT, + "is ${fileText.length} characters long, the limit is ${ChartLimits.MAX_JSON_FILE_CHARS}", + ) + return ParseResult(null, reader.issues) + } + val text = fileText.removePrefix(BYTE_ORDER_MARK) + if (nestsTooDeeply(text)) { + reader.error(IssueCode.INVALID_JSON, ROOT, "is not valid JSON: nested more than $MAX_NESTING levels deep") + return ParseResult(null, reader.issues) + } + val root = try { + Json.parseToJsonElement(text) + } catch (e: SerializationException) { + reader.error(IssueCode.INVALID_JSON, ROOT, "is not valid JSON: ${shortened(e.message?.lineSequence()?.first().orEmpty())}") + return ParseResult(null, reader.issues) + } + if (root !is JsonObject) { + reader.error(IssueCode.WRONG_TYPE, ROOT, "must be an object") + return ParseResult(null, reader.issues) + } + if (!reader.readFormatVersion(root)) return ParseResult(null, reader.issues) + val value = reader.read(root) + return ParseResult(if (reader.hasError) null else value, reader.issues) + } + + /** The JSON library overflows the stack on extreme nesting, and uploads can be hostile. */ + private fun nestsTooDeeply(text: String): Boolean { + var depth = 0 + var inString = false + var i = 0 + while (i < text.length) { + val c = text[i] + if (inString) { + if (c == '\\') i++ else if (c == '"') inString = false + } else if (c == '"') { + inString = true + } else if (c == '[' || c == '{') { + if (++depth > MAX_NESTING) return true + } else if (c == ']' || c == '}') { + depth-- + } + i++ + } + return false + } +} + +private const val ROOT = "$" + +private const val FORMAT_VERSION = "formatVersion" + +private const val BYTE_ORDER_MARK = "\uFEFF" + +/** The JSON library and Kotlin's number parsing both accept more than JSON allows, like `0.5f` and `01`. */ +private val JSON_NUMBER = Regex("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?") + +/** Whole-number fields are digits only: `1e0` and `1.0` are valid JSON but not how a lane is written. */ +private val JSON_WHOLE_NUMBER = Regex("-?(0|[1-9][0-9]*)") + +/** Far more than a chart needs (6 levels), with room for unknown fields. */ +private const val MAX_NESTING = 32 + +private val DIFFICULTY_FIELDS = setOf(FORMAT_VERSION, "difficulty", "level", "laneCount", "offsetMs", "bpm", "meter", "notes") +private val META_FIELDS = + setOf(FORMAT_VERSION, "id", "title", "artist", "charter", "previewStartMs", "license", "difficulties") +private val LICENSE_FIELDS = setOf("type", "source") +private val BPM_FIELDS = setOf("t", "bpm") +private val METER_FIELDS = setOf("t", "num", "den") +private val TAP_FIELDS = setOf("type", "t", "lane") +private val HOLD_FIELDS = setOf("type", "t", "end", "lane") +private val SKY_TAP_FIELDS = setOf("type", "t", "x", "y", "button", "size") +private val SLIDE_FIELDS = setOf("type", "button", "radius", "points") +private val SLIDE_POINT_FIELDS = setOf("t", "x", "y", "ease") +private val FLICK_FIELDS = setOf("type", "t", "x", "y", "size") + +private val DIFFICULTY_NAMES = Difficulty.entries.map { it.name to it } +private val BUTTON_NAMES = SkyButton.entries.map { it.name to it } +private val EASE_NAMES = Ease.entries.map { it.id to it } +private val LICENSE_NAMES = LicenseType.entries.map { it.id to it } + +/** Reads one file, collecting issues. A read returns null when it reported an error. */ +private class FileReader { + val issues = ArrayList() + var hasError = false + private set + private var isCut = false + + fun error(code: IssueCode, path: String, message: String) { + hasError = true + add(ChartIssue(Severity.ERROR, code, path, message)) + } + + /** Past the cap, one final issue stands in for the rest. It's an error if any of the rest is. */ + private fun add(issue: ChartIssue) { + if (issues.size < ChartLimits.MAX_PARSE_ISSUES) { + issues += issue + } else if (!isCut) { + isCut = true + issues += ChartIssue( + issue.severity, + IssueCode.TOO_MANY_PROBLEMS, + ROOT, + "has too many problems, only the first ${ChartLimits.MAX_PARSE_ISSUES} are listed", + ) + } else if (issue.severity == Severity.ERROR) { + issues[issues.lastIndex] = issues.last().copy(severity = Severity.ERROR) + } + } + + fun readFormatVersion(root: JsonObject): Boolean { + val version = int(root, FORMAT_VERSION, ROOT) ?: return false + if (version != HexiumCore.CHART_FORMAT_VERSION) { + error( + IssueCode.UNKNOWN_FORMAT_VERSION, + FORMAT_VERSION, + "is $version, but this version of Hexium reads format ${HexiumCore.CHART_FORMAT_VERSION}", + ) + return false + } + return true + } + + fun readDifficulty(root: JsonObject): DifficultyChart? { + warnUnknownFields(root, ROOT, DIFFICULTY_FIELDS) + val difficulty = choice(root, "difficulty", ROOT, DIFFICULTY_NAMES) + val level = int(root, "level", ROOT) + val laneCount = int(root, "laneCount", ROOT) + val offsetMs = double(root, "offsetMs", ROOT) + val bpm = objects(root, "bpm", ROOT, ::readBpm) + val meter = objects(root, "meter", ROOT, ::readMeter) + val notes = objects(root, "notes", ROOT, ::readNote) + if (difficulty == null || level == null || laneCount == null || offsetMs == null) return null + if (bpm == null || meter == null || notes == null) return null + return DifficultyChart(HexiumCore.CHART_FORMAT_VERSION, difficulty, level, laneCount, offsetMs, bpm, meter, notes) + } + + fun readMeta(root: JsonObject): ChartMeta? { + warnUnknownFields(root, ROOT, META_FIELDS) + val id = string(root, "id", ROOT) + val title = string(root, "title", ROOT) + val artist = string(root, "artist", ROOT) + val charter = string(root, "charter", ROOT) + val previewStartMs = int(root, "previewStartMs", ROOT) + val license = child(root, "license", ROOT)?.let { readLicense(it, "license") } + val difficulties = difficulties(root) + if (id == null || title == null || artist == null || charter == null) return null + if (previewStartMs == null || license == null || difficulties == null) return null + return ChartMeta(HexiumCore.CHART_FORMAT_VERSION, id, title, artist, charter, previewStartMs, license, difficulties) + } + + private fun readLicense(element: JsonElement, path: String): License? { + val license = asObject(element, path) ?: return null + warnUnknownFields(license, path, LICENSE_FIELDS) + val type = choice(license, "type", path, LICENSE_NAMES) + val hasSource = "source" in license + val source = if (hasSource) string(license, "source", path) else null + if (type == null || (hasSource && source == null)) return null + return License(type, source) + } + + private fun difficulties(root: JsonObject): List? { + val array = array(root, "difficulties", ROOT) ?: return null + val result = ArrayList(array.size) + for (i in array.indices) { + val path = "difficulties[$i]" + val text = textOf(array[i], path) ?: continue + result += choiceOf(text, path, DIFFICULTY_NAMES) ?: continue + } + return result + } + + private fun readBpm(bpm: JsonObject, path: String): BpmChange? { + warnUnknownFields(bpm, path, BPM_FIELDS) + val t = beat(bpm, "t", path) + val value = double(bpm, "bpm", path) + if (t == null || value == null) return null + return BpmChange(t, value) + } + + private fun readMeter(meter: JsonObject, path: String): MeterChange? { + warnUnknownFields(meter, path, METER_FIELDS) + val t = beat(meter, "t", path) + val num = int(meter, "num", path) + val den = int(meter, "den", path) + if (t == null || num == null || den == null) return null + return MeterChange(t, num, den) + } + + private fun readNote(note: JsonObject, path: String): Note? { + val type = string(note, "type", path) ?: return null + return when (type) { + "tap" -> readTap(note, path) + "hold" -> readHold(note, path) + "skyTap" -> readSkyTap(note, path) + "slide" -> readSlide(note, path) + "flick" -> readFlick(note, path) + else -> { + error( + IssueCode.UNKNOWN_VALUE, + join(path, "type"), + "is \"${shortened(type)}\", must be one of tap, hold, skyTap, slide, flick", + ) + null + } + } + } + + private fun readTap(note: JsonObject, path: String): Note? { + warnUnknownFields(note, path, TAP_FIELDS) + val t = beat(note, "t", path) + val lane = int(note, "lane", path) + if (t == null || lane == null) return null + return Note.Tap(t, lane) + } + + private fun readHold(note: JsonObject, path: String): Note? { + warnUnknownFields(note, path, HOLD_FIELDS) + val t = beat(note, "t", path) + val end = beat(note, "end", path) + val lane = int(note, "lane", path) + if (t == null || end == null || lane == null) return null + return Note.Hold(t, end, lane) + } + + private fun readSkyTap(note: JsonObject, path: String): Note? { + warnUnknownFields(note, path, SKY_TAP_FIELDS) + val t = beat(note, "t", path) + val x = double(note, "x", path) + val y = double(note, "y", path) + val button = choice(note, "button", path, BUTTON_NAMES) + val size = double(note, "size", path) + if (t == null || x == null || y == null || button == null || size == null) return null + return Note.SkyTap(t, x, y, button, size) + } + + private fun readSlide(note: JsonObject, path: String): Note? { + warnUnknownFields(note, path, SLIDE_FIELDS) + val button = choice(note, "button", path, BUTTON_NAMES) + val radius = double(note, "radius", path) + val points = objects(note, "points", path, ::readSlidePoint) + if (button == null || radius == null || points == null) return null + return Note.Slide(button, radius, points) + } + + private fun readSlidePoint(point: JsonObject, path: String): SlidePoint? { + warnUnknownFields(point, path, SLIDE_POINT_FIELDS) + val t = beat(point, "t", path) + val x = double(point, "x", path) + val y = double(point, "y", path) + val ease = choice(point, "ease", path, EASE_NAMES) + if (t == null || x == null || y == null || ease == null) return null + return SlidePoint(t, x, y, ease) + } + + private fun readFlick(note: JsonObject, path: String): Note? { + warnUnknownFields(note, path, FLICK_FIELDS) + val t = beat(note, "t", path) + val x = double(note, "x", path) + val y = double(note, "y", path) + val size = double(note, "size", path) + if (t == null || x == null || y == null || size == null) return null + return Note.Flick(t, x, y, size) + } + + private fun warnUnknownFields(obj: JsonObject, path: String, known: Set) { + for (key in obj.keys) { + if (key !in known) { + add( + ChartIssue( + Severity.WARNING, + IssueCode.UNKNOWN_FIELD, + join(path, shortened(key)), + "is not a known field and was ignored", + ), + ) + } + } + } + + private fun child(obj: JsonObject, key: String, path: String): JsonElement? { + val element = obj[key] + if (element == null) error(IssueCode.MISSING_FIELD, join(path, key), "is missing") + return element + } + + private fun wrongType(path: String, expected: String) { + error(IssueCode.WRONG_TYPE, path, "must be $expected") + } + + private fun asObject(element: JsonElement, path: String): JsonObject? { + if (element !is JsonObject) wrongType(path, "an object") + return element as? JsonObject + } + + private fun array(obj: JsonObject, key: String, path: String): JsonArray? { + val element = child(obj, key, path) ?: return null + if (element !is JsonArray) wrongType(join(path, key), "a list") + return element as? JsonArray + } + + /** Reads a list of objects. Items with errors are left out, which is fine: the file has failed by then. */ + private fun objects( + obj: JsonObject, + key: String, + path: String, + read: (JsonObject, String) -> T?, + ): List? { + val array = array(obj, key, path) ?: return null + val listPath = join(path, key) + val result = ArrayList(array.size) + for (i in array.indices) { + val itemPath = "$listPath[$i]" + val item = asObject(array[i], itemPath) ?: continue + result += read(item, itemPath) ?: continue + } + return result + } + + private fun int(obj: JsonObject, key: String, path: String): Int? { + val element = child(obj, key, path) ?: return null + val value = intOf(element) + if (value == null) wrongType(join(path, key), "a whole number") + return value + } + + private fun intOf(element: JsonElement): Int? { + val number = numberOf(element) ?: return null + return if (JSON_WHOLE_NUMBER.matches(number.content)) number.intOrNull else null + } + + private fun double(obj: JsonObject, key: String, path: String): Double? { + val element = child(obj, key, path) ?: return null + val value = numberOf(element)?.doubleOrNull + if (value == null || !value.isFinite()) { + wrongType(join(path, key), "a number") + return null + } + return value + } + + private fun numberOf(element: JsonElement): JsonPrimitive? { + val primitive = element as? JsonPrimitive ?: return null + if (primitive.isString || primitive is JsonNull) return null + return if (JSON_NUMBER.matches(primitive.content)) primitive else null + } + + private fun string(obj: JsonObject, key: String, path: String): String? { + val element = child(obj, key, path) ?: return null + return textOf(element, join(path, key)) + } + + private fun textOf(element: JsonElement, path: String): String? { + val primitive = element as? JsonPrimitive + if (primitive == null || !primitive.isString) { + wrongType(path, "text") + return null + } + return primitive.content + } + + private fun choice(obj: JsonObject, key: String, path: String, names: List>): T? { + val text = string(obj, key, path) ?: return null + return choiceOf(text, join(path, key), names) + } + + private fun choiceOf(text: String, path: String, names: List>): T? { + for ((name, value) in names) { + if (name == text) return value + } + error(IssueCode.UNKNOWN_VALUE, path, "is \"${shortened(text)}\", must be one of ${names.joinToString { it.first }}") + return null + } + + private fun beat(obj: JsonObject, key: String, path: String): Beat? { + val element = child(obj, key, path) ?: return null + val array = element as? JsonArray + if (array != null && array.size == 3) { + val whole = intOf(array[0]) + val num = intOf(array[1]) + val den = intOf(array[2]) + if (whole != null && num != null && den != null) return Beat(whole, num, den) + } + wrongType(join(path, key), "[whole, numerator, denominator], all whole numbers") + return null + } + + private fun join(path: String, key: String): String = if (path == ROOT) key else "$path.$key" +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartValidator.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartValidator.kt new file mode 100644 index 0000000..30256a9 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartValidator.kt @@ -0,0 +1,479 @@ +package net.trilleo.hexium.core.chart + +import java.math.BigInteger +import net.trilleo.hexium.core.HexiumCore +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.JudgementConfig + +/** The numbers behind the validator's rules (docs/CHART_FORMAT.md). */ +object ChartLimits { + /** A package must be smaller than this. */ + const val MAX_PACKAGE_BYTES: Long = 30L * 1024 * 1024 + + /** A chart or meta file may be this long, counted in characters. */ + const val MAX_JSON_FILE_CHARS: Int = 2 * 1024 * 1024 + + /** The parser stops listing problems after this many. */ + const val MAX_PARSE_ISSUES: Int = 100 + + /** File text repeated in an issue is cut to this length. */ + const val MAX_ISSUE_TEXT_CHARS: Int = 80 + + /** Keeps a huge hold from exhausting memory when its ticks are built. */ + const val MAX_JUDGED_OBJECTS: Int = 1_000_000 + + const val LANE_COUNT: Int = 4 + const val MAX_ID_LENGTH: Int = 64 + + /** The density warning needs at least this many inputs in a window of 1/[DENSITY_WINDOW_DENOMINATOR] beat. */ + const val DENSITY_GROUND_INPUTS: Int = 4 + const val DENSITY_SKY_INPUTS: Int = 1 + const val DENSITY_WINDOW_DENOMINATOR: Int = 16 +} + +/** + * Checks charts against the rules in docs/CHART_FORMAT.md. Never throws: every problem comes + * back as an issue. A bad value is reported once, and rules that need it skip it. + * + * The audio length and package size come from the caller, and their rules are skipped when + * they're null. The server must work them out itself, never trust the uploader's. + */ +object ChartValidator { + fun validateChart(chart: DifficultyChart, audioDurationMs: Double? = null): List = + ChartChecker(chart, audioDurationMs).check() + + fun validateMeta(meta: ChartMeta): List { + val issues = ArrayList() + if (meta.formatVersion != HexiumCore.CHART_FORMAT_VERSION) { + issues += error( + IssueCode.UNKNOWN_FORMAT_VERSION, + "formatVersion", + "is ${meta.formatVersion}, but this version of Hexium reads format ${HexiumCore.CHART_FORMAT_VERSION}", + ) + } + if (!isValidId(meta.id)) { + issues += error( + IssueCode.BAD_ID, + "id", + "is \"${shortened(meta.id)}\", must be 1 to ${ChartLimits.MAX_ID_LENGTH} characters from a-z, 0-9 and -", + ) + } + if (meta.title.isBlank()) issues += error(IssueCode.BLANK_TEXT, "title", "must not be blank") + if (meta.artist.isBlank()) issues += error(IssueCode.BLANK_TEXT, "artist", "must not be blank") + if (meta.charter.isBlank()) issues += error(IssueCode.BLANK_TEXT, "charter", "must not be blank") + if (meta.previewStartMs < 0) { + issues += error(IssueCode.NEGATIVE_PREVIEW, "previewStartMs", "is ${meta.previewStartMs}, must be 0 or more") + } + if (meta.difficulties.isEmpty()) { + issues += error(IssueCode.NO_DIFFICULTIES, "difficulties", "must list at least one difficulty") + } + for (i in meta.difficulties.indices) { + if (meta.difficulties.indexOf(meta.difficulties[i]) != i) { + issues += error(IssueCode.REPEATED_DIFFICULTY, "difficulties[$i]", "${meta.difficulties[i]} is listed twice") + } + } + return issues + } + + fun validatePackage( + pkg: ChartPackage, + audioDurationMs: Double? = null, + packageSizeBytes: Long? = null, + ): List { + val issues = ArrayList() + if (packageSizeBytes != null && packageSizeBytes >= ChartLimits.MAX_PACKAGE_BYTES) { + issues += error( + IssueCode.PACKAGE_TOO_LARGE, + "$", + "is $packageSizeBytes bytes, must be under ${ChartLimits.MAX_PACKAGE_BYTES}", + ) + } + for (issue in validateMeta(pkg.meta)) issues += issue.copy(path = "$META_FILE:${issue.path}") + checkDifficultyFiles(pkg, issues) + for (chart in pkg.charts) { + val file = fileName(chart.difficulty) + for (issue in validateChart(chart, audioDurationMs)) issues += issue.copy(path = "$file:${issue.path}") + } + return issues + } + + private fun checkDifficultyFiles(pkg: ChartPackage, issues: MutableList) { + val listed = pkg.meta.difficulties + for (i in listed.indices) { + if (listed.indexOf(listed[i]) != i) continue + if (pkg.charts.none { it.difficulty == listed[i] }) { + issues += error( + IssueCode.MISSING_DIFFICULTY_FILE, + "$META_FILE:difficulties[$i]", + "lists ${listed[i]}, but the package has no ${fileName(listed[i])}", + ) + } + } + val seen = HashSet() + for (chart in pkg.charts) { + val file = fileName(chart.difficulty) + if (chart.difficulty !in listed) { + issues += error(IssueCode.UNLISTED_DIFFICULTY_FILE, file, "is not listed in $META_FILE") + } + if (!seen.add(chart.difficulty)) { + issues += error(IssueCode.DUPLICATE_DIFFICULTY_FILE, file, "appears more than once in the package") + } + } + } + + private fun isValidId(id: String): Boolean { + if (id.isEmpty() || id.length > ChartLimits.MAX_ID_LENGTH) return false + for (c in id) { + if (c !in 'a'..'z' && c !in '0'..'9' && c != '-') return false + } + return true + } + + /** The name a difficulty's file must have in a package. */ + fun fileName(difficulty: Difficulty): String = "${difficulty.name.lowercase()}.json" + + /** Whoever reads the files checks this, since [ChartPackage] keeps no file names. */ + fun validateFileName(chart: DifficultyChart, fileName: String): List { + val expected = fileName(chart.difficulty) + if (fileName == expected) return emptyList() + return listOf( + error(IssueCode.FILE_NAME_MISMATCH, "$", "holds ${chart.difficulty}, so it must be named $expected, not $fileName"), + ) + } + + private const val META_FILE = "meta.json" +} + +private fun error(code: IssueCode, path: String, message: String) = ChartIssue(Severity.ERROR, code, path, message) + +private fun text(beat: Beat) = "[${beat.whole},${beat.num},${beat.den}]" + +/** A tap or hold whose times are fit for the overlap rules. [end] is null for a tap. */ +private class GroundNote(val t: Beat, val end: Beat?, val path: String) + +/** Where a note starts, for the density warning. */ +private class NoteStart(val t: Beat, val isSky: Boolean, val path: String) + +private class ChartChecker(private val chart: DifficultyChart, private val audioDurationMs: Double?) { + private val issues = ArrayList() + private val groundByLane = LinkedHashMap>() + private val starts = ArrayList() + private var lastEnd: Beat? = null + private var lastEndPath = "" + private var judgedObjects = 0L + + fun check(): List { + checkHeader() + val bpmIsUsable = checkBpm() + val offsetIsUsable = chart.offsetMs.isFinite() + if (!offsetIsUsable) report(IssueCode.OFFSET_NOT_FINITE, "offsetMs", "is ${chart.offsetMs}, must be a finite number") + checkMeter() + for (i in chart.notes.indices) checkNote(chart.notes[i], "notes[$i]") + for (lane in groundByLane.values) checkLaneOverlaps(lane) + if (bpmIsUsable && offsetIsUsable) checkTimes() + if (judgedObjects > ChartLimits.MAX_JUDGED_OBJECTS) { + report(IssueCode.TOO_MANY_JUDGED_OBJECTS, "notes", "has $judgedObjects judged objects, the limit is ${ChartLimits.MAX_JUDGED_OBJECTS}") + } + checkDensity() + return issues + } + + private fun report(code: IssueCode, path: String, message: String) { + issues += error(code, path, message) + } + + private fun checkHeader() { + if (chart.formatVersion != HexiumCore.CHART_FORMAT_VERSION) { + report( + IssueCode.UNKNOWN_FORMAT_VERSION, + "formatVersion", + "is ${chart.formatVersion}, but this version of Hexium reads format ${HexiumCore.CHART_FORMAT_VERSION}", + ) + } + if (chart.level < 1) report(IssueCode.BAD_LEVEL, "level", "is ${chart.level}, must be 1 or more") + if (chart.laneCount != ChartLimits.LANE_COUNT) { + report(IssueCode.BAD_LANE_COUNT, "laneCount", "is ${chart.laneCount}, must be ${ChartLimits.LANE_COUNT}") + } + } + + /** Reports an invalid beat and returns whether it was valid. */ + private fun checkBeat(beat: Beat, path: String): Boolean { + if (beat.isValid) return true + report( + IssueCode.INVALID_BEAT, + path, + "is ${text(beat)}: whole must be 0 or more, and numerator from 0 up to the denominator, which must be above 0", + ) + return false + } + + /** Returns whether the BPM list is fit for the timing map. */ + private fun checkBpm(): Boolean { + val before = issues.size + if (chart.bpm.isEmpty()) report(IssueCode.FIRST_BPM_NOT_AT_ZERO, "bpm", "must have an entry at beat 0") + var previous: Beat? = null + for (i in chart.bpm.indices) { + val change = chart.bpm[i] + if (!TimingMap.isUsableBpm(change.bpm)) { + report(IssueCode.BPM_NOT_POSITIVE, "bpm[$i].bpm", "is ${change.bpm}, must be above 0 and give a finite beat length") + } + val path = "bpm[$i].t" + if (!checkBeat(change.t, path)) continue + if (i == 0 && change.t.compareTo(BEAT_ZERO) != 0) { + report(IssueCode.FIRST_BPM_NOT_AT_ZERO, path, "is ${text(change.t)}, the first entry must be at beat 0") + } + if (previous != null && change.t <= previous) { + report(IssueCode.BPM_NOT_RISING, path, "is ${text(change.t)}, must be after the entry before it (${text(previous)})") + } + previous = change.t + } + return issues.size == before + } + + private fun checkMeter() { + if (chart.meter.isEmpty()) report(IssueCode.FIRST_METER_NOT_AT_ZERO, "meter", "must have an entry at beat 0") + var previous: Beat? = null + for (i in chart.meter.indices) { + val change = chart.meter[i] + if (change.num <= 0) report(IssueCode.METER_NOT_POSITIVE, "meter[$i].num", "is ${change.num}, must be above 0") + if (change.den <= 0) report(IssueCode.METER_NOT_POSITIVE, "meter[$i].den", "is ${change.den}, must be above 0") + val path = "meter[$i].t" + if (!checkBeat(change.t, path)) continue + if (i == 0 && change.t.compareTo(BEAT_ZERO) != 0) { + report(IssueCode.FIRST_METER_NOT_AT_ZERO, path, "is ${text(change.t)}, the first entry must be at beat 0") + } + if (previous != null && change.t <= previous) { + report(IssueCode.METER_NOT_RISING, path, "is ${text(change.t)}, must be after the entry before it (${text(previous)})") + } + previous = change.t + } + } + + private fun checkNote(note: Note, path: String) { + when (note) { + is Note.Tap -> checkTap(note, path) + is Note.Hold -> checkHold(note, path) + is Note.SkyTap -> checkSkyTap(note, path) + is Note.Slide -> checkSlide(note, path) + is Note.Flick -> checkFlick(note, path) + } + } + + private fun checkTap(note: Note.Tap, path: String) { + val laneIsValid = checkLane(note.lane, path) + if (!checkBeat(note.t, "$path.t")) return + starts += NoteStart(note.t, false, path) + noteEnd(note.t, path) + judgedObjects++ + if (laneIsValid) groundNotes(note.lane) += GroundNote(note.t, null, path) + } + + private fun checkHold(note: Note.Hold, path: String) { + val laneIsValid = checkLane(note.lane, path) + val startIsValid = checkBeat(note.t, "$path.t") + val endIsValid = checkBeat(note.end, "$path.end") + if (startIsValid) starts += NoteStart(note.t, false, path) + if (!startIsValid || !endIsValid) return + noteEnd(note.t, path) + noteEnd(note.end, path) + if (note.end <= note.t) { + report( + IssueCode.HOLD_END_NOT_AFTER_START, + "$path.end", + "is ${text(note.end)}, must be after the hold's start (${text(note.t)})", + ) + return + } + judgedObjects += 1 + ticks(note.t, note.end) + if (laneIsValid) groundNotes(note.lane) += GroundNote(note.t, note.end, path) + } + + private fun checkSkyTap(note: Note.SkyTap, path: String) { + checkPosition(note.x, note.y, path) + checkSize(note.size, path) + if (!checkBeat(note.t, "$path.t")) return + starts += NoteStart(note.t, true, path) + noteEnd(note.t, path) + judgedObjects++ + } + + private fun checkSlide(note: Note.Slide, path: String) { + if (!(note.radius > 0.0 && note.radius.isFinite())) { + report(IssueCode.RADIUS_NOT_POSITIVE, "$path.radius", "is ${note.radius}, must be a finite number above 0") + } + if (note.points.size < 2) { + report(IssueCode.SLIDE_TOO_FEW_POINTS, "$path.points", "has ${note.points.size}, must have at least 2") + } + var previous: Beat? = null + var allValid = true + for (i in note.points.indices) { + val point = note.points[i] + val pointPath = "$path.points[$i]" + checkPosition(point.x, point.y, pointPath) + if (!checkBeat(point.t, "$pointPath.t")) { + allValid = false + continue + } + if (previous != null && point.t <= previous) { + report( + IssueCode.SLIDE_POINTS_NOT_RISING, + "$pointPath.t", + "is ${text(point.t)}, must be after the point before it (${text(previous)})", + ) + } + previous = point.t + } + if (note.points.isNotEmpty() && note.points[0].t.isValid) { + starts += NoteStart(note.points[0].t, true, path) + } + if (allValid) { + for (point in note.points) noteEnd(point.t, path) + val last = note.points.lastOrNull() + if (last != null && last.t > note.points[0].t) judgedObjects += ticks(note.points[0].t, last.t) + } + } + + private fun checkFlick(note: Note.Flick, path: String) { + checkPosition(note.x, note.y, path) + checkSize(note.size, path) + if (!checkBeat(note.t, "$path.t")) return + starts += NoteStart(note.t, true, path) + noteEnd(note.t, path) + judgedObjects++ + } + + private fun ticks(start: Beat, end: Beat) = JudgeChart.tickCount(start, end, JudgementConfig.DEFAULT.ticksPerBeat) + + private fun checkLane(lane: Int, path: String): Boolean { + if (lane >= 0 && lane < chart.laneCount) return true + report(IssueCode.LANE_OUT_OF_RANGE, "$path.lane", "is $lane, must be from 0 up to ${chart.laneCount}") + return false + } + + private fun checkPosition(x: Double, y: Double, path: String) { + if (!(x >= 0.0 && x <= 1.0)) report(IssueCode.POSITION_OUT_OF_RANGE, "$path.x", "is $x, must be from 0 to 1") + if (!(y >= 0.0 && y <= 1.0)) report(IssueCode.POSITION_OUT_OF_RANGE, "$path.y", "is $y, must be from 0 to 1") + } + + private fun checkSize(size: Double, path: String) { + if (!(size > 0.0 && size.isFinite())) report(IssueCode.SIZE_NOT_POSITIVE, "$path.size", "is $size, must be a finite number above 0") + } + + private fun groundNotes(lane: Int) = groundByLane.getOrPut(lane) { ArrayList() } + + private fun noteEnd(t: Beat, path: String) { + val last = lastEnd + if (last == null || t > last) { + lastEnd = t + lastEndPath = path + } + } + + /** Walks one lane in time order, in one pass so a huge uploaded chart can't take quadratic time. */ + private fun checkLaneOverlaps(lane: List) { + val sorted = lane.sortedWith(compareBy { it.t }) + var longest: GroundNote? = null + for (note in sorted) { + val end = note.end + if (end == null) continue + val held = longest + if (held != null && note.t < held.end!!) { + report( + IssueCode.HOLDS_OVERLAP, + note.path, + "overlaps the hold at ${held.path}, which runs until ${text(held.end)}", + ) + } + if (held == null || end > held.end!!) longest = note + } + + longest = null + var nextHold = 0 + val holds = sorted.filter { it.end != null } + var previousTap: GroundNote? = null + for (note in sorted) { + if (note.end != null) continue + while (nextHold < holds.size && holds[nextHold].t <= note.t) { + val hold = holds[nextHold++] + val held = longest + if (held == null || hold.end!! > held.end!!) longest = hold + } + val held = longest + if (held != null && note.t < held.end!!) { + report( + IssueCode.TAP_INSIDE_HOLD, + note.path, + "at ${text(note.t)} sits inside the hold at ${held.path}, which runs until ${text(held.end)}", + ) + } + if (previousTap != null && previousTap.t.compareTo(note.t) == 0) { + report(IssueCode.DUPLICATE_TAP, note.path, "is at the same time and lane as the tap at ${previousTap.path}") + } + previousTap = note + } + } + + /** Times must stay finite, or a note could never be judged. */ + private fun checkTimes() { + val timing = TimingMap(chart.offsetMs, chart.bpm) + for (i in chart.bpm.indices) { + if (!timing.beatToMs(chart.bpm[i].t).isFinite()) { + report(IssueCode.TIME_NOT_FINITE, "bpm[$i].t", "is ${text(chart.bpm[i].t)}, too far away to have a time at this BPM") + return + } + } + val end = lastEnd ?: return + val endMs = timing.beatToMs(end) + if (!endMs.isFinite()) { + report(IssueCode.TIME_NOT_FINITE, lastEndPath, "ends at beat ${text(end)}, too far away to have a time at this BPM") + return + } + if (audioDurationMs != null && !(endMs < audioDurationMs)) { + report(IssueCode.NOTE_AFTER_AUDIO, lastEndPath, "ends at $endMs ms, but the audio ends at $audioDurationMs ms") + } + } + + private fun checkDensity() { + val sorted = starts.sortedWith(compareBy { it.t }) + var left = 0 + var ground = 0 + var sky = 0 + var warnedUntil = -1 + for (right in sorted.indices) { + if (sorted[right].isSky) sky++ else ground++ + while (!isInsideDensityWindow(sorted[left].t, sorted[right].t)) { + if (sorted[left].isSky) sky-- else ground-- + left++ + } + if (ground >= ChartLimits.DENSITY_GROUND_INPUTS && sky >= ChartLimits.DENSITY_SKY_INPUTS) { + if (left > warnedUntil) { + issues += ChartIssue( + Severity.WARNING, + IssueCode.TOO_DENSE, + sorted[left].path, + "starts $ground ground and $sky sky inputs within 1/${ChartLimits.DENSITY_WINDOW_DENOMINATOR} beat, " + + "which is hard to play with one hand on the keys", + ) + } + warnedUntil = right + } + } + } + + /** Exact, since denominators can be anything: whether `later - earlier` is under the window. */ + private fun isInsideDensityWindow(earlier: Beat, later: Beat): Boolean { + val wholeBeats = later.whole - earlier.whole + if (wholeBeats > 1) return false + val earlierDen = BigInteger.valueOf(earlier.den.toLong()) + val laterDen = BigInteger.valueOf(later.den.toLong()) + val bothDens = earlierDen * laterDen + val difference = BigInteger.valueOf(wholeBeats.toLong()) * bothDens + + BigInteger.valueOf(later.num.toLong()) * earlierDen - + BigInteger.valueOf(earlier.num.toLong()) * laterDen + return difference * BigInteger.valueOf(ChartLimits.DENSITY_WINDOW_DENOMINATOR.toLong()) < bothDens + } + + private companion object { + val BEAT_ZERO = Beat(0, 0, 1) + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartWriter.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartWriter.kt new file mode 100644 index 0000000..982a29e --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/ChartWriter.kt @@ -0,0 +1,94 @@ +package net.trilleo.hexium.core.chart + +import kotlinx.serialization.json.JsonPrimitive + +/** + * Writes chart files in a fixed layout, one note per line, so the same chart always gives + * the same text and diffs stay readable. It writes what it's given and doesn't validate, + * but throws [IllegalArgumentException] on NaN or infinity, which JSON can't hold. + */ +object ChartWriter { + fun writeDifficulty(chart: DifficultyChart): String = buildString { + append("{\n") + append(" \"formatVersion\": ").append(chart.formatVersion).append(",\n") + append(" \"difficulty\": ").append(text(chart.difficulty.name)).append(",\n") + append(" \"level\": ").append(chart.level).append(",\n") + append(" \"laneCount\": ").append(chart.laneCount).append(",\n") + append(" \"offsetMs\": ").append(number(chart.offsetMs)).append(",\n") + appendList("bpm", chart.bpm) { append(bpmLine(it)) } + append(",\n") + appendList("meter", chart.meter) { append(meterLine(it)) } + append(",\n") + appendList("notes", chart.notes) { appendNote(it) } + append("\n}\n") + } + + fun writeMeta(meta: ChartMeta): String = buildString { + append("{\n") + append(" \"formatVersion\": ").append(meta.formatVersion).append(",\n") + append(" \"id\": ").append(text(meta.id)).append(",\n") + append(" \"title\": ").append(text(meta.title)).append(",\n") + append(" \"artist\": ").append(text(meta.artist)).append(",\n") + append(" \"charter\": ").append(text(meta.charter)).append(",\n") + append(" \"previewStartMs\": ").append(meta.previewStartMs).append(",\n") + append(" \"license\": { \"type\": ").append(text(meta.license.type.id)) + if (meta.license.source != null) append(", \"source\": ").append(text(meta.license.source)) + append(" },\n") + append(" \"difficulties\": [ ") + append(meta.difficulties.joinToString { text(it.name) }) + append(" ]\n}\n") + } + + private fun StringBuilder.appendList(key: String, items: List, appendItem: StringBuilder.(T) -> Unit) { + append(" \"").append(key).append("\": [") + for (i in items.indices) { + append(if (i == 0) "\n " else ",\n ") + appendItem(items[i]) + } + if (items.isNotEmpty()) append("\n ") + append("]") + } + + private fun bpmLine(bpm: BpmChange) = "{ \"t\": ${beat(bpm.t)}, \"bpm\": ${number(bpm.bpm)} }" + + private fun meterLine(meter: MeterChange) = "{ \"t\": ${beat(meter.t)}, \"num\": ${meter.num}, \"den\": ${meter.den} }" + + private fun StringBuilder.appendNote(note: Note) { + when (note) { + is Note.Tap -> append("{ \"type\": \"tap\", \"t\": ${beat(note.t)}, \"lane\": ${note.lane} }") + is Note.Hold -> + append("{ \"type\": \"hold\", \"t\": ${beat(note.t)}, \"end\": ${beat(note.end)}, \"lane\": ${note.lane} }") + is Note.SkyTap -> append( + "{ \"type\": \"skyTap\", \"t\": ${beat(note.t)}, \"x\": ${number(note.x)}, \"y\": ${number(note.y)}, " + + "\"button\": \"${note.button.name}\", \"size\": ${number(note.size)} }", + ) + is Note.Slide -> { + append("{ \"type\": \"slide\", \"button\": \"${note.button.name}\", \"radius\": ${number(note.radius)}, \"points\": [") + for (i in note.points.indices) { + append(if (i == 0) "\n " else ",\n ") + append(slidePointLine(note.points[i])) + } + if (note.points.isNotEmpty()) append("\n ") + append("] }") + } + is Note.Flick -> { + append("{ \"type\": \"flick\", \"t\": ${beat(note.t)}, \"x\": ${number(note.x)}, \"y\": ${number(note.y)}, ") + append("\"size\": ${number(note.size)} }") + } + } + } + + private fun slidePointLine(point: SlidePoint) = + "{ \"t\": ${beat(point.t)}, \"x\": ${number(point.x)}, \"y\": ${number(point.y)}, \"ease\": \"${point.ease.id}\" }" + + private fun beat(beat: Beat) = "[${beat.whole},${beat.num},${beat.den}]" + + private fun text(value: String) = JsonPrimitive(value).toString() + + /** Whole values are written without a decimal point. Other values keep the digits that read back exactly. */ + private fun number(value: Double): String { + require(value.isFinite()) { "JSON can't hold $value" } + val whole = value.toLong() + return if (whole.toDouble().equals(value)) whole.toString() else value.toString() + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/GroundTrack.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/GroundTrack.kt new file mode 100644 index 0000000..d3f28a5 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/GroundTrack.kt @@ -0,0 +1,85 @@ +package net.trilleo.hexium.core.chart + +/** + * A chart's taps and holds in time order, in song milliseconds, for drawing. Lookups don't allocate, so + * they're safe in per-frame code, and keep no position of their own, so time can jump either way. + * + * Expects a chart that passed the validator. + */ +class GroundTrack(chart: DifficultyChart) { + private class Entry(val startMs: Double, val endMs: Double, val lane: Int, val chartNote: Int, val isHold: Boolean) + + private val chartNotes: IntArray + private val lanes: IntArray + private val starts: DoubleArray + private val ends: DoubleArray + private val holds: BooleanArray + + /** The latest end among each note and all before it. It always rises, so it can be searched. */ + private val endsSoFar: DoubleArray + + init { + val timing = TimingMap(chart.offsetMs, chart.bpm) + val entries = ArrayList() + for (i in chart.notes.indices) { + when (val note = chart.notes[i]) { + is Note.Tap -> { + val ms = timing.beatToMs(note.t) + entries += Entry(ms, ms, note.lane, i, false) + } + is Note.Hold -> entries += Entry(timing.beatToMs(note.t), timing.beatToMs(note.end), note.lane, i, true) + else -> {} + } + } + entries.sortWith(compareBy { it.startMs }) + chartNotes = IntArray(entries.size) { entries[it].chartNote } + lanes = IntArray(entries.size) { entries[it].lane } + starts = DoubleArray(entries.size) { entries[it].startMs } + ends = DoubleArray(entries.size) { entries[it].endMs } + holds = BooleanArray(entries.size) { entries[it].isHold } + endsSoFar = DoubleArray(entries.size) + var latest = Double.NEGATIVE_INFINITY + for (i in entries.indices) { + if (ends[i] > latest) latest = ends[i] + endsSoFar[i] = latest + } + } + + val size: Int + get() = starts.size + + fun lane(index: Int): Int = lanes[index] + + /** The note's index in the chart's notes, which is what the judge reports. */ + fun chartNote(index: Int): Int = chartNotes[index] + + fun startMs(index: Int): Double = starts[index] + + /** A tap ends when it starts. */ + fun endMs(index: Int): Double = ends[index] + + fun isHold(index: Int): Boolean = holds[index] + + /** Every note before this index ended before [timeMs]. It's [size] if they all did. */ + fun firstEndingFrom(timeMs: Double): Int { + var low = 0 + var high = endsSoFar.size + while (low < high) { + val middle = (low + high) ushr 1 + if (endsSoFar[middle] < timeMs) low = middle + 1 else high = middle + } + return low + } + + companion object { + /** Offset A in docs/JUDGEMENT.md: a positive offset draws notes later. */ + fun drawTimeMs(songMs: Double, visualOffsetMs: Double): Double = songMs - visualOffsetMs + + /** + * How many blocks a time on a note is up the lane from the judgement line. Negative is past it. + * Speed only changes how far away a note appears, never when it arrives. + */ + fun distance(noteMs: Double, drawMs: Double, blocksPerSecond: Double): Double = + (noteMs - drawMs) * blocksPerSecond / 1000.0 + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/SkyTrack.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/SkyTrack.kt new file mode 100644 index 0000000..7d23c98 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/SkyTrack.kt @@ -0,0 +1,127 @@ +package net.trilleo.hexium.core.chart + +import net.trilleo.hexium.core.judge.JudgementConfig + +/** + * A chart's sky taps, slides and flicks in time order, in song milliseconds, for drawing. A note's + * radius is the judge's hit radius, so what's drawn is what counts. Lookups don't allocate, so + * they're safe in per-frame code, and keep no position of their own, so time can jump either way. + * How far away a note is drawn comes from [GroundTrack.distance], as for ground notes. + * + * Expects a chart that passed the validator. + */ +class SkyTrack(chart: DifficultyChart, config: JudgementConfig = JudgementConfig.DEFAULT) { + enum class Kind { TAP, SLIDE, FLICK } + + private class Entry( + val kind: Kind, + val startMs: Double, + val endMs: Double, + val x: Double, + val y: Double, + val button: SkyButton?, + val radius: Double, + val chartNote: Int, + val path: SlidePath?, + ) + + private val timing = TimingMap(chart.offsetMs, chart.bpm) + private val kinds: Array + private val starts: DoubleArray + private val ends: DoubleArray + private val xs: DoubleArray + private val ys: DoubleArray + private val buttons: Array + private val radii: DoubleArray + private val chartNotes: IntArray + private val paths: Array + + /** The latest end among each note and all before it. It always rises, so it can be searched. */ + private val endsSoFar: DoubleArray + + init { + val entries = ArrayList() + for (i in chart.notes.indices) { + when (val note = chart.notes[i]) { + is Note.SkyTap -> { + val ms = timing.beatToMs(note.t) + entries += Entry(Kind.TAP, ms, ms, note.x, note.y, note.button, config.baseHitRadius * note.size, i, null) + } + is Note.Flick -> { + val ms = timing.beatToMs(note.t) + entries += Entry(Kind.FLICK, ms, ms, note.x, note.y, null, config.baseHitRadius * note.size, i, null) + } + is Note.Slide -> { + val first = note.points.first() + entries += Entry( + Kind.SLIDE, timing.beatToMs(first.t), timing.beatToMs(note.points.last().t), + first.x, first.y, note.button, note.radius, i, SlidePath(note.points), + ) + } + else -> {} + } + } + // Stable, so notes at the same time keep the chart's order. + entries.sortWith(compareBy { it.startMs }) + kinds = Array(entries.size) { entries[it].kind } + starts = DoubleArray(entries.size) { entries[it].startMs } + ends = DoubleArray(entries.size) { entries[it].endMs } + xs = DoubleArray(entries.size) { entries[it].x } + ys = DoubleArray(entries.size) { entries[it].y } + buttons = Array(entries.size) { entries[it].button } + radii = DoubleArray(entries.size) { entries[it].radius } + chartNotes = IntArray(entries.size) { entries[it].chartNote } + paths = Array(entries.size) { entries[it].path } + endsSoFar = DoubleArray(entries.size) + var latest = Double.NEGATIVE_INFINITY + for (i in entries.indices) { + if (ends[i] > latest) latest = ends[i] + endsSoFar[i] = latest + } + } + + val size: Int + get() = starts.size + + /** The screen's width over its height. A hit circle [radius] high is `radius / screenAspect` wide in x's units. */ + val screenAspect: Double = config.screenAspect + + fun kind(index: Int): Kind = kinds[index] + + /** The note's index in the chart's notes, which is what the judge reports. */ + fun chartNote(index: Int): Int = chartNotes[index] + + fun startMs(index: Int): Double = starts[index] + + /** A tap or flick ends when it starts. */ + fun endMs(index: Int): Double = ends[index] + + /** The button a tap or slide needs, or null for a flick. */ + fun button(index: Int): SkyButton? = buttons[index] + + /** The hit radius, as a fraction of the screen's height, measured with [screenAspect] (docs/JUDGEMENT.md). */ + fun radius(index: Int): Double = radii[index] + + /** Where the note is across the screen at [timeMs], 0 (left) to 1 (right). Only a slide moves. */ + fun x(index: Int, timeMs: Double): Double { + val path = paths[index] ?: return xs[index] + return path.x(timing.msToBeat(timeMs)) + } + + /** Where the note is up the screen at [timeMs], 0 (bottom) to 1 (top). Only a slide moves. */ + fun y(index: Int, timeMs: Double): Double { + val path = paths[index] ?: return ys[index] + return path.y(timing.msToBeat(timeMs)) + } + + /** Every note before this index ended before [timeMs]. It's [size] if they all did. */ + fun firstEndingFrom(timeMs: Double): Int { + var low = 0 + var high = endsSoFar.size + while (low < high) { + val middle = (low + high) ushr 1 + if (endsSoFar[middle] < timeMs) low = middle + 1 else high = middle + } + return low + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/SlidePath.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/SlidePath.kt new file mode 100644 index 0000000..49b19b0 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/SlidePath.kt @@ -0,0 +1,31 @@ +package net.trilleo.hexium.core.chart + +/** + * Where a slide is at any beat, shared by the judge and the renderer. Lookups don't allocate. + * Before the first point and after the last, the position stays on that point. Expects points + * that passed the validator. + */ +class SlidePath(points: List) { + private val beats = DoubleArray(points.size) { points[it].t.toDouble() } + private val xs = DoubleArray(points.size) { points[it].x } + private val ys = DoubleArray(points.size) { points[it].y } + private val eases = Array(points.size) { points[it].ease } + + fun x(beat: Double): Double = position(xs, beat) + + fun y(beat: Double): Double = position(ys, beat) + + private fun position(values: DoubleArray, beat: Double): Double { + if (beat <= beats[0]) return values[0] + val last = beats.size - 1 + if (beat >= beats[last]) return values[last] + var low = 0 + var high = last - 1 + while (low < high) { + val middle = (low + high + 1) ushr 1 + if (beats[middle] <= beat) low = middle else high = middle - 1 + } + val t = (beat - beats[low]) / (beats[low + 1] - beats[low]) + return values[low] + (values[low + 1] - values[low]) * eases[low].progress(t) + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/chart/TimingMap.kt b/core/src/main/kotlin/net/trilleo/hexium/core/chart/TimingMap.kt new file mode 100644 index 0000000..5a84f72 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/chart/TimingMap.kt @@ -0,0 +1,64 @@ +package net.trilleo.hexium.core.chart + +/** + * Turns beats into song milliseconds using `offsetMs` and the BPM list. Lookups don't + * allocate, so they're safe in per-frame code. + * + * Expects BPM data that passed the validator, and throws [IllegalArgumentException] if it + * didn't: running a chart without validating it is a programming error. + */ +class TimingMap(offsetMs: Double, bpm: List) { + private val startBeat = DoubleArray(bpm.size) + private val startMs = DoubleArray(bpm.size) + private val msPerBeat = DoubleArray(bpm.size) + + init { + require(offsetMs.isFinite()) { "Offset is not finite" } + require(bpm.isNotEmpty()) { "BPM list is empty" } + for (i in bpm.indices) { + val change = bpm[i] + require(change.t.isValid) { "BPM entry $i has an invalid time" } + require(isUsableBpm(change.bpm)) { "BPM entry $i is not a finite number above 0 with a finite beat length" } + startBeat[i] = change.t.toDouble() + msPerBeat[i] = MS_PER_MINUTE / change.bpm + if (i == 0) { + require(startBeat[0] == 0.0) { "First BPM entry is not at beat 0" } + startMs[0] = offsetMs + } else { + require(change.t > bpm[i - 1].t) { "BPM entry $i does not rise in time" } + startMs[i] = startMs[i - 1] + (startBeat[i] - startBeat[i - 1]) * msPerBeat[i - 1] + } + } + } + + fun beatToMs(beat: Beat): Double = beatToMs(beat.toDouble()) + + fun beatToMs(beat: Double): Double { + // Binary search for the last segment starting at or before this beat. + var low = 0 + var high = startBeat.size - 1 + while (low < high) { + val middle = (low + high + 1) ushr 1 + if (startBeat[middle] <= beat) low = middle else high = middle - 1 + } + return startMs[low] + (beat - startBeat[low]) * msPerBeat[low] + } + + /** The inverse of [beatToMs]. */ + fun msToBeat(ms: Double): Double { + var low = 0 + var high = startMs.size - 1 + while (low < high) { + val middle = (low + high + 1) ushr 1 + if (startMs[middle] <= ms) low = middle else high = middle - 1 + } + return startBeat[low] + (ms - startMs[low]) / msPerBeat[low] + } + + internal companion object { + private const val MS_PER_MINUTE = 60000.0 + + /** Very small values pass "above 0" but make a beat infinitely long, which turns times into NaN. */ + fun isUsableBpm(bpm: Double): Boolean = bpm > 0.0 && bpm.isFinite() && (MS_PER_MINUTE / bpm).isFinite() + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/clock/SongClock.kt b/core/src/main/kotlin/net/trilleo/hexium/core/clock/SongClock.kt new file mode 100644 index 0000000..fff4f65 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/clock/SongClock.kt @@ -0,0 +1,101 @@ +package net.trilleo.hexium.core.clock + +import kotlin.math.abs + +/** + * Song time from a steady wall clock, gently pulled toward the audio position. The raw position + * only moves in steps, so it can't place notes itself, but over a song it decides where the music + * is. Knows nothing about where its numbers come from, so the mod feeds it and tests can too. + * + * Doesn't allocate. + */ +class SongClock { + private var baseSongMs = 0.0 + private var baseWallNs = 0L + private var lastObservedNs = 0L + /** [nowMs] never returns less than this, except after [start]. */ + private var floorMs = Double.NEGATIVE_INFINITY + + var running = false + private set + + /** The audio position minus the clock, at the last [observe]. Positive means the music is ahead. */ + var driftMs = 0.0 + private set + + /** The largest [driftMs] either way since [start]. */ + var maxDriftMs = 0.0 + private set + + /** How many times the audio was too far away to pull toward, since this clock was made. */ + var resyncCount = 0 + private set + + /** Starts running from [songMs]. */ + fun start(songMs: Double, wallNs: Long) { + seek(songMs, wallNs) + running = true + } + + /** Moves to [songMs], running or paused as it was. Starting and seeking are the only ways time can go backwards. */ + fun seek(songMs: Double, wallNs: Long) { + baseSongMs = songMs + baseWallNs = wallNs + lastObservedNs = wallNs + floorMs = Double.NEGATIVE_INFINITY + driftMs = 0.0 + maxDriftMs = 0.0 + } + + fun pause(wallNs: Long) { + if (!running) return + baseSongMs = nowMs(wallNs) + baseWallNs = wallNs + running = false + } + + /** Tells the clock where the audio is. Call once per frame. A position that isn't finite is ignored. */ + fun observe(audioMs: Double, wallNs: Long) { + if (!running || !audioMs.isFinite()) return + val sinceLastNs = wallNs - lastObservedNs + if (sinceLastNs <= 0L) return + lastObservedNs = wallNs + + val error = audioMs - mapMs(wallNs) + driftMs = error + if (abs(error) > maxDriftMs) maxDriftMs = abs(error) + if (abs(error) > RESYNC_MS) { + baseSongMs = audioMs + baseWallNs = wallNs + resyncCount++ + return + } + // This is a share of the time passed, so it's the same at any frame rate. Since the error is + // under RESYNC_MS, the pull is always less than the time passed, so time never reverses. + val share = sinceLastNs / NANOS_PER_MS / PULL_TIME_MS + baseSongMs += error * (if (share < 1.0) share else 1.0) + } + + /** Song time at [wallNs], for an input timestamp. May be earlier than [nowMs] has already returned. */ + fun mapMs(wallNs: Long): Double { + if (!running) return baseSongMs + return baseSongMs + (wallNs - baseWallNs) / NANOS_PER_MS + } + + /** Song time for this frame. Never goes backwards. */ + fun nowMs(wallNs: Long): Double { + val time = mapMs(wallNs) + if (time > floorMs) floorMs = time + return floorMs + } + + private companion object { + const val NANOS_PER_MS = 1_000_000.0 + + /** Longer smooths out the steps better. Shorter follows a sound card's own speed more closely. */ + const val PULL_TIME_MS = 1000.0 + + /** Past this, something has happened, such as an audio stall. Pulling would take too long. */ + const val RESYNC_MS = 100.0 + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/judge/Judge.kt b/core/src/main/kotlin/net/trilleo/hexium/core/judge/Judge.kt new file mode 100644 index 0000000..0b00020 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/judge/Judge.kt @@ -0,0 +1,402 @@ +package net.trilleo.hexium.core.judge + +import net.trilleo.hexium.core.chart.SkyButton + +/** + * Judges one play of a chart from timestamped input, in song milliseconds. The mod calls this + * every frame and the server calls it with a replay, through the same code, so both get the + * same result. Nothing here allocates after construction. + * + * Results don't depend on how often [advanceTo] is called, only on the input. Time can't go + * backwards: an input older than the current time counts as happening now. Live play goes + * through [net.trilleo.hexium.core.replay.PlayInput] and + * [net.trilleo.hexium.core.replay.ReplayRecorder], which records it that way too. + * + * All times passed in are raw song time: [judgementOffsetMs] (offset B) is subtracted from them. + * + * Crosshair positions are normalised screen coordinates, as in chart files, and may lie off the + * screen. They're floats so a replay can store exactly what the judge saw. + */ +class Judge(private val chart: JudgeChart, private val judgementOffsetMs: Double = 0.0) { + private val config = chart.config + private val weights = intArrayOf( + config.justiceCriticalWeightPercent, + config.justiceWeightPercent, + config.attackWeightPercent, + config.missWeightPercent, + ) + + private var now = Double.NEGATIVE_INFINITY + + private val nextPress = IntArray(chart.laneCount) + private val laneDown = BooleanArray(chart.laneCount) + private val laneLastDownMs = DoubleArray(chart.laneCount) { Double.NEGATIVE_INFINITY } + private var nextTick = 0 + + private val skyNext = IntArray(SkyButton.entries.size) + private val skyJudged = Array(SkyButton.entries.size) { BooleanArray(chart.skyMs[it].size) } + private val buttonDown = BooleanArray(SkyButton.entries.size) + + private val slideLastHeldMs = DoubleArray(chart.slideCount) { Double.NEGATIVE_INFINITY } + private val activeSlides = IntArray(chart.slideCount) + private var activeSlideCount = 0 + private var nextSlide = 0 + + private var nextFlick = 0 + private val flickJudged = BooleanArray(chart.flickMs.size) + /** A flick can't be given up on until a sample has passed its deadline: a swipe may still be under way. */ + private var flickSeenUntilMs = Double.NEGATIVE_INFINITY + private var hasAim = false + private var aimMs = 0.0 + private var aimX = 0.0 + private var aimY = 0.0 + + private val judgedObject = IntArray(chart.objectCount) + private val judgedResult = Array(chart.objectCount) { Judgement.MISS } + private val judgedDelta = DoubleArray(chart.objectCount) + private val counts = IntArray(weights.size) + private var weightSum = 0L + + val objectCount: Int + get() = chart.objectCount + + /** How many objects have been judged. Results stay in this order, so a reader can keep its own position. */ + var judgedCount = 0 + private set + var combo = 0 + private set + var maxCombo = 0 + private set + + val score: Int + get() { + if (chart.objectCount == 0) return 0 + return (config.perfectScoreBase * weightSum / (100L * chart.objectCount)).toInt() + } + + /** [ClearLamp.NONE] until every object is judged. */ + val clearLamp: ClearLamp + get() { + if (chart.objectCount == 0 || judgedCount < chart.objectCount) return ClearLamp.NONE + if (count(Judgement.MISS) > 0) return ClearLamp.NONE + if (count(Judgement.ATTACK) > 0) return ClearLamp.FULL_COMBO + if (count(Judgement.JUSTICE) > 0) return ClearLamp.ALL_JUSTICE + return ClearLamp.ALL_JUSTICE_CRITICAL + } + + fun count(judgement: Judgement): Int = counts[judgement.ordinal] + + fun judgement(index: Int): Judgement = judgedResult[index] + + /** The judged object's index in the chart's notes. */ + fun judgedNote(index: Int): Int = chart.objectNote[judgedObject[index]] + + /** False for hold and slide ticks: their delta is how long ago the input was held, not how well it was timed. */ + fun judgedIsPress(index: Int): Boolean = chart.tickObject.isEmpty() || judgedObject[index] < chart.tickObject[0] + + /** Input time minus target time. Negative is early. NaN if there was no input to measure. */ + fun judgedDeltaMs(index: Int): Double = judgedDelta[index] + + /** Judges everything due before [timeMs]. */ + fun advanceTo(timeMs: Double) { + val time = timeMs - judgementOffsetMs + if (time > now) now = time + settleBefore(now, waitForFlicks = true) + } + + /** An input changes what's held, so everything due before it must be judged first. */ + private fun settleForInput(timeMs: Double) { + val time = timeMs - judgementOffsetMs + if (time > now) now = time + settleBefore(now, waitForFlicks = false) + } + + /** Judges everything left, once the song is over. */ + fun finish() { + flickSeenUntilMs = Double.POSITIVE_INFINITY + settleBefore(Double.POSITIVE_INFINITY, waitForFlicks = false) + } + + /** Records where the crosshair is. Call once per frame: slides and flicks are judged from these samples. */ + fun aimSample(timeMs: Double, x: Float, y: Float) { + val time = timeMs - judgementOffsetMs + if (time > now) now = time + flickSeenUntilMs = now + val sampleX = x.toDouble() + val sampleY = y.toDouble() + if (hasAim && now > aimMs) judgeFlicksAlong(sampleX, sampleY) + settleBefore(now, waitForFlicks = false) + updateSlides(sampleX, sampleY) + hasAim = true + aimMs = now + aimX = sampleX + aimY = sampleY + } + + fun pressButton(button: SkyButton, timeMs: Double, x: Float, y: Float) { + val b = button.ordinal + if (buttonDown[b]) return + settleForInput(timeMs) + buttonDown[b] = true + val clickX = x.toDouble() + val clickY = y.toDouble() + updateSlides(clickX, clickY) + + val targets = chart.skyMs[b] + val judged = skyJudged[b] + var i = skyNext[b] + while (i < targets.size && targets[i] - now <= config.earlyMissMs) { + if (!judged[i] && isInside(clickX, clickY, chart.skyX[b][i], chart.skyY[b][i], chart.skyRadius[b][i])) { + judged[i] = true + val delta = now - targets[i] + record(chart.skyObject[b][i], pressJudgement(delta), delta) + advanceSkyNext(b) + return + } + i++ + } + } + + fun releaseButton(button: SkyButton, timeMs: Double) { + val b = button.ordinal + if (!buttonDown[b]) return + settleForInput(timeMs) + buttonDown[b] = false + } + + private fun advanceSkyNext(button: Int) { + val judged = skyJudged[button] + var i = skyNext[button] + while (i < judged.size && judged[i]) i++ + skyNext[button] = i + } + + private fun isInside(x: Double, y: Double, centreX: Double, centreY: Double, radius: Double): Boolean { + val dx = (x - centreX) * config.screenAspect + val dy = y - centreY + return dx * dx + dy * dy <= radius * radius + } + + /** Brings each slide being played up to date with a crosshair position at the current time. */ + private fun updateSlides(x: Double, y: Double) { + while (nextSlide < chart.slideCount && chart.slideStartMs[nextSlide] - config.tickAttackMs <= now) { + activeSlides[activeSlideCount++] = nextSlide++ + } + if (activeSlideCount == 0) return + val beat = chart.timing.msToBeat(now) + var i = 0 + while (i < activeSlideCount) { + val slide = activeSlides[i] + if (now > chart.slideEndMs[slide]) { + activeSlides[i] = activeSlides[--activeSlideCount] + continue + } + if (buttonDown[chart.slideButton[slide]]) { + val path = chart.slidePath[slide] + if (isInside(x, y, path.x(beat), path.y(beat), chart.slideRadius[slide])) { + slideLastHeldMs[slide] = now + } + } + i++ + } + } + + /** Judges flicks crossed by the swipe from the last sample to this one, in the order they're crossed. */ + private fun judgeFlicksAlong(toX: Double, toY: Double) { + val dt = now - aimMs + val dx = (toX - aimX) * config.screenAspect + val dy = toY - aimY + val length = Math.sqrt(dx * dx + dy * dy) + if (length * 1000.0 / dt <= config.flickMinSpeed) return + while (true) { + var crossed = -1 + var crossedAtMs = Double.POSITIVE_INFINITY + var i = nextFlick + while (i < flickJudged.size && chart.flickMs[i] - config.flickJusticeMs <= now) { + if (!flickJudged[i]) { + val atMs = crossingInWindowMs(i, dx, dy, dt) + if (atMs < crossedAtMs && atMs - chart.flickMs[i] <= config.flickJusticeMs) { + crossed = i + crossedAtMs = atMs + } + } + i++ + } + if (crossed < 0) return + settleBefore(crossedAtMs, waitForFlicks = false) + judgeFlick(crossed, crossedAtMs) + } + } + + /** + * When the swipe crosses a flick inside its window, or infinity if it doesn't. A swipe that entered + * earlier and is still inside when the window opens counts as crossing at that moment. + */ + private fun crossingInWindowMs(flick: Int, dx: Double, dy: Double, dt: Double): Double { + val enteredMs = crossingMs(flick, dx, dy, dt) + val opensMs = chart.flickMs[flick] - config.flickJusticeMs + if (enteredMs >= opensMs || enteredMs == Double.POSITIVE_INFINITY) return enteredMs + val u = (opensMs - aimMs) / dt + val fromX = (aimX - chart.flickX[flick]) * config.screenAspect + dx * u + val fromY = aimY - chart.flickY[flick] + dy * u + val radius = chart.flickRadius[flick] + return if (fromX * fromX + fromY * fromY <= radius * radius) opensMs else Double.POSITIVE_INFINITY + } + + /** When the swipe first enters a flick's hit area, or infinity if it doesn't. */ + private fun crossingMs(flick: Int, dx: Double, dy: Double, dt: Double): Double { + val fromX = (aimX - chart.flickX[flick]) * config.screenAspect + val fromY = aimY - chart.flickY[flick] + val radius = chart.flickRadius[flick] + val c = fromX * fromX + fromY * fromY - radius * radius + if (c <= 0.0) return aimMs + val a = dx * dx + dy * dy + val b = fromX * dx + fromY * dy + val discriminant = b * b - a * c + if (b >= 0.0 || discriminant < 0.0) return Double.POSITIVE_INFINITY + val u = (-b - Math.sqrt(discriminant)) / a + return if (u <= 1.0) aimMs + u * dt else Double.POSITIVE_INFINITY + } + + private fun judgeFlick(flick: Int, atMs: Double) { + flickJudged[flick] = true + val delta = atMs - chart.flickMs[flick] + val distance = Math.abs(delta) + val judgement = if (distance <= config.flickJusticeCriticalMs) Judgement.JUSTICE_CRITICAL else Judgement.JUSTICE + record(chart.flickObject[flick], judgement, delta) + advanceNextFlick() + } + + private fun advanceNextFlick() { + while (nextFlick < flickJudged.size && flickJudged[nextFlick]) nextFlick++ + } + + fun pressLane(lane: Int, timeMs: Double) { + if (lane < 0 || lane >= chart.laneCount || laneDown[lane]) return + settleForInput(timeMs) + laneDown[lane] = true + laneLastDownMs[lane] = now + val next = nextPress[lane] + val targets = chart.pressMs[lane] + if (next >= targets.size) return + val delta = now - targets[next] + if (delta < -config.earlyMissMs) return + nextPress[lane] = next + 1 + record(chart.pressObject[lane][next], pressJudgement(delta), delta) + } + + fun releaseLane(lane: Int, timeMs: Double) { + if (lane < 0 || lane >= chart.laneCount || !laneDown[lane]) return + settleForInput(timeMs) + laneDown[lane] = false + laneLastDownMs[lane] = now + } + + /** + * Judges notes nobody hit and ticks due before [requestedLimit], earliest first. At equal times, + * ground notes go before sky taps, sky taps before flicks, and all of them before ticks. + * + * With [waitForFlicks], it stops at the last sample once a flick's window has opened: a swipe may + * still be under way, and judging past it would make the order of results depend on how often + * [advanceTo] is called. A flick's own Miss always waits for a sample past its deadline. + */ + private fun settleBefore(requestedLimit: Double, waitForFlicks: Boolean) { + while (true) { + var limit = requestedLimit + if (waitForFlicks && nextFlick < flickJudged.size) { + val opens = chart.flickMs[nextFlick] - config.flickJusticeMs + val canSettleTo = if (flickSeenUntilMs > opens) flickSeenUntilMs else opens + if (canSettleTo < limit) limit = canSettleTo + } + var lane = -1 + var button = -1 + var flickIsDue = false + var dueMs = limit + for (i in nextPress.indices) { + if (nextPress[i] < chart.pressMs[i].size) { + val deadline = chart.pressMs[i][nextPress[i]] + chart.attackWindowMs + if (deadline < dueMs) { + dueMs = deadline + lane = i + } + } + } + for (i in skyNext.indices) { + if (skyNext[i] < chart.skyMs[i].size) { + val deadline = chart.skyMs[i][skyNext[i]] + chart.attackWindowMs + if (deadline < dueMs) { + dueMs = deadline + lane = -1 + button = i + } + } + } + if (nextFlick < flickJudged.size) { + val deadline = chart.flickMs[nextFlick] + config.flickJusticeMs + if (deadline < dueMs && deadline < flickSeenUntilMs) { + dueMs = deadline + lane = -1 + button = -1 + flickIsDue = true + } + } + if (nextTick < chart.tickMs.size && chart.tickMs[nextTick] < dueMs) { + judgeTick() + } else if (lane >= 0) { + record(chart.pressObject[lane][nextPress[lane]], Judgement.MISS, Double.NaN) + nextPress[lane]++ + } else if (button >= 0) { + val next = skyNext[button] + skyJudged[button][next] = true + record(chart.skyObject[button][next], Judgement.MISS, Double.NaN) + advanceSkyNext(button) + } else if (flickIsDue) { + flickJudged[nextFlick] = true + record(chart.flickObject[nextFlick], Judgement.MISS, Double.NaN) + advanceNextFlick() + } else { + return + } + } + } + + private fun judgeTick() { + val tick = nextTick++ + val tickMs = chart.tickMs[tick] + val lane = chart.tickLane[tick] + val age = when { + lane < 0 -> tickMs - slideLastHeldMs[chart.tickSlide[tick]] + laneDown[lane] -> 0.0 + else -> tickMs - laneLastDownMs[lane] + } + record(chart.tickObject[tick], tickJudgement(age), if (age == Double.POSITIVE_INFINITY) Double.NaN else 0.0 - age) + } + + private fun pressJudgement(delta: Double): Judgement { + val distance = if (delta < 0.0) -delta else delta + return when { + distance <= config.justiceCriticalMs -> Judgement.JUSTICE_CRITICAL + distance <= config.justiceMs -> Judgement.JUSTICE + distance <= chart.attackWindowMs -> Judgement.ATTACK + else -> Judgement.MISS + } + } + + private fun tickJudgement(age: Double): Judgement = when { + age <= config.tickJusticeCriticalMs -> Judgement.JUSTICE_CRITICAL + age <= config.tickJusticeMs -> Judgement.JUSTICE + age <= config.tickAttackMs -> Judgement.ATTACK + else -> Judgement.MISS + } + + private fun record(obj: Int, judgement: Judgement, deltaMs: Double) { + val index = judgedCount++ + judgedObject[index] = obj + judgedResult[index] = judgement + judgedDelta[index] = deltaMs + counts[judgement.ordinal]++ + weightSum += weights[judgement.ordinal] + combo = if (judgement == Judgement.MISS) 0 else combo + 1 + if (combo > maxCombo) maxCombo = combo + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/judge/JudgeChart.kt b/core/src/main/kotlin/net/trilleo/hexium/core/judge/JudgeChart.kt new file mode 100644 index 0000000..68029f3 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/judge/JudgeChart.kt @@ -0,0 +1,196 @@ +package net.trilleo.hexium.core.judge + +import java.math.BigInteger +import net.trilleo.hexium.core.chart.Beat +import net.trilleo.hexium.core.chart.ChartLimits +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.SlidePath +import net.trilleo.hexium.core.chart.TimingMap + +/** + * A chart turned into the flat arrays the judge walks, built once when a chart loads so that + * playing it doesn't allocate. Every judged object (tap, hold head, sky tap, flick, tick) has an id. + * + * Expects a chart that passed the validator. + */ +class JudgeChart private constructor( + val config: JudgementConfig, + internal val attackWindowMs: Double, + val objectCount: Int, + internal val objectNote: IntArray, + internal val pressObject: Array, + internal val pressMs: Array, + internal val tickObject: IntArray, + internal val tickMs: DoubleArray, + /** The tick's lane, or -1 for a slide tick. */ + internal val tickLane: IntArray, + internal val tickSlide: IntArray, + internal val timing: TimingMap, + internal val skyObject: Array, + internal val skyMs: Array, + internal val skyX: Array, + internal val skyY: Array, + internal val skyRadius: Array, + internal val flickObject: IntArray, + internal val flickMs: DoubleArray, + internal val flickX: DoubleArray, + internal val flickY: DoubleArray, + internal val flickRadius: DoubleArray, + internal val slideStartMs: DoubleArray, + internal val slideEndMs: DoubleArray, + internal val slideButton: IntArray, + internal val slideRadius: DoubleArray, + internal val slidePath: Array, +) { + val laneCount: Int + get() = pressMs.size + + internal val slideCount: Int + get() = slideStartMs.size + + private class Press(val ms: Double, val note: Int, val lane: Int) + + private class Tick(val ms: Double, val note: Int, val lane: Int, val slide: Int) + + private class Sky(val ms: Double, val note: Int, val tap: Note.SkyTap) + + private class Flick(val ms: Double, val note: Int, val flick: Note.Flick) + + private class Slide(val startMs: Double, val endMs: Double, val note: Int, val slide: Note.Slide) + + companion object { + fun compile(chart: DifficultyChart, config: JudgementConfig = JudgementConfig.DEFAULT): JudgeChart { + val timing = TimingMap(chart.offsetMs, chart.bpm) + val presses = ArrayList() + val ticks = ArrayList() + val skyTaps = ArrayList() + val flicks = ArrayList() + val slides = ArrayList() + for (i in chart.notes.indices) { + when (val note = chart.notes[i]) { + is Note.Tap -> presses += Press(timing.beatToMs(note.t), i, note.lane) + is Note.Hold -> { + presses += Press(timing.beatToMs(note.t), i, note.lane) + val count = tickCount(note.t, note.end, config.ticksPerBeat) + require(presses.size + ticks.size + count <= ChartLimits.MAX_JUDGED_OBJECTS) { "Too many judged objects" } + for (k in 0 until count.toInt()) { + ticks += Tick(timing.beatToMs(tickBeat(note.t, note.end, k, count, config.ticksPerBeat)), i, note.lane, -1) + } + } + is Note.SkyTap -> skyTaps += Sky(timing.beatToMs(note.t), i, note) + is Note.Flick -> flicks += Flick(timing.beatToMs(note.t), i, note) + is Note.Slide -> slides += Slide(timing.beatToMs(note.points.first().t), timing.beatToMs(note.points.last().t), i, note) + } + } + presses.sortWith(compareBy { it.ms }) + skyTaps.sortWith(compareBy { it.ms }) + flicks.sortWith(compareBy { it.ms }) + slides.sortWith(compareBy { it.startMs }) + for (s in slides.indices) { + val start = slides[s].slide.points.first().t + val end = slides[s].slide.points.last().t + val count = tickCount(start, end, config.ticksPerBeat) + require(presses.size + ticks.size + skyTaps.size + flicks.size + count <= ChartLimits.MAX_JUDGED_OBJECTS) { + "Too many judged objects" + } + for (k in 0 until count.toInt()) { + ticks += Tick(timing.beatToMs(tickBeat(start, end, k, count, config.ticksPerBeat)), slides[s].note, -1, s) + } + } + ticks.sortWith(compareBy { it.ms }) + + val objectCount = presses.size + skyTaps.size + flicks.size + ticks.size + val objectNote = IntArray(objectCount) + var nextObject = 0 + val pressObject = Array(chart.laneCount) { lane -> IntArray(presses.count { it.lane == lane }) } + val pressMs = Array(chart.laneCount) { DoubleArray(pressObject[it].size) } + val filled = IntArray(chart.laneCount) + for (press in presses) { + val slot = filled[press.lane]++ + pressObject[press.lane][slot] = nextObject + pressMs[press.lane][slot] = press.ms + objectNote[nextObject++] = press.note + } + val buttons = SkyButton.entries + val skyByButton = Array(buttons.size) { b -> skyTaps.filter { it.tap.button == buttons[b] } } + val skyObject = Array(buttons.size) { IntArray(skyByButton[it].size) } + for (b in buttons.indices) { + for (i in skyByButton[b].indices) { + skyObject[b][i] = nextObject + objectNote[nextObject++] = skyByButton[b][i].note + } + } + val flickObject = IntArray(flicks.size) + for (i in flicks.indices) { + flickObject[i] = nextObject + objectNote[nextObject++] = flicks[i].note + } + val tickObject = IntArray(ticks.size) + val tickMs = DoubleArray(ticks.size) + val tickLane = IntArray(ticks.size) + val tickSlide = IntArray(ticks.size) + for (i in ticks.indices) { + tickObject[i] = nextObject + tickMs[i] = ticks[i].ms + tickLane[i] = ticks[i].lane + tickSlide[i] = ticks[i].slide + objectNote[nextObject++] = ticks[i].note + } + val isEasy = chart.difficulty == Difficulty.BASIC || chart.difficulty == Difficulty.ADVANCED + return JudgeChart( + config, + if (isEasy) config.easyAttackMs else config.attackMs, + objectCount, + objectNote, + pressObject, + pressMs, + tickObject, + tickMs, + tickLane, + tickSlide, + timing, + skyObject, + Array(buttons.size) { b -> DoubleArray(skyByButton[b].size) { skyByButton[b][it].ms } }, + Array(buttons.size) { b -> DoubleArray(skyByButton[b].size) { skyByButton[b][it].tap.x } }, + Array(buttons.size) { b -> DoubleArray(skyByButton[b].size) { skyByButton[b][it].tap.y } }, + Array(buttons.size) { b -> DoubleArray(skyByButton[b].size) { skyByButton[b][it].tap.size * config.baseHitRadius } }, + flickObject, + DoubleArray(flicks.size) { flicks[it].ms }, + DoubleArray(flicks.size) { flicks[it].flick.x }, + DoubleArray(flicks.size) { flicks[it].flick.y }, + DoubleArray(flicks.size) { flicks[it].flick.size * config.baseHitRadius }, + DoubleArray(slides.size) { slides[it].startMs }, + DoubleArray(slides.size) { slides[it].endMs }, + IntArray(slides.size) { slides[it].slide.button.ordinal }, + DoubleArray(slides.size) { slides[it].slide.radius }, + Array(slides.size) { SlidePath(slides[it].slide.points) }, + ) + } + + /** + * How many ticks a hold or slide from [start] to [end] has: one every 1/[ticksPerBeat] beat, + * excluding both ends, or one at the end if none fit. Exact, since a tick that lands on the + * end must be left out however the fractions round. + */ + internal fun tickCount(start: Beat, end: Beat, ticksPerBeat: Int): Long { + val startDen = BigInteger.valueOf(start.den.toLong()) + val endDen = BigInteger.valueOf(end.den.toLong()) + val bothDens = startDen * endDen + val length = BigInteger.valueOf(end.whole.toLong() - start.whole.toLong()) * bothDens + + BigInteger.valueOf(end.num.toLong()) * startDen - + BigInteger.valueOf(start.num.toLong()) * endDen + val steps = length * BigInteger.valueOf(ticksPerBeat.toLong()) + val division = steps.divideAndRemainder(bothDens) + val between = if (division[1].signum() == 0) division[0] - BigInteger.ONE else division[0] + return maxOf(1L, between.toLong()) + } + + private fun tickBeat(start: Beat, end: Beat, index: Int, count: Long, ticksPerBeat: Int): Double { + if (count == 1L && start.toDouble() + 1.0 / ticksPerBeat >= end.toDouble()) return end.toDouble() + return start.toDouble() + (index + 1).toDouble() / ticksPerBeat + } + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/judge/Judgement.kt b/core/src/main/kotlin/net/trilleo/hexium/core/judge/Judgement.kt new file mode 100644 index 0000000..8c788f8 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/judge/Judgement.kt @@ -0,0 +1,5 @@ +package net.trilleo.hexium.core.judge + +enum class Judgement { JUSTICE_CRITICAL, JUSTICE, ATTACK, MISS } + +enum class ClearLamp { NONE, FULL_COMBO, ALL_JUSTICE, ALL_JUSTICE_CRITICAL } diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/judge/JudgementConfig.kt b/core/src/main/kotlin/net/trilleo/hexium/core/judge/JudgementConfig.kt new file mode 100644 index 0000000..ff4b86b --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/judge/JudgementConfig.kt @@ -0,0 +1,40 @@ +package net.trilleo.hexium.core.judge + +/** The windows, weights and sizes the judge and score use (docs/JUDGEMENT.md). Nothing else may hold these numbers. */ +data class JudgementConfig( + val justiceCriticalMs: Double = 33.33, + val justiceMs: Double = 66.67, + val attackMs: Double = 83.33, + /** The Attack window for BASIC and ADVANCED. */ + val easyAttackMs: Double = 100.0, + /** A press this early, but outside the Attack window, uses up the note as a Miss. */ + val earlyMissMs: Double = 150.0, + + val tickJusticeCriticalMs: Double = 50.0, + val tickJusticeMs: Double = 100.0, + val tickAttackMs: Double = 150.0, + val ticksPerBeat: Int = 4, + + val flickJusticeCriticalMs: Double = 83.33, + val flickJusticeMs: Double = 166.67, + /** In screen heights per second. */ + val flickMinSpeed: Double = 1.0, + + /** A note's hit radius at `size` 1, as a fraction of the screen's height. */ + val baseHitRadius: Double = 0.08, + /** The screen's width divided by its height. */ + val screenAspect: Double = 2.0, + + val perfectScoreBase: Long = 1_000_000, + val justiceCriticalWeightPercent: Int = 101, + val justiceWeightPercent: Int = 100, + val attackWeightPercent: Int = 50, + val missWeightPercent: Int = 0, +) { + companion object { + val DEFAULT = JudgementConfig() + + /** Raise this whenever a change could alter a replay's result (docs/REPLAY_FORMAT.md). */ + const val JUDGE_VERSION: Int = 2 + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/replay/PlayInput.kt b/core/src/main/kotlin/net/trilleo/hexium/core/replay/PlayInput.kt new file mode 100644 index 0000000..5dfda2d --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/replay/PlayInput.kt @@ -0,0 +1,188 @@ +package net.trilleo.hexium.core.replay + +import net.trilleo.hexium.core.chart.SkyButton + +/** + * What reaches [recorder] during a play, which is where the pause rule lives. Resuming rewinds the + * song so the player can get back in time, but judging and recording only reopen when it comes back to + * the point where they paused, and a key that changed in between is synced at that exact time. So + * a replay's times never go down, and a replay can't tell a pause happened. + * + * A key reaches the game after it happened, often after a later frame has already read the time. So + * aim samples, and the judge's clock with them, wait [HOLD_BACK_MS] behind the song, and a key is + * judged at once at its own time, among the samples around it. Only a key older than that gets moved + * up to the judge's time, which [lateKeyCount] counts. Sky buttons work the same way as lane keys. + * All input must come through here, so it stays in order with the samples. Doesn't allocate. + * + * Moving the mouse during a pause mustn't look like a fast swipe once judging reopens. So pausing + * records the crosshair where it last was at the pause point, and reopening records it again at that + * same point: where it was on its way from the last countdown frame to the frame that reopened, or + * where it was last seen if a key reopened. The judge doesn't test flicks on a step that takes no + * time, so this moves the aim without swiping, and the next step keeps its real speed. + */ +class PlayInput(private val recorder: ReplayRecorder, laneCount: Int) { + /** Where the keys really are. */ + private val down = BooleanArray(laneCount) + + /** Where the judge thinks they are. */ + private val judged = BooleanArray(laneCount) + + private val buttonDown = BooleanArray(BUTTONS.size) + private val buttonJudged = BooleanArray(BUTTONS.size) + + /** The crosshair in the latest frame, whether or not it was judged. */ + private var hasAim = false + private var lastAimMs = 0.0 + private var lastAimX = 0f + private var lastAimY = 0f + + private var paused = false + + /** Samples not sent yet, oldest first, in a fixed ring. */ + private val aimTimes = DoubleArray(AIM_CAPACITY) + private val aimXs = FloatArray(AIM_CAPACITY) + private val aimYs = FloatArray(AIM_CAPACITY) + private var aimHead = 0 + private var aimCount = 0 + + /** True once input reaches the judge, which isn't while paused or during the rewind after it. */ + var isOpen = true + private set + + /** Everything up to here has been played. Before the first pause that's nothing. */ + var playedUntilMs = Double.NEGATIVE_INFINITY + private set + + /** Keys older than the judge's current time, so they count as happening at it. */ + var lateKeyCount = 0 + private set + + fun isLaneDown(lane: Int): Boolean = down[lane] + + fun isButtonDown(button: SkyButton): Boolean = buttonDown[button.ordinal] + + /** A lane key changing, wherever the play is. */ + fun lane(lane: Int, isDown: Boolean, timeMs: Double) { + if (!isOpen && !paused && timeMs >= playedUntilMs) reopen(hasAim, lastAimX, lastAimY) + down[lane] = isDown + if (!isOpen) return + sendAimUpTo(timeMs) + if (timeMs < recorder.latestMs) lateKeyCount++ + send(lane, isDown, timeMs) + } + + /** A sky button changing, wherever the play is, with the crosshair at that moment. */ + fun button(button: SkyButton, isDown: Boolean, timeMs: Double, x: Float, y: Float) { + if (!isOpen && !paused && timeMs >= playedUntilMs) reopen(hasAim, lastAimX, lastAimY) + buttonDown[button.ordinal] = isDown + if (!isOpen) return + sendAimUpTo(timeMs) + if (timeMs < recorder.latestMs) lateKeyCount++ + sendButton(button, isDown, timeMs, x, y) + } + + /** Call once per frame while the song is running, after that frame's input. */ + fun frame(timeMs: Double, aimX: Float, aimY: Float) { + if (!timeMs.isFinite()) return + val aimFinite = aimX.isFinite() && aimY.isFinite() + if (!isOpen && !paused && timeMs >= playedUntilMs) { + if (!aimFinite) { + reopen(hasAim, lastAimX, lastAimY) + } else if (!hasAim || timeMs <= lastAimMs) { + reopen(true, aimX, aimY) + } else { + val along = ((playedUntilMs - lastAimMs) / (timeMs - lastAimMs)).coerceIn(0.0, 1.0) + reopen(true, (lastAimX + (aimX - lastAimX) * along).toFloat(), (lastAimY + (aimY - lastAimY) * along).toFloat()) + } + } + if (aimFinite) { + hasAim = true + lastAimMs = timeMs + lastAimX = aimX + lastAimY = aimY + } + if (!isOpen) return + if (aimCount == AIM_CAPACITY) sendOldestAim() + val slot = (aimHead + aimCount) % AIM_CAPACITY + aimTimes[slot] = timeMs + aimXs[slot] = aimX + aimYs[slot] = aimY + aimCount++ + val judgedUntilMs = timeMs - HOLD_BACK_MS + sendAimUpTo(judgedUntilMs) + recorder.advanceTo(judgedUntilMs) + } + + /** Stops the play at [timeMs]. Pausing again during a rewind keeps the first pause point. */ + fun pause(timeMs: Double) { + if (isOpen) { + sendAimUpTo(Double.POSITIVE_INFINITY) + if (hasAim) recorder.aimSample(timeMs, lastAimX, lastAimY) + recorder.advanceTo(timeMs) + playedUntilMs = timeMs + } + isOpen = false + paused = true + } + + /** Returns the song time to go back to. */ + fun resume(): Double { + paused = false + return playedUntilMs - REWIND_MS + } + + /** + * Syncs keys and buttons at the pause point, then records the crosshair at [aimX], [aimY] there. + * Without a crosshair seen yet ([aimKnown] false) there's nowhere to press a button, so a press + * waits for the next pause point. + */ + private fun reopen(aimKnown: Boolean, aimX: Float, aimY: Float) { + for (lane in down.indices) { + if (down[lane] != judged[lane]) send(lane, down[lane], playedUntilMs) + } + for (i in BUTTONS.indices) { + if (buttonDown[i] != buttonJudged[i] && (aimKnown || !buttonDown[i])) sendButton(BUTTONS[i], buttonDown[i], playedUntilMs, aimX, aimY) + } + // After the buttons, so a slide only counts as held with the button really down. + if (aimKnown) recorder.aimSample(playedUntilMs, aimX, aimY) + isOpen = true + } + + private fun sendButton(button: SkyButton, isDown: Boolean, timeMs: Double, x: Float, y: Float) { + buttonJudged[button.ordinal] = isDown + if (isDown) recorder.pressButton(button, timeMs, x, y) else recorder.releaseButton(button, timeMs) + } + + private fun send(lane: Int, isDown: Boolean, timeMs: Double) { + judged[lane] = isDown + if (isDown) recorder.pressLane(lane, timeMs) else recorder.releaseLane(lane, timeMs) + } + + /** The play is over: sends what's waiting and judges everything left. */ + fun finish() { + sendAimUpTo(Double.POSITIVE_INFINITY) + recorder.finish() + } + + private fun sendAimUpTo(timeMs: Double) { + while (aimCount > 0 && aimTimes[aimHead] <= timeMs) sendOldestAim() + } + + private fun sendOldestAim() { + recorder.aimSample(aimTimes[aimHead], aimXs[aimHead], aimYs[aimHead]) + aimHead = (aimHead + 1) % AIM_CAPACITY + aimCount-- + } + + companion object { + private val BUTTONS = SkyButton.entries.toTypedArray() + + const val REWIND_MS = 3000.0 + + /** Covers a key a whole frame old at about 30 FPS, plus its way to the game. Misses and ticks show this much later. */ + const val HOLD_BACK_MS = 50.0 + + /** Room for the hold-back at 5000 FPS. Past that the oldest sample just goes early. */ + private const val AIM_CAPACITY = 256 + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/replay/Replay.kt b/core/src/main/kotlin/net/trilleo/hexium/core/replay/Replay.kt new file mode 100644 index 0000000..e517ac4 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/replay/Replay.kt @@ -0,0 +1,40 @@ +package net.trilleo.hexium.core.replay + +import java.security.MessageDigest + +enum class ReplayEvent { AIM, LANE_DOWN, LANE_UP, BUTTON_DOWN, BUTTON_UP } + +/** Every input of one play, in order (docs/REPLAY_FORMAT.md). */ +class Replay internal constructor( + val judgeVersion: Int, + val chartHash: ByteArray, + val judgementOffsetMs: Double, + val eventCount: Int, + private val events: ByteArray, + private val indexes: ByteArray, + private val times: DoubleArray, + private val xs: FloatArray, + private val ys: FloatArray, +) { + fun event(i: Int): ReplayEvent = EVENTS[events[i].toInt()] + + /** The lane, or the [net.trilleo.hexium.core.chart.SkyButton] ordinal. */ + fun index(i: Int): Int = indexes[i].toInt() + + fun timeMs(i: Int): Double = times[i] + + /** Only for [ReplayEvent.AIM] and [ReplayEvent.BUTTON_DOWN]. */ + fun x(i: Int): Float = xs[i] + + /** Only for [ReplayEvent.AIM] and [ReplayEvent.BUTTON_DOWN]. */ + fun y(i: Int): Float = ys[i] + + companion object { + const val MAX_EVENTS: Int = 2_000_000 + + internal val EVENTS = ReplayEvent.entries.toTypedArray() + + /** The hash a replay holds for a difficulty file's bytes. */ + fun hashOf(chartFile: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(chartFile) + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayFile.kt b/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayFile.kt new file mode 100644 index 0000000..5eac25e --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayFile.kt @@ -0,0 +1,114 @@ +package net.trilleo.hexium.core.replay + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.nio.BufferUnderflowException +import java.nio.ByteBuffer +import java.util.zip.GZIPInputStream +import java.util.zip.GZIPOutputStream + +/** [replay] is null when [error] says why the file was rejected. */ +class ReplayReadResult internal constructor(val replay: Replay?, val error: String?) + +/** Reads and writes replay files (docs/REPLAY_FORMAT.md). Reading never throws. */ +object ReplayFile { + private val MAGIC = byteArrayOf('H'.code.toByte(), 'X'.code.toByte(), 'R'.code.toByte(), 'P'.code.toByte()) + private const val FORMAT_VERSION = 1 + private const val HASH_BYTES = 32 + private const val HEADER_BYTES = 4 + 4 + 4 + HASH_BYTES + 8 + 4 + private const val PLAIN_EVENT_BYTES = 1 + 8 + private const val AIM_EVENT_BYTES = PLAIN_EVENT_BYTES + 4 + 4 + private const val MAX_UNPACKED_BYTES = HEADER_BYTES + Replay.MAX_EVENTS * AIM_EVENT_BYTES + + private fun hasPosition(event: Int) = event == ReplayEvent.AIM.ordinal || event == ReplayEvent.BUTTON_DOWN.ordinal + + private fun isButton(event: Int) = event == ReplayEvent.BUTTON_DOWN.ordinal || event == ReplayEvent.BUTTON_UP.ordinal + + fun write(replay: Replay): ByteArray { + var size = HEADER_BYTES + for (i in 0 until replay.eventCount) { + size += if (hasPosition(replay.event(i).ordinal)) AIM_EVENT_BYTES else PLAIN_EVENT_BYTES + } + val buffer = ByteBuffer.allocate(size) + buffer.put(MAGIC) + buffer.putInt(FORMAT_VERSION) + buffer.putInt(replay.judgeVersion) + buffer.put(replay.chartHash) + buffer.putDouble(replay.judgementOffsetMs) + buffer.putInt(replay.eventCount) + for (i in 0 until replay.eventCount) { + val event = replay.event(i).ordinal + buffer.put(((event shl 4) or replay.index(i)).toByte()) + buffer.putDouble(replay.timeMs(i)) + if (hasPosition(event)) { + buffer.putFloat(replay.x(i)) + buffer.putFloat(replay.y(i)) + } + } + val out = ByteArrayOutputStream() + GZIPOutputStream(out).use { it.write(buffer.array()) } + return out.toByteArray() + } + + fun read(file: ByteArray): ReplayReadResult { + val bytes = try { + GZIPInputStream(ByteArrayInputStream(file)).use { it.readNBytes(MAX_UNPACKED_BYTES + 1) } + } catch (e: IOException) { + return rejected("is not a compressed replay file: ${e.message}") + } + if (bytes.size > MAX_UNPACKED_BYTES) return rejected("is too large: it unpacks past $MAX_UNPACKED_BYTES bytes") + return try { + parse(ByteBuffer.wrap(bytes)) + } catch (e: BufferUnderflowException) { + rejected("is cut short") + } + } + + private fun parse(buffer: ByteBuffer): ReplayReadResult { + val magic = ByteArray(MAGIC.size) + buffer.get(magic) + if (!magic.contentEquals(MAGIC)) return rejected("is not a Hexium replay") + val formatVersion = buffer.getInt() + if (formatVersion != FORMAT_VERSION) return rejected("uses format version $formatVersion, this Hexium reads $FORMAT_VERSION") + val judgeVersion = buffer.getInt() + val hash = ByteArray(HASH_BYTES) + buffer.get(hash) + val offsetMs = buffer.getDouble() + if (!offsetMs.isFinite()) return rejected("has a judgement offset that isn't finite") + val count = buffer.getInt() + if (count < 0 || count > Replay.MAX_EVENTS) return rejected("claims $count events, the limit is ${Replay.MAX_EVENTS}") + if (count.toLong() * PLAIN_EVENT_BYTES > buffer.remaining()) return rejected("is cut short") + + val events = ByteArray(count) + val indexes = ByteArray(count) + val times = DoubleArray(count) + val xs = FloatArray(count) + val ys = FloatArray(count) + var previous = Double.NEGATIVE_INFINITY + for (i in 0 until count) { + val head = buffer.get().toInt() and 0xFF + val event = head ushr 4 + val index = head and 0x0F + if (event >= Replay.EVENTS.size) return rejected("event $i has unknown kind $event") + if (isButton(event) && index > 1) return rejected("event $i has unknown button $index") + if (event == ReplayEvent.AIM.ordinal && index != 0) return rejected("event $i is an aim sample with index $index") + val time = buffer.getDouble() + if (!time.isFinite()) return rejected("event $i has a time that isn't finite") + if (time < previous) return rejected("event $i goes back in time") + previous = time + events[i] = event.toByte() + indexes[i] = index.toByte() + times[i] = time + if (hasPosition(event)) { + xs[i] = buffer.getFloat() + ys[i] = buffer.getFloat() + if (!xs[i].isFinite() || !ys[i].isFinite()) return rejected("event $i has a position that isn't finite") + } + } + if (buffer.hasRemaining()) return rejected("has ${buffer.remaining()} bytes after the last event") + return ReplayReadResult(Replay(judgeVersion, hash, offsetMs, count, events, indexes, times, xs, ys), null) + } + + private fun rejected(why: String) = ReplayReadResult(null, "This replay $why") +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayJudge.kt b/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayJudge.kt new file mode 100644 index 0000000..1cfe13d --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayJudge.kt @@ -0,0 +1,48 @@ +package net.trilleo.hexium.core.replay + +import net.trilleo.hexium.core.chart.ChartParser +import net.trilleo.hexium.core.chart.ChartValidator +import net.trilleo.hexium.core.chart.Severity +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.judge.Judge +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.JudgementConfig + +/** [judge] holds the finished play, and is null when [error] says why it couldn't be re-judged. */ +class RejudgeResult internal constructor(val judge: Judge?, val error: String?) + +/** Runs a replay through the same judge as live play. */ +object ReplayJudge { + private val BUTTONS = SkyButton.entries.toTypedArray() + + fun play(chart: JudgeChart, replay: Replay): Judge { + val judge = Judge(chart, replay.judgementOffsetMs) + for (i in 0 until replay.eventCount) { + val time = replay.timeMs(i) + when (replay.event(i)) { + ReplayEvent.AIM -> judge.aimSample(time, replay.x(i), replay.y(i)) + ReplayEvent.LANE_DOWN -> judge.pressLane(replay.index(i), time) + ReplayEvent.LANE_UP -> judge.releaseLane(replay.index(i), time) + ReplayEvent.BUTTON_DOWN -> judge.pressButton(BUTTONS[replay.index(i)], time, replay.x(i), replay.y(i)) + ReplayEvent.BUTTON_UP -> judge.releaseButton(BUTTONS[replay.index(i)], time) + } + } + judge.finish() + return judge + } + + /** Re-judges from the difficulty file's bytes, checking the replay belongs to it. Never throws on bad input. */ + fun rejudge(chartFile: ByteArray, replay: Replay): RejudgeResult { + if (!Replay.hashOf(chartFile).contentEquals(replay.chartHash)) return failed("This replay is of a different chart") + if (replay.judgeVersion != JudgementConfig.JUDGE_VERSION) { + return failed("This replay was played under judge version ${replay.judgeVersion}, this is ${JudgementConfig.JUDGE_VERSION}") + } + val parsed = ChartParser.parseDifficulty(String(chartFile, Charsets.UTF_8)) + val chart = parsed.value ?: return failed("The chart can't be read: ${parsed.issues.first { it.severity == Severity.ERROR }}") + val problem = ChartValidator.validateChart(chart).firstOrNull { it.severity == Severity.ERROR } + if (problem != null) return failed("The chart isn't valid: $problem") + return RejudgeResult(play(JudgeChart.compile(chart), replay), null) + } + + private fun failed(why: String) = RejudgeResult(null, why) +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayRecorder.kt b/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayRecorder.kt new file mode 100644 index 0000000..b96c082 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/replay/ReplayRecorder.kt @@ -0,0 +1,129 @@ +package net.trilleo.hexium.core.replay + +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.judge.Judge +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.JudgementConfig + +/** + * Sends input to the judge and records it, so a replay holds exactly what the judge saw. An + * event older than the current time is recorded as happening now, which is how the judge + * treats it. Events with times or positions that aren't finite are dropped. + * + * Doesn't allocate until it passes [expectedEvents], so size that for the whole song. Past + * [Replay.MAX_EVENTS] it stops recording but keeps judging: check [isFull] before submitting. + */ +class ReplayRecorder( + chart: JudgeChart, + private val chartHash: ByteArray, + private val judgementOffsetMs: Double, + expectedEvents: Int, +) { + val judge = Judge(chart, judgementOffsetMs) + + private var capacity = expectedEvents.coerceIn(1, Replay.MAX_EVENTS) + private var events = ByteArray(capacity) + private var indexes = ByteArray(capacity) + private var times = DoubleArray(capacity) + private var xs = FloatArray(capacity) + private var ys = FloatArray(capacity) + private var count = 0 + + /** The time everything now counts from: an event older than this is recorded as happening at it. */ + var latestMs = Double.NEGATIVE_INFINITY + private set + + /** True if events have been lost to the limit. */ + var isFull = false + private set + + fun pressLane(lane: Int, timeMs: Double) { + if (!timeMs.isFinite() || lane !in 0..MAX_INDEX) return + val time = latest(timeMs) + record(ReplayEvent.LANE_DOWN, lane, time, 0f, 0f) + judge.pressLane(lane, time) + } + + fun releaseLane(lane: Int, timeMs: Double) { + if (!timeMs.isFinite() || lane !in 0..MAX_INDEX) return + val time = latest(timeMs) + record(ReplayEvent.LANE_UP, lane, time, 0f, 0f) + judge.releaseLane(lane, time) + } + + fun pressButton(button: SkyButton, timeMs: Double, x: Float, y: Float) { + if (!timeMs.isFinite() || !x.isFinite() || !y.isFinite()) return + val time = latest(timeMs) + record(ReplayEvent.BUTTON_DOWN, button.ordinal, time, x, y) + judge.pressButton(button, time, x, y) + } + + fun releaseButton(button: SkyButton, timeMs: Double) { + if (!timeMs.isFinite()) return + val time = latest(timeMs) + record(ReplayEvent.BUTTON_UP, button.ordinal, time, 0f, 0f) + judge.releaseButton(button, time) + } + + fun aimSample(timeMs: Double, x: Float, y: Float) { + if (!timeMs.isFinite() || !x.isFinite() || !y.isFinite()) return + val time = latest(timeMs) + record(ReplayEvent.AIM, 0, time, x, y) + judge.aimSample(time, x, y) + } + + fun advanceTo(timeMs: Double) { + if (!timeMs.isFinite()) return + judge.advanceTo(latest(timeMs)) + } + + fun finish() { + judge.finish() + } + + fun toReplay(): Replay = Replay( + JudgementConfig.JUDGE_VERSION, + chartHash, + judgementOffsetMs, + count, + events.copyOf(count), + indexes.copyOf(count), + times.copyOf(count), + xs.copyOf(count), + ys.copyOf(count), + ) + + private fun latest(timeMs: Double): Double { + if (timeMs > latestMs) latestMs = timeMs + return latestMs + } + + private fun record(event: ReplayEvent, index: Int, timeMs: Double, x: Float, y: Float) { + if (count == capacity && !grow()) { + isFull = true + return + } + events[count] = event.ordinal.toByte() + indexes[count] = index.toByte() + times[count] = timeMs + xs[count] = x + ys[count] = y + count++ + } + + private fun grow(): Boolean { + if (capacity >= Replay.MAX_EVENTS) return false + capacity = minOf(capacity.toLong() * 2, Replay.MAX_EVENTS.toLong()).toInt() + events = events.copyOf(capacity) + indexes = indexes.copyOf(capacity) + times = times.copyOf(capacity) + xs = xs.copyOf(capacity) + ys = ys.copyOf(capacity) + return true + } + + private companion object { + /** An event's index has 4 bits in the file. */ + const val MAX_INDEX = 15 + } +} diff --git a/core/src/main/kotlin/net/trilleo/hexium/core/settings/PlayerSettings.kt b/core/src/main/kotlin/net/trilleo/hexium/core/settings/PlayerSettings.kt new file mode 100644 index 0000000..e66a8d7 --- /dev/null +++ b/core/src/main/kotlin/net/trilleo/hexium/core/settings/PlayerSettings.kt @@ -0,0 +1,100 @@ +package net.trilleo.hexium.core.settings + +import kotlin.math.roundToLong +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.doubleOrNull +import kotlinx.serialization.json.put + +/** + * What a player has set, as stored in `settings.json`. Note speed is in blocks per second. The offsets + * are A and B in docs/JUDGEMENT.md. The comfort settings only change how the camera feels during play, + * never judging: mouse sensitivity is a percentage on top of vanilla's, play FOV is the field of view on + * the stage in degrees, and view assist is how strongly the camera eases back to the rest view when no + * sky notes are near, 0 for off. Reading never fails: a player must always be able to start the game. + * A later format version must still read these fields the same way, since nothing here checks the version. + */ +data class PlayerSettings( + val noteSpeed: Int = DEFAULT_NOTE_SPEED, + val visualOffsetMs: Int = 0, + val judgementOffsetMs: Int = 0, + val mouseSensitivity: Int = DEFAULT_MOUSE_SENSITIVITY, + val playFov: Int = DEFAULT_PLAY_FOV, + val viewAssist: Int = 0, +) { + fun inRange() = PlayerSettings( + noteSpeed.coerceIn(MIN_NOTE_SPEED, MAX_NOTE_SPEED), + visualOffsetMs.coerceIn(-MAX_OFFSET_MS, MAX_OFFSET_MS), + judgementOffsetMs.coerceIn(-MAX_OFFSET_MS, MAX_OFFSET_MS), + mouseSensitivity.coerceIn(MIN_MOUSE_SENSITIVITY, MAX_MOUSE_SENSITIVITY), + playFov.coerceIn(MIN_PLAY_FOV, MAX_PLAY_FOV), + viewAssist.coerceIn(0, MAX_VIEW_ASSIST), + ) + + companion object { + const val DEFAULT_NOTE_SPEED = 25 + const val MIN_NOTE_SPEED = 10 + const val MAX_NOTE_SPEED = 120 + const val MAX_OFFSET_MS = 500 + + /** Percent of vanilla's mouse sensitivity. */ + const val DEFAULT_MOUSE_SENSITIVITY = 100 + const val MIN_MOUSE_SENSITIVITY = 10 + const val MAX_MOUSE_SENSITIVITY = 300 + + /** Degrees, vanilla's own range and default. The sky screen is 90 degrees wide, so a low FOV or a narrow window cuts its sides. */ + const val DEFAULT_PLAY_FOV = 70 + const val MIN_PLAY_FOV = 30 + const val MAX_PLAY_FOV = 110 + + const val MAX_VIEW_ASSIST = 5 + + private const val FORMAT_VERSION = 1 + private val JSON = Json { prettyPrint = true } + + /** Broken text gives the defaults. A broken field gives its own default. Everything comes back in range. */ + fun parse(text: String): PlayerSettings { + val root = try { + Json.parseToJsonElement(text) as? JsonObject + } catch (_: SerializationException) { + null + } catch (_: IllegalArgumentException) { + null + } catch (_: StackOverflowError) { + null + } ?: return PlayerSettings() + return PlayerSettings( + number(root, "noteSpeed", DEFAULT_NOTE_SPEED), + number(root, "visualOffsetMs", 0), + number(root, "judgementOffsetMs", 0), + number(root, "mouseSensitivity", DEFAULT_MOUSE_SENSITIVITY), + number(root, "playFov", DEFAULT_PLAY_FOV), + number(root, "viewAssist", 0), + ).inRange() + } + + fun write(settings: PlayerSettings): String = JSON.encodeToString( + JsonObject.serializer(), + buildJsonObject { + put("formatVersion", FORMAT_VERSION) + put("noteSpeed", settings.noteSpeed) + put("visualOffsetMs", settings.visualOffsetMs) + put("judgementOffsetMs", settings.judgementOffsetMs) + put("mouseSensitivity", settings.mouseSensitivity) + put("playFov", settings.playFov) + put("viewAssist", settings.viewAssist) + }, + ) + + private fun number(root: JsonObject, name: String, default: Int): Int { + val primitive = root[name] as? JsonPrimitive ?: return default + if (primitive.isString) return default + val value = primitive.doubleOrNull ?: return default + if (!value.isFinite()) return default + return value.roundToLong().coerceIn(Int.MIN_VALUE.toLong(), Int.MAX_VALUE.toLong()).toInt() + } + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/aim/ScreenPlaneTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/aim/ScreenPlaneTest.kt new file mode 100644 index 0000000..98dd4e2 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/aim/ScreenPlaneTest.kt @@ -0,0 +1,184 @@ +package net.trilleo.hexium.core.aim + +import java.lang.management.ManagementFactory +import kotlin.math.atan +import kotlin.math.sqrt +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ScreenPlaneTest { + private val tolerance = 1e-9 + + /** A 12 by 6 screen standing on y 0, 6 blocks down +Z from the eye at (0, 3, 0). Its left edge is on +X. */ + private val plane = ScreenPlane(leftX = 6.0, rightX = -6.0, bottomY = 0.0, topY = 6.0, planeZ = 6.0) + + private fun degrees(radians: Double) = Math.toDegrees(radians) + + @Test + fun lookingStraightAheadHitsTheMiddle() { + assertTrue(plane.aim(0.0, 3.0, 0.0, 0.0, 0.0)) + assertEquals(0.5, plane.x, tolerance) + assertEquals(0.5, plane.y, tolerance) + } + + /** Minecraft's yaw turns toward -X as it grows, and the screen's right edge is on -X. */ + @Test + fun turningRightMovesTheAimRight() { + assertTrue(plane.aim(0.0, 3.0, 0.0, 45.0, 0.0)) + assertEquals(1.0, plane.x, tolerance) + assertEquals(0.5, plane.y, tolerance) + plane.aim(0.0, 3.0, 0.0, -45.0, 0.0) + assertEquals(0.0, plane.x, tolerance) + } + + /** Minecraft's pitch looks down as it grows. */ + @Test + fun lookingDownMovesTheAimDown() { + plane.aim(0.0, 3.0, 0.0, 0.0, degrees(atan(0.5))) + assertEquals(0.0, plane.y, tolerance) + plane.aim(0.0, 3.0, 0.0, 0.0, -degrees(atan(0.5))) + assertEquals(1.0, plane.y, tolerance) + } + + @Test + fun theEyesOwnPlaceCounts() { + plane.aim(3.0, 6.0, 3.0, 0.0, 0.0) + assertEquals(0.25, plane.x, tolerance) + assertEquals(1.0, plane.y, tolerance) + } + + @Test + fun anAimOffTheScreenStillGivesItsPlace() { + plane.aim(0.0, 3.0, 0.0, 60.0, 0.0) + assertTrue(plane.x > 1.0) + } + + @Test + fun lookingAwayFromTheScreenHitsNothing() { + assertFalse(plane.aim(0.0, 3.0, 0.0, 180.0, 0.0)) + assertTrue(plane.x.isNaN() && plane.y.isNaN()) + assertFalse(plane.aim(0.0, 3.0, 0.0, 0.0, 90.0)) + assertFalse(plane.aim(0.0, 3.0, 0.0, 90.0, 0.0)) + } + + @Test + fun aWholeTurnMakesNoDifference() { + plane.aim(0.0, 3.0, 0.0, 20.0 + 720.0, 10.0) + val x = plane.x + val y = plane.y + plane.aim(0.0, 3.0, 0.0, 20.0, 10.0) + assertEquals(x, plane.x, 1e-9) + assertEquals(y, plane.y, 1e-9) + } + + @Test + fun aLookInsideTheLimitIsLeftAlone() { + assertFalse(plane.clampLook(0.0, 3.0, 0.0, 10.0, 5.0, 0.1, 0.1)) + assertEquals(10.0, plane.yaw, tolerance) + assertEquals(5.0, plane.pitch, tolerance) + } + + @Test + fun aLookPastAnEdgeStopsAtTheEdgePlusTheMargin() { + assertTrue(plane.clampLook(0.0, 3.0, 0.0, 60.0, 0.0, 0.1, 0.2)) + plane.aim(0.0, 3.0, 0.0, plane.yaw, plane.pitch) + assertEquals(1.1, plane.x, 1e-9) + assertEquals(0.5, plane.y, 1e-9) + assertTrue(plane.clampLook(0.0, 3.0, 0.0, 0.0, -80.0, 0.1, 0.2)) + plane.aim(0.0, 3.0, 0.0, plane.yaw, plane.pitch) + assertEquals(0.5, plane.x, 1e-9) + assertEquals(1.2, plane.y, 1e-9) + } + + @Test + fun aCornerIsClampedOnBothAxes() { + assertTrue(plane.clampLook(0.0, 3.0, 0.0, -70.0, 70.0, 0.1, 0.2)) + plane.aim(0.0, 3.0, 0.0, plane.yaw, plane.pitch) + assertEquals(-0.1, plane.x, 1e-9) + assertEquals(-0.2, plane.y, 1e-9) + } + + /** The camera's yaw keeps counting past a whole turn, so a clamp mustn't make it jump back by 360. */ + @Test + fun aClampedYawStaysOnTheSameTurn() { + assertTrue(plane.clampLook(0.0, 3.0, 0.0, 720.0 + 60.0, 0.0, 0.1, 0.1)) + assertTrue(plane.yaw > 700.0 && plane.yaw < 780.0, "yaw ${plane.yaw}") + assertTrue(plane.clampLook(0.0, 3.0, 0.0, -720.0 - 60.0, 0.0, 0.1, 0.1)) + assertTrue(plane.yaw < -700.0 && plane.yaw > -780.0, "yaw ${plane.yaw}") + } + + /** One frame's turn can go past where the look misses the screen at all. It still stops at the edge it went past. */ + @Test + fun turningSoFarTheLookMissesStopsAtTheEdgeItWentPast() { + assertTrue(plane.clampLook(0.0, 3.0, 0.0, 120.0, 0.0, 0.1, 0.1)) + plane.aim(0.0, 3.0, 0.0, plane.yaw, plane.pitch) + assertEquals(1.1, plane.x, 1e-9) + assertEquals(0.5, plane.y, 1e-9) + assertTrue(plane.clampLook(0.0, 3.0, 0.0, -100.0, -30.0, 0.1, 0.1)) + plane.aim(0.0, 3.0, 0.0, plane.yaw, plane.pitch) + assertEquals(-0.1, plane.x, 1e-9) + assertEquals(1.1, plane.y, 1e-9) + } + + /** Straight up or straight behind has no side to go to, so it stays level with the eye on that axis. */ + @Test + fun lookingStraightAwayIsTurnedBackInLineWithTheEye() { + assertTrue(plane.clampLook(0.0, 3.0, 0.0, 180.0, 0.0, 0.1, 0.1)) + plane.aim(0.0, 3.0, 0.0, plane.yaw, plane.pitch) + assertEquals(0.5, plane.x, 1e-9) + assertEquals(0.5, plane.y, 1e-9) + assertTrue(plane.clampLook(0.0, 3.0, 0.0, 3030.0, -90.0, 0.1, 0.1)) + plane.aim(0.0, 3.0, 0.0, plane.yaw, plane.pitch) + assertEquals(0.5, plane.x, 1e-9) + assertEquals(1.1, plane.y, 1e-9) + } + + @Test + fun lookingTowardAPointHitsIt() { + val random = Random(7) + repeat(200) { + val x = random.nextDouble(-0.2, 1.2) + val y = random.nextDouble(-0.2, 1.2) + plane.lookToward(1.0, 4.0, -1.0, x, y) + assertTrue(plane.aim(1.0, 4.0, -1.0, plane.yaw, plane.pitch)) + assertEquals(x, plane.x, 1e-9) + assertEquals(y, plane.y, 1e-9) + } + } + + /** The bottom right corner is 6 blocks right, 3 down and 6 ahead: half right and a little down, in Minecraft's angles. */ + @Test + fun lookingTowardAPointGivesMinecraftsAngles() { + plane.lookToward(0.0, 3.0, 0.0, 1.0, 0.0) + assertEquals(45.0, plane.yaw, 1e-9) + assertEquals(degrees(atan(3.0 / sqrt(72.0))), plane.pitch, 1e-9) + // Minecraft's own view vector for those angles points at the corner. + val yaw = Math.toRadians(plane.yaw) + val pitch = Math.toRadians(plane.pitch) + val length = sqrt(81.0) + assertEquals(-6.0 / length, -Math.sin(yaw) * Math.cos(pitch), 1e-9) + assertEquals(-3.0 / length, -Math.sin(pitch), 1e-9) + assertEquals(6.0 / length, Math.cos(yaw) * Math.cos(pitch), 1e-9) + } + + @Test + fun aimingAndClampingDoNotAllocate() { + val threads = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + val thread = Thread.currentThread().threadId() + var sum = 0.0 + val before = threads.getThreadAllocatedBytes(thread) + for (i in 0 until 100_000) { + val yaw = (i % 200) - 100.0 + val pitch = (i % 120) - 60.0 + if (plane.aim(0.0, 3.0, 0.0, yaw, pitch)) sum += plane.x + plane.y + plane.clampLook(0.0, 3.0, 0.0, yaw, pitch, 0.1, 0.1) + sum += plane.yaw + plane.pitch + } + val allocated = threads.getThreadAllocatedBytes(thread) - before + assertTrue(sum.isFinite()) + assertTrue(allocated < 16 * 1024, "allocated $allocated bytes") + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/calibration/CalibrationTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/calibration/CalibrationTest.kt new file mode 100644 index 0000000..25fefdd --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/calibration/CalibrationTest.kt @@ -0,0 +1,137 @@ +package net.trilleo.hexium.core.calibration + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.Beat +import net.trilleo.hexium.core.chart.BpmChange +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.GroundTrack +import net.trilleo.hexium.core.chart.MeterChange +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.judge.Judge +import net.trilleo.hexium.core.judge.JudgeChart + +class CalibrationTest { + private val beatMs = 500.0 + private val tolerance = 1e-6 + + /** One tap on each beat from beat 4, off by each of [errors] in turn. */ + private fun taps(vararg errors: Double) = DoubleArray(errors.size) { (it + 4) * beatMs + errors[it] } + + private fun estimate(vararg errors: Double): TapEstimate { + val taps = taps(*errors) + return assertNotNull(Calibration.estimate(taps, taps.size, beatMs)) + } + + @Test + fun tapsOnTheBeatHaveNoError() { + assertEquals(0.0, estimate(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0).errorMs, tolerance) + } + + @Test + fun lateTapsArePositiveAndEarlyTapsNegative() { + assertEquals(40.0, estimate(40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0).errorMs, tolerance) + assertEquals(-40.0, estimate(-40.0, -40.0, -40.0, -40.0, -40.0, -40.0, -40.0, -40.0).errorMs, tolerance) + } + + @Test + fun theMiddleTapCountsSoOneWildTapChangesNothing() { + val result = estimate(20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 200.0) + assertEquals(27.0, result.errorMs, tolerance) + assertEquals(8, result.tapsUsed) + assertTrue(result.isSteady) + } + + @Test + fun tapsEitherSideOfTheHalfBeatStayTogether() { + val result = estimate(245.0, 255.0, 245.0, 255.0, 245.0, 255.0, 245.0, 255.0) + assertEquals(250.0, Math.abs(result.errorMs), 5.0 + tolerance) + assertTrue(result.spreadMs <= 5.0 + tolerance) + } + + @Test + fun tapsDuringALeadInCountToo() { + val taps = DoubleArray(8) { -2000.0 + it * beatMs + 30.0 } + assertEquals(30.0, assertNotNull(Calibration.estimate(taps, taps.size, beatMs)).errorMs, tolerance) + } + + @Test + fun onlyTheGivenCountIsRead() { + val taps = DoubleArray(20) + assertNull(Calibration.estimate(taps, Calibration.MIN_TAPS - 1, beatMs)) + assertNotNull(Calibration.estimate(taps, Calibration.MIN_TAPS, beatMs)) + } + + @Test + fun unevenTapsAreNotSteady() { + assertFalse(estimate(-120.0, 120.0, -90.0, 90.0, -120.0, 120.0, -90.0, 90.0, 0.0).isSteady) + } + + @Test + fun theJudgementOffsetIsHowLateThePlayerTapsToSound() { + assertEquals(40, Calibration.judgementOffsetMs(estimate(40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0))) + } + + @Test + fun theVisualOffsetLinesUpWhatTheEyeSeesWithWhatTheEarHears() { + // Taps 40 ms late to sound, but only 10 ms late to notes drawn with no offset. + val visual = estimate(10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0) + assertEquals(30, Calibration.visualOffsetMs(40, visual)) + } + + @Test + fun theSuggestedOffsetsMakeATapOnTheDrawnNoteJudgeAsZero() { + val judgementOffset = 40 + val tapLateToDrawnNotes = 10.0 + val visualOffset = Calibration.visualOffsetMs(judgementOffset, estimate(10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0)) + val beat = Beat(4, 0, 1) + val chart = DifficultyChart( + 1, Difficulty.EXPERT, 1, 4, 0.0, + listOf(BpmChange(Beat(0, 0, 1), 120.0)), + listOf(MeterChange(Beat(0, 0, 1), 4, 4)), + listOf(Note.Tap(beat, 0)), + ) + val noteMs = 2000.0 + // The song time when this note reaches the line on screen, given how it's drawn. + val onTheLineMs = noteMs + visualOffset + assertEquals(noteMs, GroundTrack.drawTimeMs(onTheLineMs, visualOffset.toDouble()), tolerance) + val judge = Judge(JudgeChart.compile(chart), judgementOffset.toDouble()) + judge.pressLane(0, onTheLineMs + tapLateToDrawnNotes) + assertEquals(0.0, judge.judgedDeltaMs(0), tolerance) + } + + @Test + fun tapsMoreThanHalfABeatLateAreLateNotEarly() { + assertEquals(251.0, estimate(*DoubleArray(8) { 251.0 }).errorMs, tolerance) + assertEquals(300.0, estimate(*DoubleArray(8) { 300.0 }).errorMs, tolerance) + } + + @Test + fun tapsALittleEarlyStayEarly() { + assertEquals(-100.0, estimate(*DoubleArray(8) { -100.0 }).errorMs, tolerance) + } + + @Test + fun tooManyThrownOutTapsAreNotSteady() { + val result = estimate(*DoubleArray(10) { 0.0 }, 200.0, -200.0, 150.0, -150.0, 180.0, -180.0) + assertEquals(10, result.tapsUsed) + assertFalse(result.isSteady) + } + + @Test + fun tooFewUsableTapsGiveNothing() { + val taps = taps(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 200.0, -200.0, 150.0, -150.0) + assertNull(Calibration.estimate(taps, 11, beatMs)) + } + + @Test + fun tapsAtTheirOwnTempoSlideOffTheBeatAndAreNotSteady() { + val taps = DoubleArray(16) { 2000.0 + it * 505.0 } + assertFalse(assertNotNull(Calibration.estimate(taps, taps.size, beatMs)).isSteady) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/BeatTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/BeatTest.kt new file mode 100644 index 0000000..bef8f39 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/BeatTest.kt @@ -0,0 +1,50 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class BeatTest { + @Test + fun fractionsWithoutReducingAreTheSameTime() { + assertEquals(0, Beat(12, 2, 4).compareTo(Beat(12, 1, 2))) + } + + @Test + fun ordersByWholeThenFraction() { + assertTrue(Beat(1, 3, 4) < Beat(2, 0, 1)) + assertTrue(Beat(2, 1, 3) < Beat(2, 1, 2)) + assertTrue(Beat(2, 1, 2) > Beat(2, 1, 3)) + } + + @Test + fun comparesHugeDenominatorsWithoutOverflow() { + val max = Int.MAX_VALUE + assertTrue(Beat(0, max - 2, max - 1) < Beat(0, max - 1, max)) + assertTrue(Beat(max, 1, max) < Beat(max, 2, max)) + } + + @Test + fun convertsToDouble() { + assertEquals(12.75, Beat(12, 3, 4).toDouble()) + assertEquals(0.0, Beat(0, 0, 1).toDouble()) + } + + @Test + fun acceptsValidFractions() { + assertTrue(Beat(0, 0, 1).isValid) + assertTrue(Beat(12, 3, 4).isValid) + assertTrue(Beat(12, 2, 4).isValid) + } + + @Test + fun rejectsInvalidFractions() { + assertFalse(Beat(12, 5, 4).isValid, "numerator above denominator") + assertFalse(Beat(12, 4, 4).isValid, "numerator equal to denominator") + assertFalse(Beat(-1, 0, 1).isValid, "negative whole") + assertFalse(Beat(1, -1, 4).isValid, "negative numerator") + assertFalse(Beat(1, 0, 0).isValid, "zero denominator") + assertFalse(Beat(1, 0, -4).isValid, "negative denominator") + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartFolderTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartFolderTest.kt new file mode 100644 index 0000000..739576c --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartFolderTest.kt @@ -0,0 +1,98 @@ +package net.trilleo.hexium.core.chart + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +class ChartFolderTest { + private val meta = File("../mod/src/client/resources/hexium_packs/test-pattern/meta.json").readText() + .replace("""[ "BASIC", "ADVANCED", "EXPERT" ]""", """[ "BASIC" ]""") + private val basic = File("../docs/examples/basic.json").readText() + + private val audio = ChartFolder.AUDIO_FILE + private val metaFile = ChartFolder.META_FILE + + private fun codes(result: ChartFolder.Result) = result.issues.map { it.issue.code } + + @Test + fun aGoodFolderHasNoIssues() { + val result = ChartFolder.read( + listOf(ChartFolder.File(metaFile, meta), ChartFolder.File("basic.json", basic)), + listOf(metaFile, "basic.json", audio), + ) + assertEquals(emptyList(), result.issues) + assertNotNull(result.meta) + assertEquals(listOf(Difficulty.BASIC), result.charts.map { it.difficulty }) + } + + @Test + fun missingMetaIsReportedEvenWithABrokenChart() { + val result = ChartFolder.read(listOf(ChartFolder.File("basic.json", "{")), listOf("basic.json", audio)) + assertTrue(IssueCode.MISSING_META_FILE in codes(result)) + assertTrue(IssueCode.INVALID_JSON in codes(result)) + } + + @Test + fun brokenMetaIsNotAlsoCalledMissing() { + val result = ChartFolder.read(listOf(ChartFolder.File(metaFile, "{")), listOf(metaFile, audio)) + assertEquals(listOf(IssueCode.INVALID_JSON), codes(result)) + } + + @Test + fun missingAudioIsAnError() { + val result = ChartFolder.read( + listOf(ChartFolder.File(metaFile, meta), ChartFolder.File("basic.json", basic)), + listOf(metaFile, "basic.json"), + ) + assertEquals(listOf(IssueCode.MISSING_AUDIO_FILE), codes(result)) + } + + /** The chart that failed already has an issue. Calling it missing too would be wrong. */ + @Test + fun aChartThatCantBeReadIsNotAlsoCalledMissing() { + for (text in listOf("{", null)) { + val result = ChartFolder.read( + listOf(ChartFolder.File(metaFile, meta), ChartFolder.File("basic.json", text)), + listOf(metaFile, "basic.json", audio), + ) + assertFalse(IssueCode.MISSING_DIFFICULTY_FILE in codes(result), "text $text") + } + } + + @Test + fun aFileNamedForAnotherDifficultyIsAnError() { + val result = ChartFolder.read( + listOf(ChartFolder.File(metaFile, meta), ChartFolder.File("expert.json", basic)), + listOf(metaFile, "expert.json", audio), + ) + assertTrue(IssueCode.FILE_NAME_MISMATCH in codes(result)) + } + + @Test + fun anOversizedPackageIsAnError() { + val result = ChartFolder.read( + listOf(ChartFolder.File(metaFile, meta), ChartFolder.File("basic.json", basic)), + listOf(metaFile, "basic.json", audio), + packageSizeBytes = ChartLimits.MAX_PACKAGE_BYTES, + ) + assertEquals(listOf(IssueCode.PACKAGE_TOO_LARGE), codes(result)) + } + + @Test + fun onlyJsonFilesThatArentHiddenAreChartFiles() { + assertTrue(ChartFolder.isChartFile("basic.json")) + assertTrue(ChartFolder.isChartFile(metaFile)) + assertFalse(ChartFolder.isChartFile("._basic.json")) + assertFalse(ChartFolder.isChartFile(audio)) + } + + @Test + fun aFileIsTooLargeToReadOnlyPastTheLimitInBytes() { + val limit = ChartLimits.MAX_JSON_FILE_CHARS * 4L + assertFalse(ChartFolder.isTooLargeToRead(limit)) + assertTrue(ChartFolder.isTooLargeToRead(limit + 1)) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartPackageValidatorTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartPackageValidatorTest.kt new file mode 100644 index 0000000..9d3c5d2 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartPackageValidatorTest.kt @@ -0,0 +1,192 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class ChartPackageValidatorTest { + private val meta = ChartMeta( + formatVersion = 1, + id = "example-song-2", + title = "Example Song", + artist = "Example Artist", + charter = "Example Charter", + previewStartMs = 0, + license = License(LicenseType.ORIGINAL, null), + difficulties = listOf(Difficulty.BASIC, Difficulty.EXPERT), + ) + + private fun chart(difficulty: Difficulty, vararg notes: Note) = DifficultyChart( + formatVersion = 1, + difficulty = difficulty, + level = 1, + laneCount = 4, + offsetMs = 0.0, + bpm = listOf(BpmChange(Beat(0, 0, 1), 120.0)), + meter = listOf(MeterChange(Beat(0, 0, 1), 4, 4)), + notes = notes.toList(), + ) + + private val pkg = ChartPackage(meta, listOf(chart(Difficulty.BASIC), chart(Difficulty.EXPERT))) + + private fun assertOnlyError(issues: List, code: IssueCode, path: String) { + assertEquals(1, issues.size, issues.toString()) + assertEquals(code, issues[0].code) + assertEquals(path, issues[0].path) + assertEquals(Severity.ERROR, issues[0].severity) + assertTrue(issues[0].message.isNotBlank()) + } + + private fun assertMetaError(meta: ChartMeta, code: IssueCode, path: String) { + assertOnlyError(ChartValidator.validateMeta(meta), code, path) + } + + @Test + fun goodMetaPasses() = assertEquals(emptyList(), ChartValidator.validateMeta(meta)) + + @Test + fun goodPackagePasses() = assertEquals(emptyList(), ChartValidator.validatePackage(pkg)) + + @Test + fun unknownFormatVersionFails() = + assertMetaError(meta.copy(formatVersion = 2), IssueCode.UNKNOWN_FORMAT_VERSION, "formatVersion") + + @Test + fun idLimitsPass() { + assertEquals(emptyList(), ChartValidator.validateMeta(meta.copy(id = "a"))) + assertEquals(emptyList(), ChartValidator.validateMeta(meta.copy(id = "a".repeat(64)))) + assertEquals(emptyList(), ChartValidator.validateMeta(meta.copy(id = "0-9-a-z"))) + } + + @Test + fun badIdsFail() { + for (id in listOf("", "a".repeat(65), "Upper", "under_score", "with space", "sláinte", "../evil")) { + assertMetaError(meta.copy(id = id), IssueCode.BAD_ID, "id") + } + } + + @Test + fun longBadIdsAreShortenedInTheMessage() { + val issue = ChartValidator.validateMeta(meta.copy(id = "X".repeat(10_000))).single() + assertTrue(issue.message.length < ChartLimits.MAX_ISSUE_TEXT_CHARS * 2, issue.message.length.toString()) + } + + @Test + fun fileNamedAfterItsDifficultyPasses() { + assertEquals(emptyList(), ChartValidator.validateFileName(chart(Difficulty.BASIC), "basic.json")) + assertEquals("master.json", ChartValidator.fileName(Difficulty.MASTER)) + } + + @Test + fun fileNamedForAnotherDifficultyFails() { + assertOnlyError( + ChartValidator.validateFileName(chart(Difficulty.BASIC), "expert.json"), + IssueCode.FILE_NAME_MISMATCH, + "$", + ) + } + + @Test + fun blankTextFails() { + assertMetaError(meta.copy(title = ""), IssueCode.BLANK_TEXT, "title") + assertMetaError(meta.copy(artist = " "), IssueCode.BLANK_TEXT, "artist") + assertMetaError(meta.copy(charter = "\t"), IssueCode.BLANK_TEXT, "charter") + } + + @Test + fun previewAtZeroOrLaterPasses() { + assertEquals(emptyList(), ChartValidator.validateMeta(meta.copy(previewStartMs = 90000))) + } + + @Test + fun negativePreviewFails() = + assertMetaError(meta.copy(previewStartMs = -1), IssueCode.NEGATIVE_PREVIEW, "previewStartMs") + + @Test + fun noDifficultiesFails() = assertMetaError(meta.copy(difficulties = emptyList()), IssueCode.NO_DIFFICULTIES, "difficulties") + + @Test + fun repeatedDifficultyFails() { + assertMetaError( + meta.copy(difficulties = listOf(Difficulty.BASIC, Difficulty.BASIC)), + IssueCode.REPEATED_DIFFICULTY, + "difficulties[1]", + ) + } + + @Test + fun metaIssuesInAPackageNameTheFile() { + assertOnlyError( + ChartValidator.validatePackage(pkg.copy(meta = meta.copy(title = ""))), + IssueCode.BLANK_TEXT, + "meta.json:title", + ) + } + + @Test + fun listedDifficultyWithoutAFileFails() { + assertOnlyError( + ChartValidator.validatePackage(pkg.copy(charts = listOf(chart(Difficulty.BASIC)))), + IssueCode.MISSING_DIFFICULTY_FILE, + "meta.json:difficulties[1]", + ) + } + + @Test + fun fileNotListedFails() { + assertOnlyError( + ChartValidator.validatePackage(pkg.copy(charts = pkg.charts + chart(Difficulty.MASTER))), + IssueCode.UNLISTED_DIFFICULTY_FILE, + "master.json", + ) + } + + @Test + fun twoFilesForOneDifficultyFail() { + assertOnlyError( + ChartValidator.validatePackage(pkg.copy(charts = pkg.charts + chart(Difficulty.BASIC))), + IssueCode.DUPLICATE_DIFFICULTY_FILE, + "basic.json", + ) + } + + @Test + fun chartIssuesInAPackageNameTheFile() { + val bad = chart(Difficulty.EXPERT, Note.Tap(Beat(1, 0, 1), 9)) + assertOnlyError( + ChartValidator.validatePackage(pkg.copy(charts = listOf(chart(Difficulty.BASIC), bad))), + IssueCode.LANE_OUT_OF_RANGE, + "expert.json:notes[0].lane", + ) + } + + @Test + fun audioLengthReachesEveryChart() { + val late = chart(Difficulty.EXPERT, Note.Tap(Beat(4, 0, 1), 0)) + val withLate = pkg.copy(charts = listOf(chart(Difficulty.BASIC), late)) + assertEquals(emptyList(), ChartValidator.validatePackage(withLate, audioDurationMs = 2000.5)) + assertOnlyError( + ChartValidator.validatePackage(withLate, audioDurationMs = 2000.0), + IssueCode.NOTE_AFTER_AUDIO, + "expert.json:notes[0]", + ) + } + + @Test + fun packageUnderTheLimitPasses() { + assertEquals(emptyList(), ChartValidator.validatePackage(pkg, packageSizeBytes = ChartLimits.MAX_PACKAGE_BYTES - 1)) + } + + @Test + fun packageSizeIsSkippedWhenNotGiven() { + assertEquals(emptyList(), ChartValidator.validatePackage(pkg, packageSizeBytes = null)) + } + + @Test + fun packageAtOrOverTheLimitFails() { + assertEquals(30L * 1024 * 1024, ChartLimits.MAX_PACKAGE_BYTES) + for (size in listOf(ChartLimits.MAX_PACKAGE_BYTES, ChartLimits.MAX_PACKAGE_BYTES + 1)) { + assertOnlyError(ChartValidator.validatePackage(pkg, packageSizeBytes = size), IssueCode.PACKAGE_TOO_LARGE, "$") + } + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartParserTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartParserTest.kt new file mode 100644 index 0000000..878e549 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartParserTest.kt @@ -0,0 +1,537 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class ChartParserTest { + /** The example from docs/CHART_FORMAT.md. */ + private val specExample = """ + { + "formatVersion": 1, + "difficulty": "EXPERT", + "level": 11, + "laneCount": 4, + "offsetMs": 120, + "bpm": [ { "t": [0,0,1], "bpm": 174 }, { "t": [64,0,1], "bpm": 87 } ], + "meter": [ { "t": [0,0,1], "num": 4, "den": 4 } ], + "notes": [ + { "type": "tap", "t": [4,0,1], "lane": 0 }, + { "type": "hold", "t": [4,1,2], "end": [6,0,1], "lane": 2 }, + { "type": "skyTap", "t": [5,0,1], "x": 0.25, "y": 0.60, "button": "L", "size": 1.0 }, + { "type": "slide", "button": "L", "radius": 0.06, "points": [ + { "t": [6,0,1], "x": 0.20, "y": 0.50, "ease": "linear" }, + { "t": [7,0,1], "x": 0.70, "y": 0.80, "ease": "inOut" } ] }, + { "type": "flick", "t": [8,0,1], "x": 0.50, "y": 0.40, "size": 1.0 } + ] + } + """.trimIndent() + + private val metaExample = """ + { + "formatVersion": 1, + "id": "example-song", + "title": "Example Song", + "artist": "Example Artist", + "charter": "Example Charter", + "previewStartMs": 30000, + "license": { "type": "permitted", "source": "https://example.com/license" }, + "difficulties": [ "BASIC", "EXPERT" ] + } + """.trimIndent() + + /** A chart around one note, for testing note fields. */ + private fun chartWithNote(note: String) = """ + { "formatVersion": 1, "difficulty": "BASIC", "level": 1, "laneCount": 4, "offsetMs": 0, + "bpm": [], "meter": [], "notes": [ $note ] } + """.trimIndent() + + private fun assertSingleError(result: ParseResult<*>, code: IssueCode, path: String) { + assertNull(result.value) + assertEquals(1, result.issues.size, result.issues.toString()) + val issue = result.issues[0] + assertEquals(Severity.ERROR, issue.severity) + assertEquals(code, issue.code) + assertEquals(path, issue.path) + assertTrue(issue.message.isNotBlank()) + } + + @Test + fun readsTheSpecExample() { + val result = ChartParser.parseDifficulty(specExample) + assertEquals(emptyList(), result.issues) + assertEquals( + DifficultyChart( + formatVersion = 1, + difficulty = Difficulty.EXPERT, + level = 11, + laneCount = 4, + offsetMs = 120.0, + bpm = listOf(BpmChange(Beat(0, 0, 1), 174.0), BpmChange(Beat(64, 0, 1), 87.0)), + meter = listOf(MeterChange(Beat(0, 0, 1), 4, 4)), + notes = listOf( + Note.Tap(Beat(4, 0, 1), 0), + Note.Hold(Beat(4, 1, 2), Beat(6, 0, 1), 2), + Note.SkyTap(Beat(5, 0, 1), 0.25, 0.60, SkyButton.L, 1.0), + Note.Slide( + SkyButton.L, + 0.06, + listOf( + SlidePoint(Beat(6, 0, 1), 0.20, 0.50, Ease.LINEAR), + SlidePoint(Beat(7, 0, 1), 0.70, 0.80, Ease.IN_OUT), + ), + ), + Note.Flick(Beat(8, 0, 1), 0.50, 0.40, 1.0), + ), + ), + result.value, + ) + } + + @Test + fun readsTheMetaExample() { + val result = ChartParser.parseMeta(metaExample) + assertEquals(emptyList(), result.issues) + assertEquals( + ChartMeta( + formatVersion = 1, + id = "example-song", + title = "Example Song", + artist = "Example Artist", + charter = "Example Charter", + previewStartMs = 30000, + license = License(LicenseType.PERMITTED, "https://example.com/license"), + difficulties = listOf(Difficulty.BASIC, Difficulty.EXPERT), + ), + result.value, + ) + } + + @Test + fun licenseSourceCanBeLeftOut() { + val meta = ChartParser.parseMeta(metaExample.replace(""", "source": "https://example.com/license"""", "")) + assertEquals(License(LicenseType.PERMITTED, null), meta.value?.license) + } + + @Test + fun everyEaseAndButtonIsRead() { + val slide = """{ "type": "slide", "button": "R", "radius": 0.1, "points": [ + { "t": [0,0,1], "x": 0, "y": 0, "ease": "linear" }, + { "t": [1,0,1], "x": 0, "y": 0, "ease": "in" }, + { "t": [2,0,1], "x": 0, "y": 0, "ease": "out" }, + { "t": [3,0,1], "x": 0, "y": 0, "ease": "inOut" } ] }""" + val note = ChartParser.parseDifficulty(chartWithNote(slide)).value?.notes?.single() as Note.Slide + assertEquals(SkyButton.R, note.button) + assertEquals(listOf(Ease.LINEAR, Ease.IN, Ease.OUT, Ease.IN_OUT), note.points.map { it.ease }) + } + + @Test + fun valuesTheFormatForbidsAreLeftForTheValidator() { + val result = ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,5,0], "lane": 99 }""")) + assertEquals(emptyList(), result.issues) + assertEquals(Note.Tap(Beat(1, 5, 0), 99), result.value?.notes?.single()) + } + + @Test + fun brokenJsonIsReportedNotThrown() { + assertSingleError(ChartParser.parseDifficulty("{ not json"), IssueCode.INVALID_JSON, "$") + assertSingleError(ChartParser.parseDifficulty(""), IssueCode.INVALID_JSON, "$") + assertSingleError(ChartParser.parseDifficulty("{} trailing"), IssueCode.INVALID_JSON, "$") + assertSingleError(ChartParser.parseMeta("{ not json"), IssueCode.INVALID_JSON, "$") + } + + @Test + fun veryDeepNestingIsNotACrash() { + val result = ChartParser.parseDifficulty("[".repeat(100_000)) + assertNull(result.value) + assertEquals(IssueCode.INVALID_JSON, result.issues.single().code) + } + + @Test + fun nestingLimitIgnoresBracketsInsideText() { + val brackets = "[".repeat(100) + val result = ChartParser.parseMeta(metaExample.replace("Example Song", brackets)) + assertEquals(emptyList(), result.issues) + assertEquals(brackets, result.value?.title) + + val escapedQuote = """\\\"""" + brackets + val escaped = ChartParser.parseMeta(metaExample.replace("Example Song", escapedQuote)) + assertEquals(emptyList(), escaped.issues) + } + + @Test + fun nestingStopsAtTheLimit() { + fun nested(levels: Int) = "[".repeat(levels) + "]".repeat(levels) + assertSingleError(ChartParser.parseDifficulty(nested(32)), IssueCode.WRONG_TYPE, "$") + assertSingleError(ChartParser.parseDifficulty(nested(33)), IssueCode.INVALID_JSON, "$") + } + + @Test + fun closingBracketsFirstDoNotHideDeepNesting() { + val text = "]".repeat(100) + "[".repeat(100) + assertSingleError(ChartParser.parseDifficulty(text), IssueCode.INVALID_JSON, "$") + } + + @Test + fun aLeadingByteOrderMarkIsIgnored() { + val result = ChartParser.parseDifficulty("\uFEFF" + specExample) + assertEquals(emptyList(), result.issues) + assertNotNull(result.value) + } + + @Test + fun numbersOutsideJsonsGrammarAreRejected() { + for (bad in listOf("0.5f", "0.5D", "0x1p-1", ".5", "1.", "+0.5", "00.5")) { + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "flick", "t": [1,0,1], "x": $bad, "y": 0, "size": 1 }""")), + IssueCode.WRONG_TYPE, + "notes[0].x", + ) + } + for (bad in listOf("01", "+1", "0x1")) { + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1], "lane": $bad }""")), + IssueCode.WRONG_TYPE, + "notes[0].lane", + ) + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [$bad,0,1], "lane": 0 }""")), + IssueCode.WRONG_TYPE, + "notes[0].t", + ) + } + } + + @Test + fun numbersInJsonsGrammarAreRead() { + val values = listOf("0" to 0.0, "1.5" to 1.5, "-0.5" to -0.5, "1e-2" to 0.01, "1E2" to 100.0, "2.5e+1" to 25.0) + for ((text, value) in values) { + val note = ChartParser.parseDifficulty( + chartWithNote("""{ "type": "flick", "t": [1,0,1], "x": $text, "y": 0, "size": 1 }"""), + ).value?.notes?.single() as Note.Flick + assertEquals(value, note.x, text) + } + } + + @Test + fun wholeNumbersAreDigitsOnly() { + for (bad in listOf("1e0", "1E0", "1.0")) { + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1], "lane": $bad }""")), + IssueCode.WRONG_TYPE, + "notes[0].lane", + ) + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [$bad,0,1], "lane": 0 }""")), + IssueCode.WRONG_TYPE, + "notes[0].t", + ) + } + assertSingleError(ChartParser.parseDifficulty("""{ "formatVersion": 1e0 }"""), IssueCode.WRONG_TYPE, "formatVersion") + assertEquals( + Note.Tap(Beat(1, 0, 1), -1), + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1], "lane": -1 }""")).value?.notes?.single(), + ) + } + + @Test + fun theLastRepeatedKeyWins() { + val note = ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1], "lane": 0, "lane": 3 }""")) + assertEquals(emptyList(), note.issues) + assertEquals(Note.Tap(Beat(1, 0, 1), 3), note.value?.notes?.single()) + } + + @Test + fun filesOverTheSizeLimitAreRejectedBeforeReading() { + val limit = ChartLimits.MAX_JSON_FILE_CHARS + assertEquals(2 * 1024 * 1024, limit) + assertSingleError(ChartParser.parseDifficulty(" ".repeat(limit + 1)), IssueCode.FILE_TOO_LARGE, "$") + assertSingleError(ChartParser.parseMeta(" ".repeat(limit + 1)), IssueCode.FILE_TOO_LARGE, "$") + assertSingleError(ChartParser.parseDifficulty("[".repeat(limit + 1)), IssueCode.FILE_TOO_LARGE, "$") + } + + @Test + fun fileAtTheSizeLimitIsRead() { + val padded = specExample + " ".repeat(ChartLimits.MAX_JSON_FILE_CHARS - specExample.length) + assertEquals(emptyList(), ChartParser.parseDifficulty(padded).issues) + } + + @Test + fun theWorstFileUnderTheLimitStaysBounded() { + val start = """{ "formatVersion": 1, "difficulty": "BASIC", "level": 1, "laneCount": 4, "offsetMs": 0, "bpm": [], "meter": [], "notes": [""" + val end = "1] }" + val items = (ChartLimits.MAX_JSON_FILE_CHARS - start.length - end.length) / 2 + val result = ChartParser.parseDifficulty(start + "1,".repeat(items) + end) + assertNull(result.value) + assertEquals(ChartLimits.MAX_PARSE_ISSUES + 1, result.issues.size) + } + + @Test + fun theHeaviestNestingUnderTheLimitIsStillReported() { + val start = """{ "formatVersion": 1, "extra": [""" + val end = "1] }" + val item = "[".repeat(30) + "1" + "]".repeat(30) + "," + val items = (ChartLimits.MAX_JSON_FILE_CHARS - start.length - end.length) / item.length + val result = ChartParser.parseDifficulty(start + item.repeat(items) + end) + assertNull(result.value) + assertTrue(result.issues.any { it.code == IssueCode.MISSING_FIELD }) + } + + private fun notesText(count: Int, note: String) = chartWithNote(List(count) { note }.joinToString()) + + @Test + fun issuesStopAtTheCapWithAFinalIssue() { + val limit = ChartLimits.MAX_PARSE_ISSUES + assertEquals(100, limit) + + val atCap = ChartParser.parseDifficulty(notesText(limit, "1")) + assertEquals(limit, atCap.issues.size) + assertTrue(atCap.issues.none { it.code == IssueCode.TOO_MANY_PROBLEMS }) + + val over = ChartParser.parseDifficulty(notesText(limit + 50, "1")) + assertNull(over.value) + assertEquals(limit + 1, over.issues.size) + assertEquals(IssueCode.WRONG_TYPE, over.issues[limit - 1].code) + assertEquals(IssueCode.TOO_MANY_PROBLEMS, over.issues[limit].code) + assertEquals(Severity.ERROR, over.issues[limit].severity) + } + + @Test + fun tooManyWarningsStillLoadTheChart() { + val fields = List(ChartLimits.MAX_PARSE_ISSUES + 5) { """"extra$it": 0""" }.joinToString() + val result = ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1], "lane": 0, $fields }""")) + assertNotNull(result.value) + assertEquals(ChartLimits.MAX_PARSE_ISSUES + 1, result.issues.size) + assertEquals(IssueCode.TOO_MANY_PROBLEMS, result.issues.last().code) + assertEquals(Severity.WARNING, result.issues.last().severity) + } + + @Test + fun anErrorPastTheCapStillFailsAndSaysSo() { + val fields = List(ChartLimits.MAX_PARSE_ISSUES + 5) { """"extra$it": 0""" }.joinToString() + val result = ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1], "lane": 0, $fields }, 1""")) + assertNull(result.value) + assertEquals(ChartLimits.MAX_PARSE_ISSUES + 1, result.issues.size) + assertTrue(result.issues.any { it.severity == Severity.ERROR }) + assertEquals(Severity.ERROR, result.issues.last().severity) + } + + @Test + fun longTextInIssuesIsShortened() { + val long = "x".repeat(10_000) + val limit = ChartLimits.MAX_ISSUE_TEXT_CHARS + val type = ChartParser.parseDifficulty(chartWithNote("""{ "type": "$long" }""")).issues.single() + assertTrue(type.message.length < limit * 2, type.message.length.toString()) + + val difficulty = ChartParser.parseDifficulty(specExample.replace("EXPERT", long)).issues.single() + assertTrue(difficulty.message.length < limit * 2, difficulty.message.length.toString()) + + val field = ChartParser.parseDifficulty(specExample.replace(""""level": 11,""", """"level": 11, "$long": 0,""")).issues.single() + assertTrue(field.path.length < limit * 2, field.path.length.toString()) + + val broken = ChartParser.parseDifficulty("{ \"$long").issues.single() + assertTrue(broken.message.length < limit * 2, broken.message.length.toString()) + } + + @Test + fun rootMustBeAnObject() { + assertSingleError(ChartParser.parseDifficulty("[]"), IssueCode.WRONG_TYPE, "$") + } + + @Test + fun unknownFormatVersionStopsParsing() { + val text = """{ "formatVersion": 2, "somethingNew": true }""" + assertSingleError(ChartParser.parseDifficulty(text), IssueCode.UNKNOWN_FORMAT_VERSION, "formatVersion") + assertSingleError(ChartParser.parseMeta(text), IssueCode.UNKNOWN_FORMAT_VERSION, "formatVersion") + } + + @Test + fun missingFormatVersionStopsParsing() { + assertSingleError(ChartParser.parseDifficulty("{}"), IssueCode.MISSING_FIELD, "formatVersion") + assertSingleError( + ChartParser.parseDifficulty("""{ "formatVersion": "1" }"""), + IssueCode.WRONG_TYPE, + "formatVersion", + ) + } + + @Test + fun missingFieldsNameTheirPath() { + assertSingleError( + ChartParser.parseDifficulty(specExample.replace(""""level": 11,""", "")), + IssueCode.MISSING_FIELD, + "level", + ) + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1] }""")), + IssueCode.MISSING_FIELD, + "notes[0].lane", + ) + assertSingleError( + ChartParser.parseMeta(metaExample.replace(""""type": "permitted", """, "")), + IssueCode.MISSING_FIELD, + "license.type", + ) + } + + /** Flicks hit from any direction, so a `dir` left in an older chart is just an unknown field. */ + @Test + fun aFlickDirIsAnUnknownField() { + val result = ChartParser.parseDifficulty(chartWithNote("""{ "type": "flick", "t": [1,0,1], "x": 0, "y": 0, "dir": 90, "size": 1 }""")) + assertEquals(Note.Flick(Beat(1, 0, 1), 0.0, 0.0, 1.0), result.value!!.notes.single()) + val issue = result.issues.single() + assertEquals(Severity.WARNING, issue.severity) + assertEquals(IssueCode.UNKNOWN_FIELD, issue.code) + assertEquals("notes[0].dir", issue.path) + } + + @Test + fun everyNoteFieldIsRequired() { + val notes = listOf( + """{ "type": "tap", "t": [1,0,1], "lane": 0 }""" to listOf("t", "lane"), + """{ "type": "hold", "t": [1,0,1], "end": [2,0,1], "lane": 0 }""" to listOf("t", "end", "lane"), + """{ "type": "skyTap", "t": [1,0,1], "x": 0, "y": 0, "button": "L", "size": 1 }""" to + listOf("t", "x", "y", "button", "size"), + """{ "type": "slide", "button": "L", "radius": 0.1, "points": [] }""" to + listOf("button", "radius", "points"), + """{ "type": "flick", "t": [1,0,1], "x": 0, "y": 0, "size": 1 }""" to + listOf("t", "x", "y", "size"), + ) + for ((note, fields) in notes) { + assertEquals(emptyList(), ChartParser.parseDifficulty(chartWithNote(note)).issues, note) + for (field in fields) { + val without = note.replace(Regex(""", "$field": (\[[^]]*]|"[^"]*"|[\d.]+)"""), "") + assertSingleError( + ChartParser.parseDifficulty(chartWithNote(without)), + IssueCode.MISSING_FIELD, + "notes[0].$field", + ) + } + } + } + + @Test + fun slidePointFieldsAreRequired() { + val slide = """{ "type": "slide", "button": "L", "radius": 0.1, "points": [ { "t": [1,0,1], "x": 0, "y": 0 } ] }""" + assertSingleError( + ChartParser.parseDifficulty(chartWithNote(slide)), + IssueCode.MISSING_FIELD, + "notes[0].points[0].ease", + ) + } + + @Test + fun wrongTypesAreReported() { + val cases = listOf( + """"lane": "0"""" to "notes[0].lane", + """"lane": 1.5""" to "notes[0].lane", + """"lane": 99999999999""" to "notes[0].lane", + """"lane": true""" to "notes[0].lane", + """"lane": null""" to "notes[0].lane", + ) + for ((lane, path) in cases) { + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": [1,0,1], $lane }""")), + IssueCode.WRONG_TYPE, + path, + ) + } + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("").replace("[ ]", "1").replace("[ ]", "1")), + IssueCode.WRONG_TYPE, + "notes", + ) + assertSingleError(ChartParser.parseDifficulty(chartWithNote("1")), IssueCode.WRONG_TYPE, "notes[0]") + } + + @Test + fun numbersMustBeFinite() { + assertSingleError( + ChartParser.parseDifficulty(specExample.replace(""""offsetMs": 120""", """"offsetMs": 1e999""")), + IssueCode.WRONG_TYPE, + "offsetMs", + ) + } + + @Test + fun beatsMustBeThreeWholeNumbers() { + for (beat in listOf("[1,0]", "[1,0,1,0]", "[1,0.5,1]", """[1,"0",1]""", "4", "[99999999999,0,1]")) { + assertSingleError( + ChartParser.parseDifficulty(chartWithNote("""{ "type": "tap", "t": $beat, "lane": 0 }""")), + IssueCode.WRONG_TYPE, + "notes[0].t", + ) + } + } + + @Test + fun unknownNamesAreReportedWithTheirChoices() { + val noteType = ChartParser.parseDifficulty(chartWithNote("""{ "type": "laser" }""")) + assertSingleError(noteType, IssueCode.UNKNOWN_VALUE, "notes[0].type") + assertTrue("laser" in noteType.issues[0].message) + assertTrue("flick" in noteType.issues[0].message) + + val difficulty = ChartParser.parseDifficulty(specExample.replace("EXPERT", "expert")) + assertSingleError(difficulty, IssueCode.UNKNOWN_VALUE, "difficulty") + assertTrue("MASTER" in difficulty.issues[0].message) + + assertSingleError( + ChartParser.parseDifficulty(specExample.replace(""""button": "L", "size"""", """"button": "M", "size"""")), + IssueCode.UNKNOWN_VALUE, + "notes[2].button", + ) + assertSingleError( + ChartParser.parseDifficulty(specExample.replace("inOut", "bounce")), + IssueCode.UNKNOWN_VALUE, + "notes[3].points[1].ease", + ) + assertSingleError( + ChartParser.parseMeta(metaExample.replace("permitted", "stolen")), + IssueCode.UNKNOWN_VALUE, + "license.type", + ) + assertSingleError( + ChartParser.parseMeta(metaExample.replace("BASIC", "EASY")), + IssueCode.UNKNOWN_VALUE, + "difficulties[0]", + ) + } + + @Test + fun unknownFieldsWarnAndStillLoad() { + val result = ChartParser.parseDifficulty( + specExample + .replace(""""level": 11,""", """"level": 11, "mood": "calm",""") + .replace(""""lane": 0 }""", """"lane": 0, "colour": 3 }"""), + ) + assertNotNull(result.value) + assertEquals(listOf("mood", "notes[0].colour"), result.issues.map { it.path }) + for (issue in result.issues) { + assertEquals(Severity.WARNING, issue.severity) + assertEquals(IssueCode.UNKNOWN_FIELD, issue.code) + } + assertEquals(Note.Tap(Beat(4, 0, 1), 0), result.value.notes.first()) + } + + @Test + fun unknownFieldsWarnInMeta() { + val result = ChartParser.parseMeta(metaExample.replace(""""type": "permitted",""", """"type": "permitted", "year": 2026,""")) + assertNotNull(result.value) + assertEquals("license.year", result.issues.single().path) + } + + @Test + fun everyErrorInAFileIsReported() { + val result = ChartParser.parseDifficulty( + """{ "formatVersion": 1, "level": "x", "laneCount": 4, "offsetMs": 0, "bpm": [], "meter": [], + "notes": [ { "type": "tap", "t": [1,0,1] }, { "type": "laser" } ] }""", + ) + assertNull(result.value) + assertEquals( + listOf("difficulty", "level", "notes[0].lane", "notes[1].type"), + result.issues.map { it.path }, + ) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartValidatorTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartValidatorTest.kt new file mode 100644 index 0000000..17bad0e --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartValidatorTest.kt @@ -0,0 +1,570 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** Every rule has a passing and a failing case. A failing case must give exactly one issue, with no follow-on errors. */ +class ChartValidatorTest { + private fun b(whole: Int, num: Int = 0, den: Int = 1) = Beat(whole, num, den) + + private val chart = DifficultyChart( + formatVersion = 1, + difficulty = Difficulty.EXPERT, + level = 1, + laneCount = 4, + offsetMs = 0.0, + bpm = listOf(BpmChange(b(0), 120.0)), + meter = listOf(MeterChange(b(0), 4, 4)), + notes = emptyList(), + ) + + private fun withNotes(vararg notes: Note) = chart.copy(notes = notes.toList()) + + private fun slide(vararg points: SlidePoint, radius: Double = 0.1) = Note.Slide(SkyButton.L, radius, points.toList()) + + private fun point(t: Beat, x: Double = 0.5, y: Double = 0.5) = SlidePoint(t, x, y, Ease.LINEAR) + + private fun skyTap(t: Beat, x: Double = 0.5, y: Double = 0.5, size: Double = 1.0) = + Note.SkyTap(t, x, y, SkyButton.L, size) + + private fun flick(t: Beat, x: Double = 0.5, y: Double = 0.5, size: Double = 1.0) = + Note.Flick(t, x, y, size) + + private fun assertValid(chart: DifficultyChart, audioDurationMs: Double? = null) { + assertEquals(emptyList(), ChartValidator.validateChart(chart, audioDurationMs)) + } + + private fun assertOnlyIssue( + issues: List, + code: IssueCode, + path: String, + severity: Severity = Severity.ERROR, + ) { + assertEquals(1, issues.size, issues.toString()) + assertEquals(code, issues[0].code) + assertEquals(path, issues[0].path) + assertEquals(severity, issues[0].severity) + assertTrue(issues[0].message.isNotBlank()) + } + + private fun assertOnlyError(chart: DifficultyChart, code: IssueCode, path: String, audioDurationMs: Double? = null) { + assertOnlyIssue(ChartValidator.validateChart(chart, audioDurationMs), code, path) + } + + @Test + fun emptyChartIsValid() = assertValid(chart) + + // formatVersion + + @Test + fun knownFormatVersionPasses() = assertValid(chart.copy(formatVersion = 1)) + + @Test + fun unknownFormatVersionFails() = + assertOnlyError(chart.copy(formatVersion = 2), IssueCode.UNKNOWN_FORMAT_VERSION, "formatVersion") + + // laneCount and level + + @Test + fun fourLanesPass() = assertValid(chart.copy(laneCount = 4)) + + @Test + fun otherLaneCountsFail() { + assertOnlyError(chart.copy(laneCount = 6), IssueCode.BAD_LANE_COUNT, "laneCount") + assertOnlyError(chart.copy(laneCount = 0), IssueCode.BAD_LANE_COUNT, "laneCount") + } + + @Test + fun levelOneAndUpPasses() { + assertValid(chart.copy(level = 1)) + assertValid(chart.copy(level = 15)) + } + + @Test + fun levelBelowOneFails() = assertOnlyError(chart.copy(level = 0), IssueCode.BAD_LEVEL, "level") + + // Fractions + + @Test + fun unreducedFractionsPass() = assertValid(withNotes(Note.Tap(b(12, 2, 4), 0))) + + @Test + fun invalidFractionsFailOnceEverywhere() { + val bad = b(12, 5, 4) + assertOnlyError(withNotes(Note.Tap(bad, 0)), IssueCode.INVALID_BEAT, "notes[0].t") + assertOnlyError(withNotes(Note.Hold(bad, b(13), 0)), IssueCode.INVALID_BEAT, "notes[0].t") + assertOnlyError(withNotes(Note.Hold(b(1), bad, 0)), IssueCode.INVALID_BEAT, "notes[0].end") + assertOnlyError(withNotes(skyTap(bad)), IssueCode.INVALID_BEAT, "notes[0].t") + assertOnlyError(withNotes(flick(bad)), IssueCode.INVALID_BEAT, "notes[0].t") + assertOnlyError( + withNotes(slide(point(b(1)), point(bad), point(b(2)))), + IssueCode.INVALID_BEAT, + "notes[0].points[1].t", + ) + assertOnlyError( + chart.copy(bpm = chart.bpm + BpmChange(bad, 90.0)), + IssueCode.INVALID_BEAT, + "bpm[1].t", + ) + assertOnlyError( + chart.copy(meter = chart.meter + MeterChange(bad, 3, 4)), + IssueCode.INVALID_BEAT, + "meter[1].t", + ) + } + + @Test + fun invalidFractionKindsAreAllCaught() { + for (bad in listOf(b(-1), b(1, 4, 4), b(1, -1, 4), b(1, 0, 0), b(1, 0, -4))) { + assertOnlyError(withNotes(Note.Tap(bad, 0)), IssueCode.INVALID_BEAT, "notes[0].t") + } + } + + @Test + fun audioRuleSkipsNotesWithInvalidBeats() { + assertOnlyError(withNotes(Note.Tap(b(1, 0, 0), 0)), IssueCode.INVALID_BEAT, "notes[0].t", audioDurationMs = 1.0) + } + + // BPM + + @Test + fun bpmAboveZeroPasses() = assertValid(chart.copy(bpm = listOf(BpmChange(b(0), 0.001)))) + + @Test + fun bpmAtOrBelowZeroFails() { + for (bad in listOf(0.0, -120.0, Double.NaN)) { + assertOnlyError(chart.copy(bpm = listOf(BpmChange(b(0), bad))), IssueCode.BPM_NOT_POSITIVE, "bpm[0].bpm") + } + } + + @Test + fun bpmWhoseBeatLengthIsNotFiniteFails() { + for (bad in listOf(1e-320, Double.POSITIVE_INFINITY)) { + assertOnlyError(chart.copy(bpm = listOf(BpmChange(b(0), bad))), IssueCode.BPM_NOT_POSITIVE, "bpm[0].bpm") + } + } + + @Test + fun finiteOffsetPasses() = assertValid(chart.copy(offsetMs = -250.5)) + + @Test + fun offsetThatIsNotFiniteFails() { + for (bad in listOf(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)) { + assertOnlyError(chart.copy(offsetMs = bad), IssueCode.OFFSET_NOT_FINITE, "offsetMs") + } + } + + @Test + fun audioRuleIsSkippedWhenTheOffsetIsBroken() { + assertOnlyError( + chart.copy(offsetMs = Double.NaN, notes = listOf(Note.Tap(b(4), 0))), + IssueCode.OFFSET_NOT_FINITE, + "offsetMs", + audioDurationMs = 1.0, + ) + } + + @Test + fun firstBpmAtBeatZeroPasses() = assertValid(chart.copy(bpm = listOf(BpmChange(b(0, 0, 4), 120.0)))) + + @Test + fun firstBpmElsewhereFails() { + assertOnlyError(chart.copy(bpm = listOf(BpmChange(b(1), 120.0))), IssueCode.FIRST_BPM_NOT_AT_ZERO, "bpm[0].t") + assertOnlyError(chart.copy(bpm = emptyList()), IssueCode.FIRST_BPM_NOT_AT_ZERO, "bpm") + } + + @Test + fun risingBpmPasses() = assertValid(chart.copy(bpm = chart.bpm + BpmChange(b(0, 1, 2), 90.0) + BpmChange(b(1), 60.0))) + + @Test + fun bpmNotRisingFails() { + val same = chart.bpm + BpmChange(b(0, 0, 3), 90.0) + assertOnlyError(chart.copy(bpm = same), IssueCode.BPM_NOT_RISING, "bpm[1].t") + val back = chart.bpm + BpmChange(b(4), 90.0) + BpmChange(b(2), 60.0) + assertOnlyError(chart.copy(bpm = back), IssueCode.BPM_NOT_RISING, "bpm[2].t") + } + + // Meter + + @Test + fun firstMeterAtBeatZeroPasses() = assertValid(chart.copy(meter = listOf(MeterChange(b(0, 0, 2), 3, 4)))) + + @Test + fun firstMeterElsewhereFails() { + assertOnlyError(chart.copy(meter = listOf(MeterChange(b(1), 4, 4))), IssueCode.FIRST_METER_NOT_AT_ZERO, "meter[0].t") + assertOnlyError(chart.copy(meter = emptyList()), IssueCode.FIRST_METER_NOT_AT_ZERO, "meter") + } + + @Test + fun risingMeterPasses() = assertValid(chart.copy(meter = chart.meter + MeterChange(b(4), 3, 4))) + + @Test + fun meterNotRisingFails() { + assertOnlyError(chart.copy(meter = chart.meter + MeterChange(b(0), 3, 4)), IssueCode.METER_NOT_RISING, "meter[1].t") + } + + @Test + fun meterAboveZeroPasses() = assertValid(chart.copy(meter = listOf(MeterChange(b(0), 7, 8)))) + + @Test + fun meterAtOrBelowZeroFails() { + assertOnlyError(chart.copy(meter = listOf(MeterChange(b(0), 0, 4))), IssueCode.METER_NOT_POSITIVE, "meter[0].num") + assertOnlyError(chart.copy(meter = listOf(MeterChange(b(0), 4, -4))), IssueCode.METER_NOT_POSITIVE, "meter[0].den") + } + + // Lanes and holds + + @Test + fun lanesInRangePass() = assertValid(withNotes(Note.Tap(b(1), 0), Note.Tap(b(1), 3), Note.Hold(b(2), b(3), 3))) + + @Test + fun lanesOutOfRangeFail() { + assertOnlyError(withNotes(Note.Tap(b(1), 4)), IssueCode.LANE_OUT_OF_RANGE, "notes[0].lane") + assertOnlyError(withNotes(Note.Tap(b(1), -1)), IssueCode.LANE_OUT_OF_RANGE, "notes[0].lane") + assertOnlyError(withNotes(Note.Hold(b(1), b(2), 4)), IssueCode.LANE_OUT_OF_RANGE, "notes[0].lane") + } + + @Test + fun holdEndingAfterItsStartPasses() = assertValid(withNotes(Note.Hold(b(1), b(1, 1, 32), 0))) + + @Test + fun holdNotEndingAfterItsStartFails() { + assertOnlyError(withNotes(Note.Hold(b(1), b(1), 0)), IssueCode.HOLD_END_NOT_AFTER_START, "notes[0].end") + assertOnlyError(withNotes(Note.Hold(b(1, 2, 4), b(1, 1, 2), 0)), IssueCode.HOLD_END_NOT_AFTER_START, "notes[0].end") + assertOnlyError(withNotes(Note.Hold(b(2), b(1), 0)), IssueCode.HOLD_END_NOT_AFTER_START, "notes[0].end") + } + + @Test + fun holdsThatDoNotOverlapPass() { + assertValid(withNotes(Note.Hold(b(1), b(2), 0), Note.Hold(b(3), b(4), 0))) + assertValid(withNotes(Note.Hold(b(1), b(2), 0), Note.Hold(b(1), b(2), 1))) + } + + @Test + fun holdMayStartWhereAnotherEnds() = assertValid(withNotes(Note.Hold(b(1), b(2), 0), Note.Hold(b(2), b(3), 0))) + + @Test + fun overlappingHoldsFail() { + assertOnlyError( + withNotes(Note.Hold(b(1), b(3), 0), Note.Hold(b(2), b(4), 0)), + IssueCode.HOLDS_OVERLAP, + "notes[1]", + ) + } + + @Test + fun holdsOverlapWhateverTheFileOrder() { + assertOnlyError( + withNotes(Note.Hold(b(2), b(4), 0), Note.Hold(b(1), b(3), 0)), + IssueCode.HOLDS_OVERLAP, + "notes[0]", + ) + } + + @Test + fun holdInsideALongerHoldFailsEvenAfterAShortOne() { + val issues = ChartValidator.validateChart( + withNotes(Note.Hold(b(1), b(10), 0), Note.Hold(b(2), b(3), 0), Note.Hold(b(4), b(5), 0)), + ) + assertEquals(listOf("notes[1]", "notes[2]"), issues.map { it.path }) + assertEquals(setOf(IssueCode.HOLDS_OVERLAP), issues.map { it.code }.toSet()) + } + + @Test + fun holdsSharingAHeadFailOnce() { + assertOnlyError(withNotes(Note.Hold(b(1), b(2), 0), Note.Hold(b(1), b(3), 0)), IssueCode.HOLDS_OVERLAP, "notes[1]") + } + + @Test + fun tapOutsideAHoldPasses() { + assertValid(withNotes(Note.Hold(b(2), b(3), 0), Note.Tap(b(1), 0), Note.Tap(b(4), 0))) + assertValid(withNotes(Note.Hold(b(2), b(3), 0), Note.Tap(b(2, 1, 2), 1))) + } + + @Test + fun tapOnAHoldsEndPasses() = assertValid(withNotes(Note.Hold(b(2), b(3), 0), Note.Tap(b(3), 0))) + + @Test + fun tapInsideAHoldFails() { + assertOnlyError(withNotes(Note.Hold(b(2), b(3), 0), Note.Tap(b(2, 1, 2), 0)), IssueCode.TAP_INSIDE_HOLD, "notes[1]") + } + + @Test + fun tapOnAHoldsHeadFailsOnce() { + assertOnlyError(withNotes(Note.Tap(b(2), 0), Note.Hold(b(2), b(3), 0)), IssueCode.TAP_INSIDE_HOLD, "notes[0]") + } + + @Test + fun tapInsideALongHoldAfterAShortOneFails() { + val issues = ChartValidator.validateChart( + withNotes(Note.Hold(b(1), b(10), 0), Note.Hold(b(2), b(3), 0), Note.Tap(b(5), 0)), + ) + assertEquals( + listOf(IssueCode.HOLDS_OVERLAP to "notes[1]", IssueCode.TAP_INSIDE_HOLD to "notes[2]"), + issues.map { it.code to it.path }, + ) + } + + @Test + fun tapsAtDifferentTimesOrLanesPass() { + assertValid(withNotes(Note.Tap(b(1), 0), Note.Tap(b(1), 1), Note.Tap(b(2), 0))) + } + + @Test + fun twoTapsAtTheSameTimeAndLaneFail() { + assertOnlyError(withNotes(Note.Tap(b(1, 1, 2), 0), Note.Tap(b(1, 2, 4), 0)), IssueCode.DUPLICATE_TAP, "notes[1]") + } + + // Slides, positions, sizes + + @Test + fun slideWithRisingPointsPasses() = assertValid(withNotes(slide(point(b(1)), point(b(1, 1, 8)), point(b(2))))) + + @Test + fun slideWithTooFewPointsFails() { + assertOnlyError(withNotes(slide(point(b(1)))), IssueCode.SLIDE_TOO_FEW_POINTS, "notes[0].points") + assertOnlyError(withNotes(slide()), IssueCode.SLIDE_TOO_FEW_POINTS, "notes[0].points") + } + + @Test + fun slidePointsNotRisingFail() { + assertOnlyError( + withNotes(slide(point(b(1)), point(b(1, 0, 2)))), + IssueCode.SLIDE_POINTS_NOT_RISING, + "notes[0].points[1].t", + ) + assertOnlyError( + withNotes(slide(point(b(2)), point(b(1)))), + IssueCode.SLIDE_POINTS_NOT_RISING, + "notes[0].points[1].t", + ) + } + + @Test + fun positionsInsideTheScreenPass() { + assertValid( + withNotes( + skyTap(b(1), x = 0.0, y = 1.0), + flick(b(2), x = 1.0, y = 0.0), + slide(point(b(3), 0.0, 0.0), point(b(4), 1.0, 1.0)), + ), + ) + } + + @Test + fun positionsOutsideTheScreenFail() { + assertOnlyError(withNotes(skyTap(b(1), x = -0.01)), IssueCode.POSITION_OUT_OF_RANGE, "notes[0].x") + assertOnlyError(withNotes(skyTap(b(1), y = 1.01)), IssueCode.POSITION_OUT_OF_RANGE, "notes[0].y") + assertOnlyError(withNotes(flick(b(1), x = 1.5)), IssueCode.POSITION_OUT_OF_RANGE, "notes[0].x") + assertOnlyError(withNotes(flick(b(1), y = Double.NaN)), IssueCode.POSITION_OUT_OF_RANGE, "notes[0].y") + assertOnlyError( + withNotes(slide(point(b(1)), point(b(2), x = 2.0))), + IssueCode.POSITION_OUT_OF_RANGE, + "notes[0].points[1].x", + ) + assertOnlyError( + withNotes(slide(point(b(1), y = -1.0), point(b(2)))), + IssueCode.POSITION_OUT_OF_RANGE, + "notes[0].points[0].y", + ) + } + + @Test + fun sizeAndRadiusAboveZeroPass() { + assertValid(withNotes(skyTap(b(1), size = 0.1), flick(b(2), size = 0.1), slide(point(b(3)), point(b(4)), radius = 0.01))) + } + + @Test + fun sizeAndRadiusAtOrBelowZeroFail() { + assertOnlyError(withNotes(skyTap(b(1), size = 0.0)), IssueCode.SIZE_NOT_POSITIVE, "notes[0].size") + assertOnlyError(withNotes(flick(b(1), size = -1.0)), IssueCode.SIZE_NOT_POSITIVE, "notes[0].size") + assertOnlyError(withNotes(slide(point(b(1)), point(b(2)), radius = 0.0)), IssueCode.RADIUS_NOT_POSITIVE, "notes[0].radius") + for (bad in listOf(Double.NaN, Double.POSITIVE_INFINITY)) { + assertOnlyError(withNotes(skyTap(b(1), size = bad)), IssueCode.SIZE_NOT_POSITIVE, "notes[0].size") + assertOnlyError(withNotes(slide(point(b(1)), point(b(2)), radius = bad)), IssueCode.RADIUS_NOT_POSITIVE, "notes[0].radius") + } + } + + // The last note against the audio. At 120 BPM, beat 4 is 2000 ms. + + @Test + fun notesEndingBeforeTheAudioPass() { + assertValid(withNotes(Note.Tap(b(4), 0)), audioDurationMs = 2000.5) + } + + @Test + fun audioRuleIsSkippedWithoutALength() = assertValid(withNotes(Note.Tap(b(4000), 0)), audioDurationMs = null) + + @Test + fun lastNoteAtOrPastTheAudioEndFails() { + assertOnlyError(withNotes(Note.Tap(b(4), 0)), IssueCode.NOTE_AFTER_AUDIO, "notes[0]", audioDurationMs = 2000.0) + assertOnlyError(withNotes(Note.Tap(b(5), 0)), IssueCode.NOTE_AFTER_AUDIO, "notes[0]", audioDurationMs = 2000.0) + } + + @Test + fun audioRuleUsesWhereANoteEnds() { + assertOnlyError(withNotes(Note.Hold(b(1), b(4), 0)), IssueCode.NOTE_AFTER_AUDIO, "notes[0]", audioDurationMs = 2000.0) + assertOnlyError(withNotes(slide(point(b(1)), point(b(4)))), IssueCode.NOTE_AFTER_AUDIO, "notes[0]", audioDurationMs = 2000.0) + assertOnlyError(withNotes(skyTap(b(4))), IssueCode.NOTE_AFTER_AUDIO, "notes[0]", audioDurationMs = 2000.0) + assertOnlyError(withNotes(flick(b(4))), IssueCode.NOTE_AFTER_AUDIO, "notes[0]", audioDurationMs = 2000.0) + } + + @Test + fun audioRuleReportsOnlyTheLastNoteWhateverTheFileOrder() { + assertOnlyError( + withNotes(Note.Tap(b(5), 0), Note.Tap(b(6), 0), Note.Tap(b(1), 0)), + IssueCode.NOTE_AFTER_AUDIO, + "notes[1]", + audioDurationMs = 2000.0, + ) + } + + @Test + fun audioRuleUsesOffsetAndBpmChanges() { + val timed = chart.copy(offsetMs = 500.0, bpm = chart.bpm + BpmChange(b(2), 60.0)) + val note = Note.Tap(b(3), 0) + assertValid(timed.copy(notes = listOf(note)), audioDurationMs = 2500.5) + assertOnlyError(timed.copy(notes = listOf(note)), IssueCode.NOTE_AFTER_AUDIO, "notes[0]", audioDurationMs = 2500.0) + } + + @Test + fun audioRuleIsSkippedWhenBpmIsBroken() { + val broken = chart.copy(bpm = listOf(BpmChange(b(0), 0.0)), notes = listOf(Note.Tap(b(4), 0))) + assertOnlyError(broken, IssueCode.BPM_NOT_POSITIVE, "bpm[0].bpm", audioDurationMs = 1.0) + } + + // The judged-object limit. A hold has its head plus a tick every 1/4 beat between its start and end. + + @Test + fun chartAtTheJudgedObjectLimitPasses() { + assertEquals(1_000_000, ChartLimits.MAX_JUDGED_OBJECTS) + assertValid(withNotes(Note.Hold(b(0), b(250_000), 0))) + } + + @Test + fun chartOverTheJudgedObjectLimitFails() { + assertOnlyError(withNotes(Note.Hold(b(0), b(250_000, 1, 4), 0)), IssueCode.TOO_MANY_JUDGED_OBJECTS, "notes") + assertOnlyError(withNotes(Note.Hold(b(0), b(Int.MAX_VALUE), 0)), IssueCode.TOO_MANY_JUDGED_OBJECTS, "notes") + assertOnlyError( + withNotes(slide(point(b(0)), point(b(Int.MAX_VALUE)))), + IssueCode.TOO_MANY_JUDGED_OBJECTS, + "notes", + ) + } + + // Times must stay finite, or a note could never be judged. + + @Test + fun noteTimesThatOverflowFail() { + val slow = chart.copy(bpm = listOf(BpmChange(b(0), 1e-300))) + assertOnlyError(slow.copy(notes = listOf(Note.Tap(b(2_000_000_000), 0))), IssueCode.TIME_NOT_FINITE, "notes[0]") + } + + @Test + fun bpmChangesThatOverflowFail() { + val slow = chart.copy(bpm = listOf(BpmChange(b(0), 1e-300), BpmChange(b(2_000_000_000), 120.0))) + assertOnlyError(slow, IssueCode.TIME_NOT_FINITE, "bpm[1].t") + } + + @Test + fun verySlowChartsWithFiniteTimesPass() { + assertValid(chart.copy(bpm = listOf(BpmChange(b(0), 1e-300)), notes = listOf(Note.Tap(b(1), 0)))) + } + + // The density warning + + private fun fourLanes(t: Beat) = arrayOf(Note.Tap(t, 0), Note.Tap(t, 1), Note.Tap(t, 2), Note.Tap(t, 3)) + + private fun assertDensityWarning(chart: DifficultyChart, path: String = "notes[0]") { + assertOnlyIssue(ChartValidator.validateChart(chart), IssueCode.TOO_DENSE, path, Severity.WARNING) + } + + @Test + fun fourGroundPlusSkyWarns() = assertDensityWarning(withNotes(*fourLanes(b(1)), skyTap(b(1)))) + + @Test + fun threeGroundPlusSkyPasses() { + assertValid(withNotes(Note.Tap(b(1), 0), Note.Tap(b(1), 1), Note.Tap(b(1), 2), skyTap(b(1)))) + } + + @Test + fun fourGroundAlonePasses() = assertValid(withNotes(*fourLanes(b(1)))) + + @Test + fun holdHeadsCountAsGround() { + assertDensityWarning( + withNotes(Note.Hold(b(1), b(2), 0), Note.Tap(b(1), 1), Note.Tap(b(1), 2), Note.Tap(b(1), 3), skyTap(b(1))), + ) + } + + @Test + fun heldKeysDoNotCount() { + assertValid(withNotes(Note.Hold(b(0), b(2), 0), Note.Tap(b(1), 1), Note.Tap(b(1), 2), Note.Tap(b(1), 3), skyTap(b(1)))) + } + + @Test + fun flicksAndSlideStartsCountAsSky() { + assertDensityWarning(withNotes(*fourLanes(b(1)), flick(b(1)))) + assertDensityWarning(withNotes(*fourLanes(b(1)), slide(point(b(1)), point(b(2))))) + } + + @Test + fun laterSlidePointsDoNotCount() = assertValid(withNotes(*fourLanes(b(2)), slide(point(b(1)), point(b(2)), point(b(3))))) + + @Test + fun notesCloserThanASixteenthWarn() { + assertDensityWarning(withNotes(*fourLanes(b(1)), skyTap(b(1, 1, 32)))) + } + + @Test + fun notesExactlyASixteenthApartPass() = assertValid(withNotes(*fourLanes(b(1)), skyTap(b(1, 1, 16)))) + + @Test + fun theWindowSlidesAcrossSixteenthBoundaries() { + assertDensityWarning(withNotes(*fourLanes(b(1, 31, 64)), skyTap(b(1, 33, 64)))) + } + + @Test + fun theWindowIsIndependentOfFileOrder() { + assertDensityWarning(withNotes(skyTap(b(1, 1, 32)), *fourLanes(b(1))), path = "notes[1]") + } + + @Test + fun theWindowComparesHugeDenominatorsExactly() { + val max = Int.MAX_VALUE + assertDensityWarning(withNotes(*fourLanes(b(0, max - 1, max)), skyTap(b(1, 1, max)))) + assertValid(withNotes(*fourLanes(b(0, max - 1, max)), skyTap(b(2)))) + } + + @Test + fun oneClusterWarnsOnce() { + val notes = fourLanes(b(1)) + skyTap(b(1)) + skyTap(b(1, 1, 64)) + skyTap(b(1, 2, 64)) + assertDensityWarning(chart.copy(notes = notes.toList())) + } + + @Test + fun clustersSharingOneNoteWarnOnce() { + val shared = skyTap(b(1, 2, 64)) + val notes = fourLanes(b(1)) + shared + fourLanes(b(1, 5, 64)) + assertDensityWarning(chart.copy(notes = notes.toList())) + } + + @Test + fun separateClustersWarnSeparately() { + val notes = fourLanes(b(1)) + skyTap(b(1)) + fourLanes(b(2)) + skyTap(b(2)) + val issues = ChartValidator.validateChart(chart.copy(notes = notes.toList())) + assertEquals(listOf("notes[0]", "notes[5]"), issues.map { it.path }) + } + + @Test + fun manyProblemsAreAllReported() { + val issues = ChartValidator.validateChart( + chart.copy(level = 0, laneCount = 6, notes = listOf(Note.Tap(b(1), 9), skyTap(b(1), x = 2.0))), + ) + assertEquals( + listOf(IssueCode.BAD_LEVEL, IssueCode.BAD_LANE_COUNT, IssueCode.LANE_OUT_OF_RANGE, IssueCode.POSITION_OUT_OF_RANGE), + issues.map { it.code }, + ) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartWriterTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartWriterTest.kt new file mode 100644 index 0000000..f11b34e --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ChartWriterTest.kt @@ -0,0 +1,176 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class ChartWriterTest { + private val chart = DifficultyChart( + formatVersion = 1, + difficulty = Difficulty.EXPERT, + level = 11, + laneCount = 4, + offsetMs = 120.0, + bpm = listOf(BpmChange(Beat(0, 0, 1), 174.0), BpmChange(Beat(64, 0, 1), 87.5)), + meter = listOf(MeterChange(Beat(0, 0, 1), 4, 4)), + notes = listOf( + Note.Tap(Beat(4, 0, 1), 0), + Note.Hold(Beat(4, 1, 2), Beat(6, 0, 1), 2), + Note.SkyTap(Beat(5, 0, 1), 0.25, 0.6, SkyButton.L, 1.0), + Note.Slide( + SkyButton.R, + 0.06, + listOf( + SlidePoint(Beat(6, 0, 1), 0.2, 0.5, Ease.LINEAR), + SlidePoint(Beat(6, 1, 3), 0.3, 0.6, Ease.IN), + SlidePoint(Beat(6, 2, 3), 0.4, 0.7, Ease.OUT), + SlidePoint(Beat(7, 0, 1), 0.7, 0.8, Ease.IN_OUT), + ), + ), + Note.Flick(Beat(8, 0, 1), 0.5, 0.4, 1.0), + ), + ) + + private val meta = ChartMeta( + formatVersion = 1, + id = "example-song", + title = "Example \"Song\" \\ 歌\n", + artist = "Example Artist", + charter = "Example Charter", + previewStartMs = 30000, + license = License(LicenseType.PERMITTED, "https://example.com/license"), + difficulties = listOf(Difficulty.BASIC, Difficulty.MASTER), + ) + + private fun assertRoundTrips(chart: DifficultyChart) { + val result = ChartParser.parseDifficulty(ChartWriter.writeDifficulty(chart)) + assertEquals(emptyList(), result.issues) + assertEquals(chart, result.value) + } + + @Test + fun writesTheFixedLayout() { + val small = chart.copy( + bpm = chart.bpm.take(1), + notes = listOf( + Note.Tap(Beat(4, 0, 1), 0), + Note.Slide( + SkyButton.L, + 0.06, + listOf( + SlidePoint(Beat(6, 0, 1), 0.2, 0.5, Ease.LINEAR), + SlidePoint(Beat(7, 0, 1), 0.7, 0.8, Ease.IN_OUT), + ), + ), + Note.Flick(Beat(8, 0, 1), 0.5, 0.4, 1.0), + ), + ) + assertEquals( + """ + { + "formatVersion": 1, + "difficulty": "EXPERT", + "level": 11, + "laneCount": 4, + "offsetMs": 120, + "bpm": [ + { "t": [0,0,1], "bpm": 174 } + ], + "meter": [ + { "t": [0,0,1], "num": 4, "den": 4 } + ], + "notes": [ + { "type": "tap", "t": [4,0,1], "lane": 0 }, + { "type": "slide", "button": "L", "radius": 0.06, "points": [ + { "t": [6,0,1], "x": 0.2, "y": 0.5, "ease": "linear" }, + { "t": [7,0,1], "x": 0.7, "y": 0.8, "ease": "inOut" } + ] }, + { "type": "flick", "t": [8,0,1], "x": 0.5, "y": 0.4, "size": 1 } + ] + } + """.trimIndent() + "\n", + ChartWriter.writeDifficulty(small), + ) + } + + @Test + fun writesTheMetaLayout() { + assertEquals( + """ + { + "formatVersion": 1, + "id": "song", + "title": "T", + "artist": "A", + "charter": "C", + "previewStartMs": 5, + "license": { "type": "original" }, + "difficulties": [ "BASIC", "MASTER" ] + } + """.trimIndent() + "\n", + ChartWriter.writeMeta( + meta.copy( + id = "song", + title = "T", + artist = "A", + charter = "C", + previewStartMs = 5, + license = License(LicenseType.ORIGINAL, null), + ), + ), + ) + } + + @Test + fun everyNoteTypeRoundTrips() { + assertRoundTrips(chart) + } + + @Test + fun metaRoundTripsIncludingEscapedText() { + val result = ChartParser.parseMeta(ChartWriter.writeMeta(meta)) + assertEquals(emptyList(), result.issues) + assertEquals(meta, result.value) + } + + @Test + fun fractionsStayAsWritten() { + val chart = chart.copy(notes = listOf(Note.Tap(Beat(12, 2, 4), 0))) + assertEquals(true, """"t": [12,2,4]""" in ChartWriter.writeDifficulty(chart)) + assertRoundTrips(chart) + } + + @Test + fun numbersKeepTheirExactValue() { + for (value in listOf(0.0, -0.0, -250.0, 0.1, 1.0 / 3.0, 1e-7, 1e21, 123456.789)) { + assertRoundTrips(chart.copy(offsetMs = value)) + } + } + + @Test + fun forbiddenValuesStillRoundTripForTheValidator() { + assertRoundTrips( + chart.copy( + level = 0, + laneCount = 9, + bpm = emptyList(), + notes = listOf(Note.Tap(Beat(-1, 5, 0), 99)), + ), + ) + } + + @Test + fun outputIsStable() { + val once = ChartWriter.writeDifficulty(chart) + val twice = ChartWriter.writeDifficulty(ChartParser.parseDifficulty(once).value!!) + assertEquals(once, twice) + } + + @Test + fun refusesNumbersJsonCannotHold() { + assertFailsWith { ChartWriter.writeDifficulty(chart.copy(offsetMs = Double.NaN)) } + assertFailsWith { + ChartWriter.writeDifficulty(chart.copy(offsetMs = Double.POSITIVE_INFINITY)) + } + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/ExampleChartsTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ExampleChartsTest.kt new file mode 100644 index 0000000..27e6e5d --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/ExampleChartsTest.kt @@ -0,0 +1,99 @@ +package net.trilleo.hexium.core.chart + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** The hand-written charts in docs/examples and the examples in the spec must stay valid. */ +class ExampleChartsTest { + private val docs = File("../docs") + + private fun text(name: String) = File(docs, "examples/$name.json").readText() + + private fun chart(name: String): DifficultyChart { + val result = ChartParser.parseDifficulty(text(name)) + assertEquals(emptyList(), result.issues, name) + return result.value!! + } + + private val names = listOf("basic", "advanced", "expert") + + @Test + fun examplesPassTheValidatorWithoutWarnings() { + for (name in names) assertEquals(emptyList(), ChartValidator.validateChart(chart(name)), name) + } + + @Test + fun examplesAreNamedAfterTheirDifficulty() { + for (name in names) assertEquals(name, chart(name).difficulty.name.lowercase()) + } + + @Test + fun examplesAreWrittenInTheWritersLayout() { + for (name in names) assertEquals(text(name), ChartWriter.writeDifficulty(chart(name)), name) + } + + @Test + fun examplesFormAValidPackage() { + val meta = ChartMeta( + formatVersion = 1, + id = "example", + title = "Example", + artist = "Example", + charter = "Example", + previewStartMs = 0, + license = License(LicenseType.ORIGINAL, null), + difficulties = listOf(Difficulty.BASIC, Difficulty.ADVANCED, Difficulty.EXPERT), + ) + val pkg = ChartPackage(meta, names.map { chart(it) }) + assertEquals(emptyList(), ChartValidator.validatePackage(pkg, audioDurationMs = 60000.0)) + } + + @Test + fun basicIsGroundNotesOnly() { + val notes = chart("basic").notes + assertTrue(notes.any { it is Note.Tap }) + assertTrue(notes.any { it is Note.Hold }) + assertTrue(notes.all { it is Note.Tap || it is Note.Hold }) + } + + @Test + fun advancedAddsSkyTapsAndASlide() { + val notes = chart("advanced").notes + assertTrue(notes.any { it is Note.Tap }) + assertTrue(notes.any { it is Note.Hold }) + assertTrue(notes.any { it is Note.SkyTap }) + assertTrue(notes.any { it is Note.Slide }) + assertTrue(notes.none { it is Note.Flick }) + } + + @Test + fun expertUsesEveryNoteTypeAndTimingChange() { + val chart = chart("expert") + assertTrue(chart.notes.any { it is Note.Tap }) + assertTrue(chart.notes.any { it is Note.Hold }) + assertTrue(chart.notes.any { it is Note.SkyTap }) + assertTrue(chart.notes.any { it is Note.Slide }) + assertTrue(chart.notes.any { it is Note.Flick }) + assertTrue(chart.bpm.size > 1) + assertTrue(chart.meter.size > 1) + } + + @Test + fun theSpecsExamplesAreValid() { + val blocks = Regex("```json\\n(.*?)```", RegexOption.DOT_MATCHES_ALL) + .findAll(File(docs, "CHART_FORMAT.md").readText()) + .map { it.groupValues[1] } + .toList() + assertEquals(2, blocks.size) + + val meta = ChartParser.parseMeta(blocks[0]) + assertEquals(emptyList(), meta.issues) + assertEquals(emptyList(), ChartValidator.validateMeta(meta.value!!)) + + val chart = ChartParser.parseDifficulty(blocks[1]) + assertEquals(emptyList(), chart.issues) + assertEquals(emptyList(), ChartValidator.validateChart(chart.value!!)) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/GroundTrackTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/GroundTrackTest.kt new file mode 100644 index 0000000..38f1eaa --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/GroundTrackTest.kt @@ -0,0 +1,106 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals + +class GroundTrackTest { + private val tolerance = 1e-9 + + private fun beat(whole: Int) = Beat(whole, 0, 1) + + /** At 120 BPM a beat is 500 ms. */ + private fun track(vararg notes: Note, offsetMs: Double = 0.0) = GroundTrack( + DifficultyChart(1, Difficulty.BASIC, 1, 4, offsetMs, listOf(BpmChange(beat(0), 120.0)), listOf(MeterChange(beat(0), 4, 4)), notes.toList()), + ) + + @Test + fun aTapStartsAndEndsOnItsOwnTimeInItsOwnLane() { + val track = track(Note.Tap(beat(2), 3), offsetMs = 100.0) + assertEquals(1, track.size) + assertEquals(3, track.lane(0)) + assertEquals(1100.0, track.startMs(0), tolerance) + assertEquals(1100.0, track.endMs(0), tolerance) + assertEquals(false, track.isHold(0)) + } + + @Test + fun aHoldRunsFromItsStartToItsEnd() { + val track = track(Note.Hold(beat(1), beat(5), 2)) + assertEquals(500.0, track.startMs(0), tolerance) + assertEquals(2500.0, track.endMs(0), tolerance) + assertEquals(true, track.isHold(0)) + } + + @Test + fun notesAreInTimeOrderAndRememberTheirPlaceInTheChart() { + val track = track(Note.Tap(beat(3), 0), Note.Tap(beat(1), 1), Note.Hold(beat(2), beat(4), 2)) + assertEquals(listOf(500.0, 1000.0, 1500.0), List(track.size) { track.startMs(it) }) + assertEquals(listOf(1, 2, 0), List(track.size) { track.chartNote(it) }) + } + + @Test + fun skyNotesAreNotOnTheTrackButKeepTheCountOfTheChart() { + val track = track(Note.SkyTap(beat(1), 0.5, 0.5, SkyButton.L, 1.0), Note.Tap(beat(2), 0)) + assertEquals(1, track.size) + assertEquals(1, track.chartNote(0)) + } + + @Test + fun theFirstNoteStillGoingIsFoundFromAnyTime() { + val track = track(Note.Tap(beat(1), 0), Note.Tap(beat(2), 0), Note.Tap(beat(3), 0)) + assertEquals(0, track.firstEndingFrom(-5000.0)) + assertEquals(0, track.firstEndingFrom(500.0)) + assertEquals(1, track.firstEndingFrom(500.5)) + assertEquals(2, track.firstEndingFrom(1500.0)) + assertEquals(3, track.firstEndingFrom(1500.5)) + } + + @Test + fun aLongHoldKeepsTheSearchFromSkippingIt() { + val track = track(Note.Hold(beat(1), beat(100), 0), Note.Tap(beat(2), 1), Note.Tap(beat(3), 1)) + assertEquals(0, track.firstEndingFrom(2000.0)) + assertEquals(0, track.firstEndingFrom(50000.0)) + assertEquals(3, track.firstEndingFrom(50000.5)) + } + + @Test + fun anEmptyTrackHasNothingToFind() { + assertEquals(0, track().firstEndingFrom(0.0)) + } + + @Test + fun aBpmChangeMovesTheNotesAfterIt() { + val chart = DifficultyChart( + 1, Difficulty.BASIC, 1, 4, 0.0, + listOf(BpmChange(beat(0), 120.0), BpmChange(beat(2), 60.0)), + listOf(MeterChange(beat(0), 4, 4)), + listOf(Note.Hold(beat(1), beat(3), 0)), + ) + val track = GroundTrack(chart) + assertEquals(500.0, track.startMs(0), tolerance) + assertEquals(2000.0, track.endMs(0), tolerance) + } + + @Test + fun aPositiveVisualOffsetDrawsANoteLater() { + val drawMs = GroundTrack.drawTimeMs(1000.0, 100.0) + assertEquals(900.0, drawMs, tolerance) + assertEquals(4.0, GroundTrack.distance(1000.0, drawMs, 40.0), tolerance) + } + + @Test + fun aNoteIsOnTheLineExactlyAtItsTime() { + assertEquals(0.0, GroundTrack.distance(1000.0, 1000.0, 40.0), tolerance) + } + + @Test + fun aNoteAheadIsFurtherAwayTheFasterTheSpeed() { + assertEquals(20.0, GroundTrack.distance(1500.0, 1000.0, 40.0), tolerance) + assertEquals(40.0, GroundTrack.distance(1500.0, 1000.0, 80.0), tolerance) + } + + @Test + fun aNotePastItsTimeIsOnThePlayersSideOfTheLine() { + assertEquals(-4.0, GroundTrack.distance(1000.0, 1100.0, 40.0), tolerance) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/SkyTrackTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/SkyTrackTest.kt new file mode 100644 index 0000000..e0826c5 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/SkyTrackTest.kt @@ -0,0 +1,240 @@ +package net.trilleo.hexium.core.chart + +import java.io.File +import java.lang.management.ManagementFactory +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.JudgementConfig + +class SkyTrackTest { + private val tolerance = 1e-9 + + private fun beat(whole: Int, numerator: Int = 0, denominator: Int = 1) = Beat(whole, numerator, denominator) + + private fun chart(vararg notes: Note, offsetMs: Double = 0.0, bpm: List = listOf(BpmChange(beat(0), 120.0))) = + DifficultyChart(1, Difficulty.EXPERT, 1, 4, offsetMs, bpm, listOf(MeterChange(beat(0), 4, 4)), notes.toList()) + + /** At 120 BPM a beat is 500 ms. */ + private fun track(vararg notes: Note, offsetMs: Double = 0.0) = SkyTrack(chart(*notes, offsetMs = offsetMs)) + + private fun slide(button: SkyButton, radius: Double, vararg points: SlidePoint) = Note.Slide(button, radius, points.toList()) + + private fun point(t: Beat, x: Double, y: Double, ease: Ease = Ease.LINEAR) = SlidePoint(t, x, y, ease) + + @Test + fun aSkyTapSitsOnItsSpotAtItsTime() { + val track = track(Note.SkyTap(beat(2), 0.25, 0.75, SkyButton.R, 1.5), offsetMs = 100.0) + assertEquals(1, track.size) + assertEquals(SkyTrack.Kind.TAP, track.kind(0)) + assertEquals(SkyButton.R, track.button(0)) + assertEquals(1100.0, track.startMs(0), tolerance) + assertEquals(1100.0, track.endMs(0), tolerance) + assertEquals(0.25, track.x(0, 0.0), tolerance) + assertEquals(0.75, track.y(0, 5000.0), tolerance) + } + + /** The judge's hit circle, so what's drawn is what counts. */ + @Test + fun aSkyTapsRadiusIsTheBaseHitRadiusTimesItsSize() { + val track = track(Note.SkyTap(beat(2), 0.5, 0.5, SkyButton.L, 1.5)) + assertEquals(JudgementConfig.DEFAULT.baseHitRadius * 1.5, track.radius(0), tolerance) + } + + @Test + fun theRadiusFollowsTheConfigItIsGiven() { + val track = SkyTrack(chart(Note.Flick(beat(1), 0.5, 0.5, 2.0)), JudgementConfig(baseHitRadius = 0.1)) + assertEquals(0.2, track.radius(0), tolerance) + } + + @Test + fun aFlickNeedsNoButton() { + val track = track(Note.Flick(beat(4), 0.3, 0.4, 1.0)) + assertEquals(SkyTrack.Kind.FLICK, track.kind(0)) + assertNull(track.button(0)) + assertEquals(2000.0, track.startMs(0), tolerance) + assertEquals(2000.0, track.endMs(0), tolerance) + assertEquals(0.3, track.x(0, 2000.0), tolerance) + assertEquals(0.4, track.y(0, 2000.0), tolerance) + } + + @Test + fun aSlideRunsFromItsFirstPointToItsLastWithItsOwnRadius() { + val track = track(slide(SkyButton.L, 0.06, point(beat(2), 0.2, 0.5), point(beat(4), 0.6, 0.9), point(beat(6), 0.6, 0.1))) + assertEquals(SkyTrack.Kind.SLIDE, track.kind(0)) + assertEquals(SkyButton.L, track.button(0)) + assertEquals(1000.0, track.startMs(0), tolerance) + assertEquals(3000.0, track.endMs(0), tolerance) + assertEquals(0.06, track.radius(0), tolerance) + } + + @Test + fun aSlideIsWhereItsPathIsAtThatTime() { + val track = track(slide(SkyButton.L, 0.06, point(beat(2), 0.2, 0.5), point(beat(4), 0.6, 0.9, Ease.IN), point(beat(6), 0.6, 0.1))) + // Halfway along a linear segment. + assertEquals(0.4, track.x(0, 1500.0), tolerance) + assertEquals(0.7, track.y(0, 1500.0), tolerance) + // Halfway along an `in` segment has gone a quarter of the way. + assertEquals(0.7, track.y(0, 2500.0), tolerance) + } + + @Test + fun aSlideStaysOnItsEndsBeforeAndAfterItsPath() { + val track = track(slide(SkyButton.R, 0.06, point(beat(2), 0.2, 0.5), point(beat(4), 0.6, 0.9))) + assertEquals(0.2, track.x(0, -5000.0), tolerance) + assertEquals(0.5, track.y(0, 999.0), tolerance) + assertEquals(0.6, track.x(0, 2001.0), tolerance) + assertEquals(0.9, track.y(0, 99999.0), tolerance) + } + + /** Eases are measured in beats, so a BPM change part way along doesn't bend the path. */ + @Test + fun aSlideAcrossABpmChangeMovesEvenlyInBeats() { + val bpm = listOf(BpmChange(beat(0), 120.0), BpmChange(beat(3), 60.0)) + val track = SkyTrack(chart(slide(SkyButton.L, 0.06, point(beat(2), 0.0, 0.0), point(beat(4), 1.0, 1.0)), bpm = bpm)) + // Beat 3 is at 1500 ms, the middle of the path in beats. + assertEquals(0.5, track.x(0, 1500.0), tolerance) + // Beat 3.5 is 500 ms after it at 60 BPM. + assertEquals(0.75, track.x(0, 2000.0), tolerance) + } + + @Test + fun notesAreInTimeOrderAndRememberTheirPlaceInTheChart() { + val track = track( + Note.Flick(beat(3), 0.5, 0.5, 1.0), + Note.Tap(beat(1), 0), + Note.SkyTap(beat(1), 0.5, 0.5, SkyButton.L, 1.0), + slide(SkyButton.R, 0.06, point(beat(2), 0.5, 0.5), point(beat(5), 0.5, 0.5)), + Note.Hold(beat(2), beat(3), 1), + ) + assertEquals(3, track.size) + assertEquals(listOf(500.0, 1000.0, 1500.0), List(track.size) { track.startMs(it) }) + assertEquals(listOf(2, 3, 0), List(track.size) { track.chartNote(it) }) + assertEquals(listOf(SkyTrack.Kind.TAP, SkyTrack.Kind.SLIDE, SkyTrack.Kind.FLICK), List(track.size) { track.kind(it) }) + } + + @Test + fun notesAtTheSameTimeKeepTheChartsOrder() { + val track = track(Note.SkyTap(beat(1), 0.2, 0.5, SkyButton.L, 1.0), Note.SkyTap(beat(1), 0.8, 0.5, SkyButton.R, 1.0)) + assertEquals(listOf(0, 1), List(track.size) { track.chartNote(it) }) + } + + @Test + fun theFirstNoteStillGoingIsFoundFromAnyTime() { + val track = track( + Note.SkyTap(beat(1), 0.5, 0.5, SkyButton.L, 1.0), + Note.SkyTap(beat(2), 0.5, 0.5, SkyButton.L, 1.0), + Note.Flick(beat(3), 0.5, 0.5, 1.0), + ) + assertEquals(0, track.firstEndingFrom(-5000.0)) + assertEquals(0, track.firstEndingFrom(500.0)) + assertEquals(1, track.firstEndingFrom(500.5)) + assertEquals(2, track.firstEndingFrom(1500.0)) + assertEquals(3, track.firstEndingFrom(1500.5)) + } + + @Test + fun aLongSlideKeepsTheSearchFromSkippingIt() { + val track = track( + slide(SkyButton.L, 0.06, point(beat(1), 0.5, 0.5), point(beat(100), 0.5, 0.5)), + Note.SkyTap(beat(2), 0.5, 0.5, SkyButton.L, 1.0), + Note.SkyTap(beat(3), 0.5, 0.5, SkyButton.L, 1.0), + ) + assertEquals(0, track.firstEndingFrom(2000.0)) + assertEquals(0, track.firstEndingFrom(50000.0)) + assertEquals(3, track.firstEndingFrom(50000.5)) + } + + @Test + fun theAspectComesFromTheConfig() { + assertEquals(JudgementConfig.DEFAULT.screenAspect, track().screenAspect, tolerance) + assertEquals(3.0, SkyTrack(chart(), JudgementConfig(screenAspect = 3.0)).screenAspect, tolerance) + } + + /** What's drawn must be what's judged: every time, spot, radius and path matches the judge's own chart. */ + @Test + fun everyNoteMatchesWhatTheJudgeUses() { + val files = listOf(File("../docs/examples/expert.json"), File("../mod/src/client/resources/hexium_packs/test-pattern/expert.json")) + for (file in files) { + val chart = assertNotNull(ChartParser.parseDifficulty(file.readText()).value, file.path) + val judge = JudgeChart.compile(chart) + val sky = SkyTrack(chart) + var slide = 0 + var checked = 0 + for (i in 0 until sky.size) { + val note = sky.chartNote(i) + when (sky.kind(i)) { + SkyTrack.Kind.TAP -> { + val b = sky.button(i)!!.ordinal + val k = judge.skyObject[b].indexOfFirst { judge.objectNote[it] == note } + assertTrue(k >= 0, "note $note in ${file.path}") + assertEquals(judge.skyMs[b][k], sky.startMs(i), tolerance) + assertEquals(judge.skyX[b][k], sky.x(i, 0.0), tolerance) + assertEquals(judge.skyY[b][k], sky.y(i, 0.0), tolerance) + assertEquals(judge.skyRadius[b][k], sky.radius(i), tolerance) + } + SkyTrack.Kind.FLICK -> { + val k = judge.flickObject.indexOfFirst { judge.objectNote[it] == note } + assertTrue(k >= 0, "note $note in ${file.path}") + assertEquals(judge.flickMs[k], sky.startMs(i), tolerance) + assertEquals(judge.flickX[k], sky.x(i, 0.0), tolerance) + assertEquals(judge.flickY[k], sky.y(i, 0.0), tolerance) + assertEquals(judge.flickRadius[k], sky.radius(i), tolerance) + } + SkyTrack.Kind.SLIDE -> { + // Both keep slides in start order. + assertEquals(judge.slideStartMs[slide], sky.startMs(i), tolerance) + assertEquals(judge.slideEndMs[slide], sky.endMs(i), tolerance) + assertEquals(judge.slideRadius[slide], sky.radius(i), tolerance) + assertEquals(judge.slideButton[slide], sky.button(i)!!.ordinal) + for (step in 0..8) { + val ms = sky.startMs(i) + (sky.endMs(i) - sky.startMs(i)) * step / 8.0 + val beat = judge.timing.msToBeat(ms) + assertEquals(judge.slidePath[slide].x(beat), sky.x(i, ms), tolerance) + assertEquals(judge.slidePath[slide].y(beat), sky.y(i, ms), tolerance) + } + slide++ + } + } + checked++ + } + assertEquals(judge.slideCount, slide, file.path) + assertTrue(checked >= 7, file.path) + } + } + + @Test + fun aGroundChartHasNothingInTheSky() { + val track = track(Note.Tap(beat(1), 0), Note.Hold(beat(2), beat(3), 1)) + assertEquals(0, track.size) + assertEquals(0, track.firstEndingFrom(0.0)) + } + + @Test + fun lookupsDoNotAllocate() { + val track = track( + Note.SkyTap(beat(1), 0.5, 0.5, SkyButton.L, 1.0), + slide(SkyButton.R, 0.06, point(beat(2), 0.2, 0.5), point(beat(4), 0.6, 0.9, Ease.IN_OUT), point(beat(6), 0.6, 0.1)), + Note.Flick(beat(7), 0.5, 0.5, 1.0), + ) + val threads = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + val thread = Thread.currentThread().threadId() + var sum = 0.0 + val before = threads.getThreadAllocatedBytes(thread) + for (i in 0 until 100_000) { + val ms = (i % 4000).toDouble() + var n = track.firstEndingFrom(ms) + while (n < track.size) { + sum += track.x(n, ms) + track.y(n, ms) + track.radius(n) + track.startMs(n) + track.endMs(n) + if (track.button(n) == SkyButton.L) sum += track.chartNote(n) + n++ + } + } + val allocated = threads.getThreadAllocatedBytes(thread) - before + assertTrue(sum.isFinite()) + assertTrue(allocated < 16 * 1024, "allocated $allocated bytes") + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/SlidePathTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/SlidePathTest.kt new file mode 100644 index 0000000..fe8f866 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/SlidePathTest.kt @@ -0,0 +1,66 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals + +class SlidePathTest { + private val tolerance = 1e-9 + + @Test + fun easesFollowTheSpec() { + for (t in listOf(0.0, 0.25, 0.5, 0.75, 1.0)) { + assertEquals(t, Ease.LINEAR.progress(t), tolerance) + assertEquals(t * t, Ease.IN.progress(t), tolerance) + assertEquals(1 - (1 - t) * (1 - t), Ease.OUT.progress(t), tolerance) + assertEquals(3 * t * t - 2 * t * t * t, Ease.IN_OUT.progress(t), tolerance) + } + } + + private fun beat(whole: Int, num: Int = 0, den: Int = 1) = Beat(whole, num, den) + + private val path = SlidePath( + listOf( + SlidePoint(beat(1), 0.2, 0.4, Ease.LINEAR), + SlidePoint(beat(2), 0.6, 0.8, Ease.IN), + SlidePoint(beat(4), 1.0, 0.0, Ease.OUT), + ), + ) + + @Test + fun positionFollowsEachSegmentsEase() { + assertEquals(0.4, path.x(1.5), tolerance) + assertEquals(0.6, path.y(1.5), tolerance) + assertEquals(0.6 + 0.4 * 0.25, path.x(3.0), tolerance) + assertEquals(0.8 - 0.8 * 0.25, path.y(3.0), tolerance) + } + + @Test + fun pointsAreExact() { + assertEquals(0.2, path.x(1.0), tolerance) + assertEquals(0.6, path.x(2.0), tolerance) + assertEquals(1.0, path.x(4.0), tolerance) + } + + @Test + fun positionStopsAtBothEnds() { + assertEquals(0.2, path.x(0.0), tolerance) + assertEquals(0.4, path.y(-5.0), tolerance) + assertEquals(1.0, path.x(9.0), tolerance) + assertEquals(0.0, path.y(9.0), tolerance) + } + + @Test + fun lastPointsEaseIsIgnored() { + val a = SlidePath(listOf(SlidePoint(beat(0), 0.0, 0.0, Ease.LINEAR), SlidePoint(beat(1), 1.0, 1.0, Ease.IN))) + val b = SlidePath(listOf(SlidePoint(beat(0), 0.0, 0.0, Ease.LINEAR), SlidePoint(beat(1), 1.0, 1.0, Ease.OUT))) + assertEquals(a.x(0.5), b.x(0.5), tolerance) + } + + @Test + fun progressIsInBeatsSoABpmChangeDoesNotBendThePath() { + val straight = SlidePath(listOf(SlidePoint(beat(0), 0.0, 0.0, Ease.LINEAR), SlidePoint(beat(2), 1.0, 1.0, Ease.LINEAR))) + val timing = TimingMap(0.0, listOf(BpmChange(beat(0), 60.0), BpmChange(beat(1), 120.0))) + assertEquals(0.5, straight.x(timing.msToBeat(1000.0)), tolerance) + assertEquals(0.75, straight.x(timing.msToBeat(1250.0)), tolerance) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/TestPackTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/TestPackTest.kt new file mode 100644 index 0000000..869d6be --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/TestPackTest.kt @@ -0,0 +1,168 @@ +package net.trilleo.hexium.core.chart + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** The pack bundled in the mod, used to play and test before there's song select. */ +class TestPackTest { + private val pack = File("../mod/src/client/resources/hexium_packs/test-pattern") + + private fun chart(name: String): DifficultyChart { + val result = ChartParser.parseDifficulty(File(pack, "$name.json").readText()) + assertEquals(emptyList(), result.issues, name) + return assertNotNull(result.value, name) + } + + private fun meta(): ChartMeta { + val result = ChartParser.parseMeta(File(pack, "meta.json").readText()) + assertEquals(emptyList(), result.issues) + return assertNotNull(result.value) + } + + @Test + fun packPassesTheValidatorWithoutWarnings() { + val pkg = ChartPackage(meta(), listOf(chart("basic"), chart("advanced"), chart("expert"))) + assertEquals(emptyList(), ChartValidator.validatePackage(pkg, audioDurationMs = AUDIO_MS, packageSizeBytes = packBytes())) + } + + @Test + fun theSongIsOurOwn() { + assertEquals(LicenseType.ORIGINAL, meta().license.type) + assertTrue(File(pack, "audio.ogg").length() > 0) + } + + /** Golden replays of real plays use this chart, and a replay is tied to its file's exact bytes. */ + @Test + fun basicIsTheExampleChartByteForByte() { + assertContentEquals(File("../docs/examples/basic.json").readBytes(), File(pack, "basic.json").readBytes()) + } + + /** The milestone's gate is no drift over a 3-minute song. */ + @Test + fun advancedLastsThreeMinutes() { + val chart = chart("advanced") + val timing = TimingMap(chart.offsetMs, chart.bpm) + val last = chart.notes.maxOf { note -> + when (note) { + is Note.Tap -> note.t + is Note.Hold -> note.end + else -> error("Sky note in the test pack") + }.let(timing::beatToMs) + } + assertTrue(last >= 180_000.0, "ends at $last ms") + } + + @Test + fun theChartsAreWrittenInTheWritersLayout() { + for (name in listOf("advanced", "expert")) assertEquals(File(pack, "$name.json").readText(), ChartWriter.writeDifficulty(chart(name)), name) + } + + /** Expert is the Milestone 3 readability chart, so it needs every sky note, on both buttons. */ + @Test + fun expertHasEverySkyNoteOnBothButtons() { + val notes = chart("expert").notes + for (button in SkyButton.entries) { + assertTrue(notes.any { it is Note.SkyTap && it.button == button }, "$button sky tap") + assertTrue(notes.any { it is Note.Slide && it.button == button }, "$button slide") + } + assertTrue(notes.any { it is Note.Flick }, "flick") + } + + /** The gate asks whether the track stays readable while aiming at the corners. */ + @Test + fun expertReachesEveryCornerWhileGroundNotesAreComing() { + val chart = chart("expert") + val sky = SkyTrack(chart) + val ground = GroundTrack(chart) + for ((cornerX, cornerY) in listOf(0.1 to 0.9, 0.9 to 0.9, 0.1 to 0.1, 0.9 to 0.1)) { + assertTrue((0 until sky.size).any { sky.x(it, sky.startMs(it)) == cornerX && sky.y(it, sky.startMs(it)) == cornerY }, "corner $cornerX, $cornerY") + } + // Each top corner within a beat of a ground note. + for (cornerX in listOf(0.1, 0.9)) { + assertTrue( + (0 until sky.size).any { i -> + val ms = sky.startMs(i) + sky.x(i, ms) == cornerX && sky.y(i, ms) == 0.9 && (0 until ground.size).any { Math.abs(ground.startMs(it) - ms) <= 500.0 } + }, + "top corner at x $cornerX with a ground note near it", + ) + } + } + + /** Every hit area fits on the screen, so nothing asks the crosshair to leave it. */ + @Test + fun expertsHitAreasStayOnTheScreen() { + val sky = SkyTrack(chart("expert")) + for (i in 0 until sky.size) { + val halfWidth = sky.radius(i) / sky.screenAspect + var step = 0 + while (step <= 16) { + val ms = sky.startMs(i) + (sky.endMs(i) - sky.startMs(i)) * step / 16.0 + val x = sky.x(i, ms) + val y = sky.y(i, ms) + assertTrue(x - halfWidth >= 0.0 && x + halfWidth <= 1.0 && y - sky.radius(i) >= 0.0 && y + sky.radius(i) <= 1.0, "note ${sky.chartNote(i)} at $x, $y") + step++ + } + } + } + + /** + * One crosshair can't be in two places: sky notes at the same moment share a spot, and a tap or + * flick while a slide is going sits inside the slide's hit area. + */ + @Test + fun expertsSkyNotesAtTheSameTimeShareASpot() { + val sky = SkyTrack(chart("expert")) + for (i in 0 until sky.size) { + if (sky.kind(i) == SkyTrack.Kind.SLIDE) continue + val ms = sky.startMs(i) + for (j in 0 until sky.size) { + if (sky.kind(j) != SkyTrack.Kind.SLIDE || ms < sky.startMs(j) || ms > sky.endMs(j)) continue + val dx = (sky.x(i, ms) - sky.x(j, ms)) * sky.screenAspect + val dy = sky.y(i, ms) - sky.y(j, ms) + assertTrue(dx * dx + dy * dy <= sky.radius(j) * sky.radius(j), "note ${sky.chartNote(i)} off slide ${sky.chartNote(j)}") + } + } + for (i in 0 until sky.size) { + for (j in i + 1 until sky.size) { + if (sky.startMs(j) != sky.startMs(i)) continue + assertEquals(sky.x(i, sky.startMs(i)), sky.x(j, sky.startMs(j)), "notes ${sky.chartNote(i)} and ${sky.chartNote(j)}") + assertEquals(sky.y(i, sky.startMs(i)), sky.y(j, sky.startMs(j)), "notes ${sky.chartNote(i)} and ${sky.chartNote(j)}") + } + } + } + + @Test + fun groundOnlyTellsChartsWithSkyNotesApart() { + assertTrue(chart("basic").isGroundOnly) + assertTrue(chart("advanced").isGroundOnly) + assertFalse(chart("expert").isGroundOnly) + val sky = ChartParser.parseDifficulty(File("../docs/examples/expert.json").readText()).value + assertFalse(assertNotNull(sky).isGroundOnly) + } + + @Test + fun anySkyNoteMakesAChartNotGroundOnly() { + val empty = chart("basic").copy(notes = emptyList()) + assertTrue(empty.isGroundOnly) + val beat = Beat(4, 0, 1) + val point = SlidePoint(beat, 0.5, 0.5, Ease.LINEAR) + val skyNotes = listOf( + Note.SkyTap(beat, 0.5, 0.5, SkyButton.L, 1.0), + Note.Slide(SkyButton.L, 0.06, listOf(point, point)), + Note.Flick(beat, 0.5, 0.5, 1.0), + ) + for (note in skyNotes) assertFalse(empty.copy(notes = listOf(note)).isGroundOnly, note.toString()) + } + + private fun packBytes(): Long = pack.listFiles().orEmpty().sumOf { it.length() } + + private companion object { + const val AUDIO_MS = 185_000.0 + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/chart/TimingMapTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/chart/TimingMapTest.kt new file mode 100644 index 0000000..72fe912 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/chart/TimingMapTest.kt @@ -0,0 +1,135 @@ +package net.trilleo.hexium.core.chart + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class TimingMapTest { + private val tolerance = 1e-9 + + private fun bpm(whole: Int, bpm: Double) = BpmChange(Beat(whole, 0, 1), bpm) + + @Test + fun beatZeroFallsOnTheOffset() { + assertEquals(120.0, TimingMap(120.0, listOf(bpm(0, 174.0))).beatToMs(Beat(0, 0, 1)), tolerance) + } + + @Test + fun negativeOffsetPutsBeatZeroBeforeTheAudio() { + assertEquals(-250.0, TimingMap(-250.0, listOf(bpm(0, 120.0))).beatToMs(Beat(0, 0, 1)), tolerance) + assertEquals(250.0, TimingMap(-250.0, listOf(bpm(0, 120.0))).beatToMs(Beat(1, 0, 1)), tolerance) + } + + @Test + fun constantBpm() { + val map = TimingMap(0.0, listOf(bpm(0, 120.0))) + assertEquals(500.0, map.beatToMs(Beat(1, 0, 1)), tolerance) + assertEquals(6375.0, map.beatToMs(Beat(12, 3, 4)), tolerance) + } + + @Test + fun thirdsOfABeatDoNotDrift() { + val map = TimingMap(0.0, listOf(bpm(0, 120.0))) + assertEquals(1000.0 * 1000.0 / 2.0 + 500.0 / 3.0, map.beatToMs(Beat(1000, 1, 3)), tolerance) + } + + @Test + fun bpmChangeUsesTheNewTempoFromItsBeat() { + val map = TimingMap(120.0, listOf(bpm(0, 174.0), bpm(64, 87.0))) + val atChange = 120.0 + 64 * 60000.0 / 174.0 + assertEquals(atChange - 60000.0 / 174.0, map.beatToMs(Beat(63, 0, 1)), tolerance) + assertEquals(atChange, map.beatToMs(Beat(64, 0, 1)), tolerance) + assertEquals(atChange + 60000.0 / 87.0, map.beatToMs(Beat(65, 0, 1)), tolerance) + } + + @Test + fun bpmChangeOnAFraction() { + val map = TimingMap(0.0, listOf(bpm(0, 120.0), BpmChange(Beat(2, 1, 2), 60.0))) + assertEquals(1250.0, map.beatToMs(Beat(2, 1, 2)), tolerance) + assertEquals(1750.0, map.beatToMs(Beat(3, 0, 1)), tolerance) + } + + @Test + fun manyChangesAddUp() { + val map = TimingMap(0.0, listOf(bpm(0, 120.0), bpm(1, 60.0), bpm(2, 240.0), bpm(3, 120.0))) + assertEquals(500.0, map.beatToMs(Beat(1, 0, 1)), tolerance) + assertEquals(1500.0, map.beatToMs(Beat(2, 0, 1)), tolerance) + assertEquals(1750.0, map.beatToMs(Beat(3, 0, 1)), tolerance) + assertEquals(2250.0, map.beatToMs(Beat(4, 0, 1)), tolerance) + } + + @Test + fun lookupsFindTheRightSegmentInALongList() { + val changes = List(1001) { bpm(it, 120.0) } + val map = TimingMap(0.0, changes) + for (whole in listOf(0, 1, 2, 499, 500, 501, 999, 1000, 1001, 5000)) { + assertEquals(whole * 500.0, map.beatToMs(Beat(whole, 0, 1)), tolerance) + assertEquals(whole * 500.0 + 250.0, map.beatToMs(Beat(whole, 1, 2)), tolerance) + } + } + + @Test + fun beatsBeforeZeroContinueTheFirstTempo() { + val map = TimingMap(1000.0, listOf(bpm(0, 120.0), bpm(4, 60.0))) + assertEquals(500.0, map.beatToMs(-1.0), tolerance) + } + + @Test + fun msToBeatUndoesBeatToMs() { + val map = TimingMap(120.0, listOf(bpm(0, 174.0), bpm(64, 87.0), BpmChange(Beat(70, 1, 3), 200.0))) + for (beat in listOf(0.0, 0.5, 63.9, 64.0, 65.25, 70.0, 70.5, 500.0, -2.0)) { + assertEquals(beat, map.msToBeat(map.beatToMs(beat)), 1e-9) + } + } + + @Test + fun doubleBeatMatchesExactBeat() { + val map = TimingMap(120.0, listOf(bpm(0, 174.0), bpm(64, 87.0))) + assertEquals(map.beatToMs(Beat(65, 1, 2)), map.beatToMs(65.5), tolerance) + } + + @Test + fun refusesBpmDataTheValidatorWouldReject() { + assertFailsWith { TimingMap(0.0, emptyList()) } + assertFailsWith { TimingMap(0.0, listOf(bpm(1, 120.0))) } + assertFailsWith { TimingMap(0.0, listOf(bpm(0, 0.0))) } + assertFailsWith { TimingMap(0.0, listOf(bpm(0, 120.0), bpm(0, 90.0))) } + assertFailsWith { TimingMap(0.0, listOf(BpmChange(Beat(0, 0, 0), 120.0))) } + assertFailsWith { TimingMap(0.0, listOf(bpm(0, 1e-320))) } + assertFailsWith { TimingMap(0.0, listOf(bpm(0, Double.POSITIVE_INFINITY))) } + assertFailsWith { TimingMap(Double.NaN, listOf(bpm(0, 120.0))) } + } +} + +class LastNoteEndTest { + private val beat = BpmChange(Beat(0, 0, 1), 120.0) + + private fun chart(vararg notes: Note) = DifficultyChart(1, Difficulty.BASIC, 1, 4, 100.0, listOf(beat), emptyList(), notes.toList()) + + @Test + fun aChartWithNoNotesEndsAtItsStart() { + assertEquals(0.0, chart().lastNoteEndMs(), 1e-9) + } + + @Test + fun theLatestEndNeedNotBeTheLastNoteListed() { + val chart = chart(Note.Hold(Beat(1, 0, 1), Beat(9, 0, 1), 0), Note.Tap(Beat(2, 0, 1), 1)) + assertEquals(4600.0, chart.lastNoteEndMs(), 1e-9) + } + + @Test + fun notesBeforeTheSongStartEndAtZero() { + val chart = chart(Note.Tap(Beat(1, 0, 1), 0)).copy(offsetMs = -2000.0) + assertEquals(0.0, chart.lastNoteEndMs(), 1e-9) + } + + @Test + fun itIsTheLatestEndOfAnyNoteType() { + val point = { whole: Int -> SlidePoint(Beat(whole, 0, 1), 0.5, 0.5, Ease.LINEAR) } + assertEquals(1100.0, chart(Note.Tap(Beat(2, 0, 1), 0)).lastNoteEndMs(), 1e-9) + assertEquals(2100.0, chart(Note.Tap(Beat(1, 0, 1), 0), Note.Hold(Beat(1, 0, 1), Beat(4, 0, 1), 1)).lastNoteEndMs(), 1e-9) + assertEquals(1600.0, chart(Note.SkyTap(Beat(3, 0, 1), 0.5, 0.5, SkyButton.L, 1.0)).lastNoteEndMs(), 1e-9) + assertEquals(2600.0, chart(Note.Flick(Beat(5, 0, 1), 0.5, 0.5, 1.0)).lastNoteEndMs(), 1e-9) + assertEquals(3100.0, chart(Note.Slide(SkyButton.L, 0.06, listOf(point(1), point(6)))).lastNoteEndMs(), 1e-9) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/clock/SongClockTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/clock/SongClockTest.kt new file mode 100644 index 0000000..4e4826b --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/clock/SongClockTest.kt @@ -0,0 +1,238 @@ +package net.trilleo.hexium.core.clock + +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class SongClockTest { + private val frameNs = 4_000_000L + + private fun ms(ns: Long) = ns / 1_000_000.0 + + @Test + fun runsOnWallTimeBetweenAudioUpdates() { + val clock = SongClock() + clock.start(1000.0, 5_000_000_000L) + assertEquals(1000.0, clock.nowMs(5_000_000_000L), 1e-6) + assertEquals(1250.0, clock.nowMs(5_250_000_000L), 1e-6) + } + + @Test + fun doesNotMoveWhilePaused() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.pause(1_000_000_000L) + assertEquals(1000.0, clock.nowMs(2_000_000_000L), 1e-6) + clock.observe(500.0, 3_000_000_000L) + assertEquals(1000.0, clock.nowMs(3_000_000_000L), 1e-6) + assertEquals(false, clock.running) + } + + @Test + fun stepsInTheAudioPositionDontShowInTheClock() { + val clock = SongClock() + clock.start(0.0, 0L) + var wall = 0L + var last = 0.0 + var biggestStep = 0.0 + repeat(60_000 / 4) { + wall += frameNs + // The raw position only moves every 20 ms. + clock.observe(Math.floor(ms(wall) / 20.0) * 20.0, wall) + val now = clock.nowMs(wall) + biggestStep = maxOf(biggestStep, now - last) + last = now + } + assertTrue(biggestStep < 4.5, "biggest step $biggestStep ms for a 4 ms frame") + assertTrue(abs(last - ms(wall)) < 25.0, "clock $last at ${ms(wall)}") + } + + /** A sound card whose clock is 0.1% fast must not pull the notes away from the music. */ + @Test + fun followsAudioThatRunsAtADifferentRateOverThreeMinutes() { + val clock = SongClock() + clock.start(0.0, 0L) + var wall = 0L + repeat(180_000 / 4) { + wall += frameNs + clock.observe(ms(wall) * 1.001, wall) + } + assertEquals(0, clock.resyncCount) + assertEquals(ms(wall) * 1.001, clock.nowMs(wall), 2.0) + } + + @Test + fun theResultDoesNotDependOnTheFrameRate() { + fun errorAt(frame: Long): Double { + val clock = SongClock() + clock.start(0.0, 0L) + var wall = 0L + // One pull time in, while the error is still shrinking, so a pull per frame would show. + while (wall < 1_000_000_000L) { + wall += frame + clock.observe(ms(wall) + 30.0, wall) + } + return ms(wall) + 30.0 - clock.nowMs(wall) + } + assertEquals(errorAt(4_000_000L), errorAt(16_000_000L), 0.5) + assertEquals(11.0, errorAt(4_000_000L), 1.0) + } + + @Test + fun jumpsForwardWhenAudioIsFarAhead() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.observe(1500.0, 1_000_000_000L) + assertEquals(1500.0, clock.nowMs(1_000_000_000L), 1e-6) + assertEquals(1, clock.resyncCount) + } + + @Test + fun neverRunsBackwardsEvenWhenAudioFallsFarBehind() { + val clock = SongClock() + clock.start(0.0, 0L) + assertEquals(1000.0, clock.nowMs(1_000_000_000L), 1e-6) + clock.observe(500.0, 1_000_000_000L) + assertEquals(1, clock.resyncCount) + assertEquals(1000.0, clock.nowMs(1_000_000_000L), 1e-6) + // Holds still until the music catches up, then moves on. + assertEquals(1000.0, clock.nowMs(1_200_000_000L), 1e-6) + assertEquals(1100.0, clock.nowMs(1_600_000_000L), 1e-6) + } + + @Test + fun neverRunsBackwardsWithNoisyAudio() { + val clock = SongClock() + clock.start(0.0, 0L) + val random = java.util.Random(42) + var wall = 0L + var last = Double.NEGATIVE_INFINITY + repeat(50_000) { + wall += 1_000_000L + random.nextInt(8_000_000) + clock.observe(ms(wall) + (random.nextDouble() - 0.5) * 80.0, wall) + // Not nowMs: its floor would hide a pull that reversed time. + val now = clock.mapMs(wall) + assertTrue(now >= last, "went from $last to $now") + last = now + } + } + + /** Input stamped before this frame's time keeps its real time. The judge decides what to do with it. */ + @Test + fun mapsOlderTimestampsWithoutHoldingThemToNow() { + val clock = SongClock() + clock.start(0.0, 0L) + assertEquals(1000.0, clock.nowMs(1_000_000_000L), 1e-6) + assertEquals(990.0, clock.mapMs(990_000_000L), 1e-6) + } + + @Test + fun aSeekMayGoBackwards() { + val clock = SongClock() + clock.start(0.0, 0L) + assertEquals(5000.0, clock.nowMs(5_000_000_000L), 1e-6) + clock.start(2000.0, 5_000_000_000L) + assertEquals(2000.0, clock.nowMs(5_000_000_000L), 1e-6) + assertEquals(0, clock.resyncCount) + } + + @Test + fun reportsDrift() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.observe(1010.0, 1_000_000_000L) + assertEquals(10.0, clock.driftMs, 1e-6) + clock.observe(1990.0, 2_000_000_000L) + assertTrue(clock.driftMs < 0.0) + assertTrue(clock.maxDriftMs >= 10.0) + } + + @Test + fun ignoresAudioPositionsThatArentNumbers() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.observe(Double.NaN, 1_000_000_000L) + assertEquals(1000.0, clock.nowMs(1_000_000_000L), 1e-6) + assertEquals(0, clock.resyncCount) + } + + @Test + fun resumesFromWherePauseLeftIt() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.pause(1_000_000_000L) + clock.start(clock.nowMs(5_000_000_000L), 5_000_000_000L) + assertEquals(1500.0, clock.nowMs(5_500_000_000L), 1e-6) + assertEquals(0, clock.resyncCount) + } + + @Test + fun seekingWhilePausedStaysPausedAtTheNewTime() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.pause(5_000_000_000L) + clock.seek(2000.0, 6_000_000_000L) + assertEquals(false, clock.running) + assertEquals(2000.0, clock.nowMs(7_000_000_000L), 1e-6) + clock.start(clock.nowMs(8_000_000_000L), 8_000_000_000L) + assertEquals(2500.0, clock.nowMs(8_500_000_000L), 1e-6) + } + + @Test + fun seekingWhileRunningKeepsRunningAndMayGoBackwards() { + val clock = SongClock() + clock.start(0.0, 0L) + assertEquals(5000.0, clock.nowMs(5_000_000_000L), 1e-6) + clock.seek(2000.0, 5_000_000_000L) + assertEquals(true, clock.running) + assertEquals(2500.0, clock.nowMs(5_500_000_000L), 1e-6) + assertEquals(0, clock.resyncCount) + } + + @Test + fun aLongGapPullsNoFurtherThanTheWholeError() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.observe(5050.0, 5_000_000_000L) + assertEquals(5050.0, clock.mapMs(5_000_000_000L), 1e-6) + } + + @Test + fun aValidPositionWorksAfterOneThatIsNot() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.observe(Double.NaN, 500_000_000L) + clock.observe(1010.0, 1_000_000_000L) + assertEquals(10.0, clock.driftMs, 1e-6) + assertEquals(1010.0, clock.mapMs(1_000_000_000L), 1e-6) + } + + @Test + fun startClearsDriftButKeepsCountingResyncs() { + val clock = SongClock() + clock.start(0.0, 0L) + clock.observe(2000.0, 1_000_000_000L) + assertEquals(1, clock.resyncCount) + clock.start(0.0, 1_000_000_000L) + assertEquals(0.0, clock.driftMs) + assertEquals(0.0, clock.maxDriftMs) + assertEquals(1, clock.resyncCount) + } + + /** Before the music starts there's no position, so the first one is believed at once. */ + @Test + fun afterALeadInTheFirstAudioPositionIsTakenWhole() { + val clock = SongClock() + clock.start(-3000.0, 0L) + var wall = 0L + while (wall < 3_000_000_000L) { + wall += frameNs + clock.observe(Double.NaN, wall) + } + assertEquals(0.0, clock.nowMs(wall), 5.0) + clock.observe(-21.0, wall) + assertEquals(-21.0, clock.mapMs(wall), 1e-6) + assertEquals(0, clock.resyncCount) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/golden/GoldenReplayTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/golden/GoldenReplayTest.kt new file mode 100644 index 0000000..d60d760 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/golden/GoldenReplayTest.kt @@ -0,0 +1,209 @@ +package net.trilleo.hexium.core.golden + +import java.io.File +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.test.assertNull +import net.trilleo.hexium.core.chart.ChartParser +import net.trilleo.hexium.core.judge.ClearLamp +import net.trilleo.hexium.core.judge.Judge +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.Judgement +import net.trilleo.hexium.core.replay.Replay +import net.trilleo.hexium.core.replay.ReplayFile +import net.trilleo.hexium.core.replay.ReplayJudge + +/** + * Stored replays of scripted players must keep giving the same results. Every summary below was + * worked out by hand from the example charts, not copied from the judge (see the comments). + * Each `.expected` file also locks every object's result, so any change to the judge shows up. + * + * After a deliberate change, regenerate them: ./gradlew :core:test --rerun -Dhexium.updateGolden=true + */ +class GoldenReplayTest { + private class Golden( + val name: String, + val chart: String, + val style: PlayStyle, + val score: Int, + val lamp: ClearLamp, + val maxCombo: Int, + val justiceCritical: Int, + val justice: Int, + val attack: Int, + val miss: Int, + ) + + /* + * Objects in each chart, counting a hold as its head plus 7 ticks per 2 beats (ticks every 1/4 beat, no ends): + * - basic: 13 taps, 2 two-beat holds (8 each) = 29. 15 presses, 14 ticks. + * - advanced: 11 taps, 3 sky taps, 1 two-beat hold (8), 1 two-beat slide (7 ticks) = 29. + * 15 presses (taps, head, sky taps), 14 ticks. + * - expert: 18 taps, holds of 8, 6 and 8, so 40 ground objects. 3 sky taps, a two-beat slide (7), 3 flicks = 53. + * + * Score is 10,000 x (sum of weight percent) / objects, rounded down: + * - late_basic: 15 x 100 + 14 x 101 = 2914. 29,140,000 / 29 = 1,004,827. + * - attack_advanced: 15 x 50 + 14 x 101 = 2164. 21,640,000 / 29 = 746,206. 90 ms late is Attack only on easy charts. + * - ground_only_expert: 40 x 101 = 4040. 40,400,000 / 53 = 762,264. + * - sloppy_expert: presses 70 ms late are Attack on Expert (24: 18 taps, 3 heads, 3 sky taps). Flicks swiped 150 ms + * late are Justice (3): beat 10's is crossed a little earlier, on the jump from rest to the start of its swipe, + * at about +111 ms, which is still Justice. The jumps to the starts of beat 9.5's and beat 20's swipes pass + * beside those notes (closest about 0.092 against radius 0.08, and 0.24 against 0.12), so they're crossed on + * the swipe itself, at 150 - 40 + 26.67 = +136.67 ms and 150 - 40 + 20 = +130 ms. The 26 ticks stay Justice Critical. 24 x 50 + 3 x 100 + 26 x 101 = 4126. + * 41,260,000 / 53 = 778,490. + * - ground_only_expert best combo: it's 10, between the hold head at 10.5 and the sky tap at 12 (missed at 12.24): 5 ticks, + * the taps at 11, 11.25 and 11.5, and two taps at 12. By time alone it would be 11, but the flick at beat 10 + * is only known to be missed at the first aim sample after its deadline. That's 5.74 ms before the head at + * 10.5, and at 120 FPS the sample lands after the head, so the Miss splits the head off (docs/JUDGEMENT.md). + */ + private val goldens = listOf( + Golden("perfect_basic", "basic", PlayStyle(), 1_010_000, ClearLamp.ALL_JUSTICE_CRITICAL, 29, 29, 0, 0, 0), + Golden("late_basic", "basic", PlayStyle(lateMs = 50.0), 1_004_827, ClearLamp.ALL_JUSTICE, 29, 14, 15, 0, 0), + Golden("perfect_advanced", "advanced", PlayStyle(), 1_010_000, ClearLamp.ALL_JUSTICE_CRITICAL, 29, 29, 0, 0, 0), + Golden("attack_advanced", "advanced", PlayStyle(lateMs = 90.0), 746_206, ClearLamp.FULL_COMBO, 29, 14, 0, 15, 0), + Golden("none_advanced", "advanced", PlayStyle(playGround = false, playSky = false), 0, ClearLamp.NONE, 0, 0, 0, 0, 29), + Golden("perfect_expert", "expert", PlayStyle(judgementOffsetMs = 25.0), 1_010_000, ClearLamp.ALL_JUSTICE_CRITICAL, 53, 53, 0, 0, 0), + Golden( + "sloppy_expert", + "expert", + PlayStyle(lateMs = 70.0, swipeLateMs = 150.0), + 778_490, + ClearLamp.FULL_COMBO, + 53, + 26, + 3, + 24, + 0, + ), + Golden("ground_only_expert", "expert", PlayStyle(playSky = false), 762_264, ClearLamp.NONE, 10, 40, 0, 0, 13), + ) + + private val folder = File("src/test/resources/golden") + private val recordedFolder = File(folder, "recorded") + + init { + if (System.getProperty("hexium.updateGolden") == "true") regenerate() + } + + private fun chartFile(name: String) = File("../docs/examples/$name.json").readBytes() + + private fun log(judge: Judge) = buildString { + append("score ").append(judge.score).append('\n') + append("lamp ").append(judge.clearLamp).append('\n') + append("maxCombo ").append(judge.maxCombo).append('\n') + for (i in 0 until judge.judgedCount) { + append(judge.judgedNote(i)).append(' ').append(judge.judgement(i)).append(' ').append(judge.judgedDeltaMs(i)).append('\n') + } + } + + @Test + fun storedReplaysGiveTheirHandWorkedResults() { + for (golden in goldens) { + val read = ReplayFile.read(File(folder, "${golden.name}.hexreplay").readBytes()) + assertNull(read.error, golden.name) + val result = ReplayJudge.rejudge(chartFile(golden.chart), assertNotNull(read.replay)) + assertNull(result.error, golden.name) + val judge = assertNotNull(result.judge) + assertEquals(golden.score, judge.score, golden.name) + assertEquals(golden.lamp, judge.clearLamp, golden.name) + assertEquals(golden.maxCombo, judge.maxCombo, golden.name) + assertEquals(golden.justiceCritical, judge.count(Judgement.JUSTICE_CRITICAL), golden.name) + assertEquals(golden.justice, judge.count(Judgement.JUSTICE), golden.name) + assertEquals(golden.attack, judge.count(Judgement.ATTACK), golden.name) + assertEquals(golden.miss, judge.count(Judgement.MISS), golden.name) + assertEquals(File(folder, "${golden.name}.expected").readText(), log(judge), golden.name) + } + } + + @Test + fun scriptedPlayersStillProduceTheStoredResults() { + for (golden in goldens) { + val judge = ScriptedPlayer(chartFile(golden.chart)).play(golden.style).judge + assertEquals(File(folder, "${golden.name}.expected").readText(), log(judge), golden.name) + } + } + + /* + * Real plays, recorded in the game, keeping the names they were saved under. Nobody can work out a person's + * results by hand, so these lock in what the judge gave: they catch a change, and regenerating, which only + * rewrites their `.expected` files, is the deliberate way to accept one. The inputs of a real play stay worth + * having under a newer judge, so unlike a real re-judge this ignores the judge version. It can't ignore the + * chart: after editing a chart, delete its recordings and record new ones. + */ + private fun recordedPlays(from: File): List = + from.listFiles { file -> file.name.endsWith(".hexreplay") }.orEmpty().sortedBy { it.name } + + private fun recordedChartFile(play: File): ByteArray { + val match = assertNotNull(RECORDED_NAME.matchEntire(play.name), "${play.name} isn't named as the game saves replays") + val (pack, difficulty) = match.destructured + assertEquals(BUNDLED_PACK, pack, "${play.name} isn't of a pack the tests can read") + return File("../mod/src/client/resources/hexium_packs/$BUNDLED_PACK/$difficulty.json").readBytes() + } + + private fun rejudgeRecorded(play: File): Judge { + val read = ReplayFile.read(play.readBytes()) + assertNull(read.error, play.name) + val replay = assertNotNull(read.replay) + val chartFile = recordedChartFile(play) + assertContentEquals(Replay.hashOf(chartFile), replay.chartHash, "${play.name} was played on a different version of its chart") + val chart = assertNotNull(ChartParser.parseDifficulty(String(chartFile, Charsets.UTF_8)).value) + return ReplayJudge.play(JudgeChart.compile(chart), replay) + } + + private fun expectedOf(play: File) = File(play.parentFile, "${play.name.removeSuffix(".hexreplay")}.expected") + + private fun assertRecordedPlaysMatch(from: File) { + for (play in recordedPlays(from)) assertEquals(expectedOf(play).readText(), log(rejudgeRecorded(play)), play.name) + } + + private fun writeRecordedExpected(from: File) { + for (play in recordedPlays(from)) expectedOf(play).writeText(log(rejudgeRecorded(play))) + } + + @Test + fun recordedPlaysKeepTheirResults() { + assertTrue(recordedPlays(recordedFolder).isNotEmpty(), "the recorded plays have gone missing") + assertRecordedPlaysMatch(recordedFolder) + } + + /** Checks the path above with a stored replay of the same chart, until and beyond there being real ones. */ + @Test + fun aRecordedPlayIsReadAndLockedIn() { + val temp = Files.createTempDirectory("hexium-recorded").toFile() + try { + val play = File(temp, "test-pattern-basic-20261104-160608-2.hexreplay") + File(folder, "late_basic.hexreplay").copyTo(play) + writeRecordedExpected(temp) + assertEquals(File(folder, "late_basic.expected").readText(), expectedOf(play).readText()) + assertRecordedPlaysMatch(temp) + } finally { + temp.deleteRecursively() + } + } + + @Test + fun aRecordedPlayMustBeNamedAsTheGameSavesIt() { + assertFailsWith { recordedChartFile(File("my-replay.hexreplay")) } + assertFailsWith { recordedChartFile(File("other-pack-basic-20261104-160608.hexreplay")) } + } + + private companion object { + const val BUNDLED_PACK = "test-pattern" + val RECORDED_NAME = Regex("""(.+)-([a-z]+)-\d{8}-\d{6}(?:-\d+)?\.hexreplay""") + } + + private fun regenerate() { + folder.mkdirs() + for (golden in goldens) { + val recorder = ScriptedPlayer(chartFile(golden.chart)).play(golden.style) + File(folder, "${golden.name}.hexreplay").writeBytes(ReplayFile.write(recorder.toReplay())) + File(folder, "${golden.name}.expected").writeText(log(recorder.judge)) + } + writeRecordedExpected(recordedFolder) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/golden/JudgeProperties.kt b/core/src/test/kotlin/net/trilleo/hexium/core/golden/JudgeProperties.kt new file mode 100644 index 0000000..af8b59b --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/golden/JudgeProperties.kt @@ -0,0 +1,151 @@ +package net.trilleo.hexium.core.golden + +import java.io.File +import kotlin.math.abs +import net.jqwik.api.Arbitraries +import net.jqwik.api.Arbitrary +import net.jqwik.api.ForAll +import net.jqwik.api.Property +import net.jqwik.api.Provide +import net.jqwik.api.RandomDistribution +import net.jqwik.api.constraints.DoubleRange +import net.jqwik.api.constraints.IntRange +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.ChartParser +import net.trilleo.hexium.core.judge.Judge +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.Judgement +import net.trilleo.hexium.core.judge.beat +import net.trilleo.hexium.core.judge.chartOf +import net.trilleo.hexium.core.replay.Replay +import net.trilleo.hexium.core.replay.ReplayFile +import net.trilleo.hexium.core.replay.ReplayJudge +import net.trilleo.hexium.core.replay.ReplayRecorder + +/** Whatever the input, these stay true (docs/DEVELOPMENT.md, test strategy). */ +class JudgeProperties { + private val names = listOf("basic", "advanced", "expert") + + private fun chartFile(which: Int) = File("../docs/examples/${names[which]}.json").readBytes() + + /** A play with a different small timing error on each press, the same for the same seed. */ + private fun jitter(seed: Int, spreadMs: Double): (Int) -> Double = { note -> + val mixed = (note + 1) * 2654435761L xor seed.toLong() + val whole = java.util.Random(mixed).nextDouble() * 2 - 1 + Math.round(whole * spreadMs * 1024.0) / 1024.0 + } + + private fun results(judge: Judge) = List(judge.judgedCount) { judge.judgedNote(it) to judge.judgement(it) } + + @Property(tries = 60) + fun shiftingEveryInputByOffsetBLeavesTheResultUnchanged( + @ForAll @IntRange(min = 0, max = 2) chart: Int, + @ForAll seed: Int, + @ForAll @IntRange(min = -3200, max = 3200) sixteenths: Int, + ): Boolean { + val player = ScriptedPlayer(chartFile(chart)) + val spread = jitter(seed, 120.0) + val plain = player.play(PlayStyle(jitterMs = spread)).judge + val shifted = player.play(PlayStyle(jitterMs = spread, judgementOffsetMs = sixteenths / 16.0)).judge + return plain.score == shifted.score && results(plain) == results(shifted) + } + + @Provide + fun swipeTimes(): Arbitrary = Arbitraries.doubles().between(-220.0, 230.0).withDistribution(RandomDistribution.uniform()) + + @Provide + fun angles(): Arbitrary = Arbitraries.doubles().between(0.0, 360.0).withDistribution(RandomDistribution.uniform()) + + @Property(tries = 300) + fun aSteadySwipeGetsTheSameJudgementAtEveryFrameRate( + @ForAll("swipeTimes") lateMs: Double, + @ForAll("angles") degrees: Double, + @ForAll @DoubleRange(min = 0.0, max = 1.0) framePhase: Double, + ): Boolean { + // 6 heights per second through a flick at 1000 ms, so it's inside the hit area for 13.33 ms either side of lateMs. + val speed = 0.006 + val insideMs = 0.08 / speed + val opens = -166.67 + val closes = 166.67 + val leavesAtMs = lateMs + insideMs + val crossesAtMs = maxOf(lateMs - insideMs, opens) + // Floats round positions, so stay clear of the very edge of each limit. + val clearOfLimits = abs(abs(crossesAtMs) - 83.33) > 0.01 && abs(leavesAtMs - opens) > 0.01 && abs(crossesAtMs - closes) > 0.01 + if (!clearOfLimits) return true + val dx = Math.cos(Math.toRadians(degrees)) * speed / 2.0 + val dy = Math.sin(Math.toRadians(degrees)) * speed + val chart = JudgeChart.compile(chartOf(Note.Flick(beat(1), 0.5, 0.5, 1.0))) + val judgements = listOf(30.0, 60.0, 120.0, 144.0, 240.0, 360.0).map { fps -> + val judge = Judge(chart) + val frame = 1000.0 / fps + var time = 600.0 + framePhase * frame + while (time < 1400.0) { + val moved = time - 1000.0 - lateMs + judge.aimSample(time, (0.5 + dx * moved).toFloat(), (0.5 + dy * moved).toFloat()) + time += frame + } + judge.finish() + judge.judgement(0) + } + val expected = when { + leavesAtMs < opens || crossesAtMs > closes -> Judgement.MISS + abs(crossesAtMs) <= 83.33 -> Judgement.JUSTICE_CRITICAL + else -> Judgement.JUSTICE + } + return judgements.all { it == expected } + } + + @Provide + fun actions(): Arbitrary> = Arbitraries.integers().between(0, 5).list().ofMinSize(50).ofMaxSize(400) + + @Property(tries = 200) + fun randomInputNeverBreaksTheJudgeAndReplaysMatch( + @ForAll @IntRange(min = 0, max = 2) chart: Int, + @ForAll("actions") actions: List, + @ForAll seed: Long, + ): Boolean { + val file = chartFile(chart) + val compiled = JudgeChart.compile(ChartParser.parseDifficulty(String(file)).value!!) + val recorder = ReplayRecorder(compiled, Replay.hashOf(file), 0.0, actions.size) + val random = java.util.Random(seed) + val chartNotes = ChartParser.parseDifficulty(String(file)).value!!.notes + val spots = chartNotes.mapNotNull { note -> + when (note) { + is Note.SkyTap -> note.x to note.y + is Note.Flick -> note.x to note.y + is Note.Slide -> note.points[0].x to note.points[0].y + else -> null + } + } + var time = 0.0 + for (action in actions) { + time += random.nextDouble() * 90.0 - 10.0 + // Half the time, somewhere a note really is, so that plays hit things as well as miss them. + val spot = if (spots.isNotEmpty() && random.nextBoolean()) spots[random.nextInt(spots.size)] else null + val x = spot?.first?.toFloat() ?: (random.nextFloat() * 1.4f - 0.2f) + val y = spot?.second?.toFloat() ?: (random.nextFloat() * 1.4f - 0.2f) + val lane = random.nextInt(5) + val button = if (random.nextBoolean()) SkyButton.L else SkyButton.R + when (action) { + 0 -> recorder.pressLane(lane, time) + 1 -> recorder.releaseLane(lane, time) + 2 -> recorder.pressButton(button, time, x, y) + 3 -> recorder.releaseButton(button, time) + 4 -> recorder.aimSample(time, x, y) + else -> recorder.advanceTo(time) + } + } + recorder.finish() + val judge = recorder.judge + val written = ReplayFile.write(recorder.toReplay()) + val replayed = ReplayJudge.play(compiled, ReplayFile.read(written).replay!!) + return judge.judgedCount == judge.objectCount && + judge.score in 0..1_010_000 && + judge.maxCombo <= judge.objectCount && + results(judge) == results(replayed) && + List(judge.judgedCount) { judge.judgedDeltaMs(it) } == List(replayed.judgedCount) { replayed.judgedDeltaMs(it) } && + judge.score == replayed.score && + judge.maxCombo == replayed.maxCombo + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/golden/ScriptedPlayer.kt b/core/src/test/kotlin/net/trilleo/hexium/core/golden/ScriptedPlayer.kt new file mode 100644 index 0000000..2c9f8f6 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/golden/ScriptedPlayer.kt @@ -0,0 +1,158 @@ +package net.trilleo.hexium.core.golden + +import net.trilleo.hexium.core.chart.ChartParser +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.SlidePath +import net.trilleo.hexium.core.chart.TimingMap +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.JudgementConfig +import net.trilleo.hexium.core.replay.Replay +import net.trilleo.hexium.core.replay.ReplayRecorder + +/** How a scripted player plays a chart. Plays one is built from are recorded as golden replays. */ +internal data class PlayStyle( + val playGround: Boolean = true, + val playSky: Boolean = true, + /** Added to every press that hits a tap, hold head or sky tap. */ + val lateMs: Double = 0.0, + val framesPerSecond: Double = 120.0, + /** Input lag: every time is this much later, which offset B then cancels. */ + val judgementOffsetMs: Double = 0.0, + /** A different extra offset for each press, from its note's index. Used by the property tests. */ + val jitterMs: (Int) -> Double = { 0.0 }, + /** Added to the moment a swipe passes through a flick. */ + val swipeLateMs: Double = 0.0, +) + +/** + * Plays a chart from what it says, without looking at the judge's results, and records it. + * The crosshair follows slides, swipes through flicks and otherwise rests in the middle. + */ +internal class ScriptedPlayer(private val chartFile: ByteArray) { + private val chart: DifficultyChart = ChartParser.parseDifficulty(String(chartFile)).value!! + private val timing = TimingMap(chart.offsetMs, chart.bpm) + + private class Input(val ms: Double, val apply: (ReplayRecorder, Double) -> Unit) + + private class SlideRun(val startMs: Double, val endMs: Double, val path: SlidePath) + + /** Any direction hits a flick. The scripted swipes always go right, so the goldens stay fixed. */ + private class Swipe(val ms: Double, val x: Double, val y: Double, val radians: Double) + + fun play(style: PlayStyle): ReplayRecorder { + val inputs = ArrayList() + val slides = ArrayList() + val swipes = ArrayList() + var lastMs = 0.0 + var firstMs = Double.POSITIVE_INFINITY + + for (i in chart.notes.indices) { + val lag = style.lateMs + style.jitterMs(i) + when (val note = chart.notes[i]) { + is Note.Tap -> { + val at = timing.beatToMs(note.t) + firstMs = minOf(firstMs, at) + lastMs = maxOf(lastMs, at) + if (style.playGround) { + inputs += Input(at + lag) { r, t -> r.pressLane(note.lane, t) } + inputs += Input(at + lag + TAP_LENGTH_MS) { r, t -> r.releaseLane(note.lane, t) } + } + } + is Note.Hold -> { + val at = timing.beatToMs(note.t) + val end = timing.beatToMs(note.end) + firstMs = minOf(firstMs, at) + lastMs = maxOf(lastMs, end) + if (style.playGround) { + inputs += Input(at + lag) { r, t -> r.pressLane(note.lane, t) } + inputs += Input(end - 1.0) { r, t -> r.releaseLane(note.lane, t) } + } + } + is Note.SkyTap -> { + val at = timing.beatToMs(note.t) + firstMs = minOf(firstMs, at) + lastMs = maxOf(lastMs, at) + if (style.playSky) { + inputs += Input(at + lag) { r, t -> r.pressButton(note.button, t, note.x.toFloat(), note.y.toFloat()) } + inputs += Input(at + lag + TAP_LENGTH_MS) { r, t -> r.releaseButton(note.button, t) } + } + } + is Note.Slide -> { + val start = timing.beatToMs(note.points.first().t) + val end = timing.beatToMs(note.points.last().t) + firstMs = minOf(firstMs, start) + lastMs = maxOf(lastMs, end) + if (style.playSky) { + val first = note.points.first() + inputs += Input(start) { r, t -> r.pressButton(note.button, t, first.x.toFloat(), first.y.toFloat()) } + inputs += Input(end) { r, t -> r.releaseButton(note.button, t) } + slides += SlideRun(start, end, SlidePath(note.points)) + } + } + is Note.Flick -> { + val at = timing.beatToMs(note.t) + firstMs = minOf(firstMs, at) + lastMs = maxOf(lastMs, at) + if (style.playSky) swipes += Swipe(at + style.swipeLateMs, note.x, note.y, 0.0) + } + } + } + inputs.sortBy { it.ms } + + val offset = style.judgementOffsetMs + val frame = 1000.0 / style.framesPerSecond + val frames = ((lastMs - firstMs + 2 * MARGIN_MS) / frame).toInt() + 1 + val recorder = ReplayRecorder(JudgeChart.compile(chart), Replay.hashOf(chartFile), offset, frames + inputs.size) + var next = 0 + for (f in 0 until frames) { + val frameMs = firstMs - MARGIN_MS + f * frame + while (next < inputs.size && inputs[next].ms <= frameMs) { + inputs[next].apply(recorder, inputs[next].ms + offset) + next++ + } + recorder.aimSample(frameMs + offset, aimX(frameMs, slides, swipes), aimY(frameMs, slides, swipes)) + } + while (next < inputs.size) { + inputs[next].apply(recorder, inputs[next].ms + offset) + next++ + } + recorder.finish() + return recorder + } + + private fun aimX(ms: Double, slides: List, swipes: List): Float { + for (swipe in swipes) { + if (Math.abs(ms - swipe.ms) <= SWIPE_HALF_MS) { + return (swipe.x + Math.cos(swipe.radians) * SWIPE_SPEED * (ms - swipe.ms) / JudgementConfig.DEFAULT.screenAspect).toFloat() + } + } + for (slide in slides) { + if (ms >= slide.startMs && ms <= slide.endMs) return slide.path.x(timing.msToBeat(ms)).toFloat() + } + return REST + } + + private fun aimY(ms: Double, slides: List, swipes: List): Float { + for (swipe in swipes) { + if (Math.abs(ms - swipe.ms) <= SWIPE_HALF_MS) { + return (swipe.y + Math.sin(swipe.radians) * SWIPE_SPEED * (ms - swipe.ms)).toFloat() + } + } + for (slide in slides) { + if (ms >= slide.startMs && ms <= slide.endMs) return slide.path.y(timing.msToBeat(ms)).toFloat() + } + return REST + } + + private companion object { + const val TAP_LENGTH_MS = 30.0 + const val MARGIN_MS = 500.0 + const val REST = 0.5f + + /** In screen heights per millisecond, well above the minimum speed. */ + const val SWIPE_SPEED = 0.006 + const val SWIPE_HALF_MS = 40.0 + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeAllocationTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeAllocationTest.kt new file mode 100644 index 0000000..0aa8ec3 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeAllocationTest.kt @@ -0,0 +1,78 @@ +package net.trilleo.hexium.core.judge + +import java.lang.management.ManagementFactory +import kotlin.test.Test +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.Ease +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.SlidePoint + +/** The judge runs every frame in the mod, so playing a chart must not allocate. */ +class JudgeAllocationTest { + private val threads = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + + @Test + fun playingAChartDoesNotAllocate() { + val notes = Array(40_000) { + if (it % 2 == 0) Note.Tap(beat(it + 1), it % 4) else Note.Hold(beat(it + 1), beat(it + 1, 1, 2), it % 4) + } + val chart = JudgeChart.compile(chartOf(*notes)) + + val judge = Judge(chart) + val thread = Thread.currentThread().threadId() + val before = threads.getThreadAllocatedBytes(thread) + var i = 0 + while (i < notes.size) { + val time = (i + 1) * 1000.0 + judge.advanceTo(time) + judge.pressLane(i % 4, time) + judge.advanceTo(time + 10.0) + judge.releaseLane(i % 4, time + 600.0) + judge.advanceTo(time + 700.0) + i++ + } + judge.finish() + val allocated = threads.getThreadAllocatedBytes(thread) - before + assertTrue(allocated < 64 * 1024, "allocated $allocated bytes over ${notes.size} notes") + assertTrue(judge.judgedCount == judge.objectCount) + } + + @Test + fun playingSkyNotesDoesNotAllocate() { + val notes = Array(30_000) { + when (it % 3) { + 0 -> Note.SkyTap(beat(it + 1), 0.5, 0.5, SkyButton.L, 1.0) + 1 -> Note.Flick(beat(it + 1), 0.5, 0.5, 1.0) + else -> Note.Slide( + SkyButton.R, + 0.1, + listOf(SlidePoint(beat(it + 1), 0.5, 0.5, Ease.IN_OUT), SlidePoint(beat(it + 1, 1, 2), 0.5, 0.5, Ease.LINEAR)), + ) + } + } + val judge = Judge(JudgeChart.compile(chartOf(*notes))) + val thread = Thread.currentThread().threadId() + val before = threads.getThreadAllocatedBytes(thread) + var i = 0 + while (i < notes.size) { + val time = (i + 1) * 1000.0 + judge.aimSample(time - 10.0, 0.5f, 0.4f) + judge.aimSample(time, 0.5f, 0.6f) + if (i % 3 == 0) { + judge.pressButton(SkyButton.L, time, 0.5f, 0.5f) + judge.releaseButton(SkyButton.L, time + 5.0) + } else if (i % 3 == 2) { + judge.pressButton(SkyButton.R, time, 0.5f, 0.5f) + judge.aimSample(time + 300.0, 0.5f, 0.5f) + judge.releaseButton(SkyButton.R, time + 600.0) + } + judge.advanceTo(time + 700.0) + i++ + } + judge.finish() + val allocated = threads.getThreadAllocatedBytes(thread) - before + assertTrue(allocated < 64 * 1024, "allocated $allocated bytes over ${notes.size} notes") + assertTrue(judge.judgedCount == judge.objectCount) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeFlickTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeFlickTest.kt new file mode 100644 index 0000000..759fa3b --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeFlickTest.kt @@ -0,0 +1,424 @@ +package net.trilleo.hexium.core.judge + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.Ease +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.SlidePoint + +class JudgeFlickTest { + /** At time 0, so window limits are exact. */ + private fun flick(whole: Int = 0, x: Double = 0.5, y: Double = 0.5, size: Double = 1.0) = + Note.Flick(beat(whole), x, y, size) + + /** Starts inside the hit area at [ms] and leaves fast, so the crossing time is exactly [ms]. */ + private fun swipeFrom(ms: Double): List { + val judge = judgeOf(flick()) + judge.aimSample(ms, 0.5f, 0.5f) + judge.aimSample(ms + 10.0, 0.9f, 0.5f) + judge.finish() + return judge.judgements() + } + + private val jc = listOf(Judgement.JUSTICE_CRITICAL) + private val justice = listOf(Judgement.JUSTICE) + private val miss = listOf(Judgement.MISS) + + @Test + fun windowsAreOnTheCrossingTime() { + assertEquals(jc, swipeFrom(0.0)) + assertEquals(jc, swipeFrom(83.33)) + assertEquals(jc, swipeFrom(-83.33)) + assertEquals(justice, swipeFrom(83.34)) + assertEquals(justice, swipeFrom(-83.34)) + assertEquals(justice, swipeFrom(166.67)) + assertEquals(justice, swipeFrom(-166.67)) + assertEquals(miss, swipeFrom(166.68)) + } + + @Test + fun aSwipeStillInsideWhenTheWindowOpensCountsAsCrossingThen() { + for (fps in listOf(30.0, 60.0, 120.0, 144.0, 240.0, 360.0)) { + val judge = judgeOf(flick()) + val frame = 1000.0 / fps + var time = -400.0 + while (time < 100.0) { + // 6 heights per second, inside the hit area from 13.33 ms before -175 ms to 13.33 ms after it. + judge.aimSample(time, (0.5 + 0.003 * (time + 175.0)).toFloat(), 0.5f) + time += frame + } + judge.finish() + assertEquals(justice, judge.judgements(), "$fps FPS") + assertTrue(judge.judgedDeltaMs(0) >= -166.68, "${judge.judgedDeltaMs(0)} at $fps FPS") + } + } + + @Test + fun theCrossingIsExactlyTheOpeningWhenASingleStepSpansIt() { + val judge = judgeOf(flick()) + judge.aimSample(-170.0, 0.5f, 0.5f) + judge.aimSample(-160.0, 0.52f, 0.5f) + assertEquals(justice, judge.judgements()) + assertEquals(-166.67, judge.judgedDeltaMs(0), 1e-9) + } + + @Test + fun aSwipeThatLeavesBeforeTheWindowOpensDoesNothing() { + for (fps in listOf(30.0, 60.0, 120.0, 360.0)) { + val judge = judgeOf(flick()) + val frame = 1000.0 / fps + var time = -400.0 + while (time < -100.0) { + judge.aimSample(time, (0.5 + 0.003 * (time + 200.0)).toFloat(), 0.5f) + time += frame + } + assertEquals(0, judge.judgedCount, "$fps FPS") + judge.finish() + assertEquals(miss, judge.judgements(), "$fps FPS") + } + val oneStep = judgeOf(flick()) + oneStep.aimSample(-200.0, 0.5f, 0.5f) + oneStep.aimSample(-190.0, 0.9f, 0.5f) + assertEquals(0, oneStep.judgedCount) + } + + @Test + fun aPressPastTheDeadlineDoesNotMissAFlickTheNextSampleShowsWasCrossed() { + val judge = judgeOf(flick(1)) + judge.aimSample(1100.0, 0.3f, 0.5f) + judge.pressLane(0, 1170.0) + assertEquals(0, judge.judgedCount) + judge.aimSample(1180.0, 0.7f, 0.5f) + assertEquals(justice, judge.judgements()) + } + + @Test + fun flicksAreRecordedInTheOrderTheyAreCrossed() { + val judge = judgeOf(flick(1, x = 0.7), Note.Flick(beat(1, 1, 20), 0.3, 0.5, 1.0)) + judge.aimSample(1000.0, 0.1f, 0.5f) + judge.aimSample(1010.0, 0.9f, 0.5f) + assertEquals(listOf(1, 0), List(judge.judgedCount) { judge.judgedNote(it) }) + } + + /** A step from 10 ms before the window opens to 4 ms after, passing the given point exactly as it opens. */ + private fun stepThroughOpening(x: Double, y: Double, alongX: Boolean): Int { + val judge = judgeOf(flick()) + val before = 0.15 + val after = 0.06 + if (alongX) { + judge.aimSample(-176.67, (x - before / 2).toFloat(), y.toFloat()) + judge.aimSample(-162.67, (x + after / 2).toFloat(), y.toFloat()) + } else { + judge.aimSample(-176.67, x.toFloat(), (y - before).toFloat()) + judge.aimSample(-162.67, x.toFloat(), (y + after).toFloat()) + } + return judge.judgedCount + } + + @Test + fun theOpeningRuleMeasuresTheHitAreaWhereTheSwipeIsAsItOpens() { + assertEquals(1, stepThroughOpening(0.5 + 0.075 / 2, 0.5, alongX = false), "0.075 heights to the side") + assertEquals(0, stepThroughOpening(0.5 + 0.085 / 2, 0.5, alongX = false), "0.085 heights to the side") + assertEquals(0, stepThroughOpening(0.575, 0.5, alongX = false), "0.075 of the width is 0.15 heights") + assertEquals(1, stepThroughOpening(0.5, 0.575, alongX = true), "0.075 heights above") + assertEquals(0, stepThroughOpening(0.5, 0.585, alongX = true), "0.085 heights above") + } + + @Test + fun aSlowSwipeInsideWhenTheWindowOpensStillDoesNothing() { + val judge = judgeOf(flick()) + judge.aimSample(-200.0, 0.5f, 0.5f) + judge.aimSample(-100.0, 0.5f, 0.5f) + assertEquals(0, judge.judgedCount) + } + + @Test + fun noClickIsNeeded() { + val judge = judgeOf(flick()) + judge.pressButton(SkyButton.L, 0.0, 0.5f, 0.5f) + assertEquals(0, judge.judgedCount) + } + + @Test + fun fastSwipeThatJumpsOverTheNoteStillHits() { + val judge = judgeOf(flick(1)) + judge.aimSample(983.0, 0.1f, 0.5f) + judge.aimSample(1016.0, 0.9f, 0.5f) + assertEquals(jc, judge.judgements()) + } + + @Test + fun crossingTimeIsWhereTheSwipeFirstEntersTheHitArea() { + val judge = judgeOf(flick(1)) + judge.aimSample(1000.0, 0.26f, 0.5f) + judge.aimSample(1100.0, 0.56f, 0.5f) + assertEquals(jc, judge.judgements()) + assertEquals(200.0 / 3.0, judge.judgedDeltaMs(0), 0.01, "enters at x = 0.46, two thirds of the way along") + } + + @Test + fun swipeThatStartsInsideUsesItsFirstSample() { + val judge = judgeOf(flick(1)) + judge.aimSample(1020.0, 0.5f, 0.5f) + judge.aimSample(1030.0, 0.9f, 0.5f) + assertEquals(20.0, judge.judgedDeltaMs(0), 1e-9) + } + + @Test + fun swipeThatMissesTheHitAreaDoesNothing() { + val judge = judgeOf(flick(1)) + judge.aimSample(990.0, 0.1f, 0.7f) + judge.aimSample(1010.0, 0.9f, 0.7f) + assertEquals(0, judge.judgedCount) + judge.finish() + assertEquals(miss, judge.judgements()) + } + + @Test + fun swipeEndingBeforeTheHitAreaDoesNothing() { + val judge = judgeOf(flick(1)) + judge.aimSample(990.0, 0.1f, 0.5f) + judge.aimSample(1010.0, 0.3f, 0.5f) + assertEquals(0, judge.judgedCount) + } + + @Test + fun theSwipeMustBeFasterThanTheMinimumSpeed() { + // Across x, 0.5 of the width is 1 screen height because the screen is 2:1. + val tooSlow = judgeOf(flick()) + tooSlow.aimSample(-500.0, 0.25f, 0.5f) + tooSlow.aimSample(500.0, 0.75f, 0.5f) + assertEquals(miss, tooSlow.judgements(), "exactly 1 height per second isn't faster, and the sample passed the deadline") + assertTrue(tooSlow.judgedDeltaMs(0).isNaN()) + + val fastEnough = judgeOf(flick()) + fastEnough.aimSample(-500.0, 0.25f, 0.5f) + fastEnough.aimSample(490.0, 0.75f, 0.5f) + assertEquals(justice, fastEnough.judgements()) + } + + @Test + fun aParkedCrosshairDoesNotHit() { + val judge = judgeOf(flick()) + judge.aimSample(-10.0, 0.5f, 0.5f) + judge.aimSample(0.0, 0.5f, 0.5f) + judge.aimSample(10.0, 0.5f, 0.5f) + assertEquals(0, judge.judgedCount) + } + + @Test + fun tooSlowThenFastStillHitsInsideTheWindow() { + val judge = judgeOf(flick()) + judge.aimSample(-100.0, 0.5f, 0.5f) + judge.aimSample(-50.0, 0.5f, 0.5f) + judge.aimSample(-40.0, 0.9f, 0.5f) + assertEquals(jc, judge.judgements()) + assertEquals(-50.0, judge.judgedDeltaMs(0), 1e-9) + } + + /** Swipes through the note at [degrees], measured in screen heights. */ + private fun swipeAt(degrees: Double): Int { + val judge = judgeOf(flick()) + val radians = Math.toRadians(degrees) + val dx = Math.cos(radians) * 0.2 / 2.0 + val dy = Math.sin(radians) * 0.2 + judge.aimSample(-5.0, (0.5 - dx).toFloat(), (0.5 - dy).toFloat()) + judge.aimSample(5.0, (0.5 + dx).toFloat(), (0.5 + dy).toFloat()) + return judge.judgedCount + } + + @Test + fun aSwipeFromAnyDirectionHits() { + for (degrees in listOf(0.0, 33.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 359.0)) assertEquals(1, swipeAt(degrees), "$degrees degrees") + } + + @Test + fun aSwipeBackAfterMissingCanStillHit() { + val judge = judgeOf(flick()) + judge.aimSample(-30.0, 0.9f, 0.9f) + judge.aimSample(-20.0, 0.9f, 0.1f) + assertEquals(0, judge.judgedCount, "the first swipe passed beside the note") + // Back across the middle, through the note. + judge.aimSample(-10.0, 0.1f, 0.9f) + assertEquals(jc, judge.judgements()) + } + + @Test + fun oneSwipeCanHitSeveralFlicks() { + val judge = judgeOf(flick(1, x = 0.3), flick(1, x = 0.7)) + judge.aimSample(990.0, 0.1f, 0.5f) + judge.aimSample(1010.0, 0.9f, 0.5f) + assertEquals(jc + jc, judge.judgements()) + assertEquals(0, judge.judgedNote(0), "the one crossed first is recorded first") + assertEquals(1, judge.judgedNote(1)) + } + + @Test + fun aCrossingBeforeTheDeadlineCountsEvenIfTheNextSampleIsAfterIt() { + val judge = judgeOf(flick()) + judge.aimSample(165.0, 0.5f, 0.5f) + judge.advanceTo(170.0) + assertEquals(0, judge.judgedCount, "a swipe may still be under way") + judge.aimSample(175.0, 0.9f, 0.5f) + assertEquals(justice, judge.judgements()) + } + + @Test + fun advancingBetweenSamplesDoesNotChangeTheOrderOfResults() { + fun play(advance: Boolean): List { + val judge = judgeOf(flick(1), Note.Tap(beat(1, 1, 20), 0)) + judge.aimSample(900.0, 0.1f, 0.5f) + if (advance) judge.advanceTo(1140.0) + judge.aimSample(1150.0, 0.9f, 0.5f) + judge.finish() + return List(judge.judgedCount) { judge.judgedNote(it) } + } + assertEquals(listOf(0, 1), play(advance = false), "crossed at about 1012 ms, before the tap's deadline") + assertEquals(play(advance = false), play(advance = true)) + } + + @Test + fun notesWaitForTheNextSampleOnlyOnceAFlickWindowHasOpened() { + val judge = judgeOf(flick(1), Note.Tap(beat(0), 0)) + judge.advanceTo(833.0) + assertEquals(1, judge.judgedCount, "the flick's window hasn't opened, so the tap's Miss needn't wait") + } + + // An open flick window must not hold back other notes when an input arrives. + + @Test + fun aPressDuringAFlickWindowDoesNotHelpATickThatAlreadyPassed() { + fun play(samples: List): Judge { + val judge = judgeOf(flick(1), Note.Hold(beat(0, 1, 2), beat(1, 1, 2), 0)) + judge.pressLane(0, 500.0) + judge.releaseLane(0, 700.0) + for (ms in samples.filter { it < 1005.0 }) judge.aimSample(ms, 0.1f, 0.1f) + judge.pressLane(0, 1005.0) + for (ms in samples.filter { it >= 1005.0 }) judge.aimSample(ms, 0.1f, 0.1f) + judge.finish() + return judge + } + for (samples in listOf(listOf(995.0, 1011.0), List(600) { 500.0 + it * 2.0 })) { + val judge = play(samples) + assertEquals(3, judge.count(Judgement.JUSTICE_CRITICAL), "head, tick at 750, tick at 1250") + assertEquals(2, judge.count(Judgement.MISS), "the tick at 1000 and the flick") + assertEquals(606_000, judge.score) + } + } + + @Test + fun aPressDuringAFlickWindowGoesToTheRightTap() { + val judge = judgeOf(flick(1), Note.Tap(beat(1), 0), Note.Tap(beat(1, 1, 10), 0)) + judge.aimSample(1080.0, 0.1f, 0.1f) + judge.pressLane(0, 1090.0) + judge.aimSample(1096.0, 0.1f, 0.1f) + judge.finish() + assertEquals(1, judge.count(Judgement.JUSTICE_CRITICAL), "the second tap, 10 ms early") + assertEquals(2, judge.count(Judgement.MISS), "the first tap and the flick") + assertEquals(336_666, judge.score) + } + + @Test + fun aClickDuringAFlickWindowGoesToTheRightSkyTap() { + val judge = judgeOf( + flick(1, x = 0.9), + Note.SkyTap(beat(1), 0.5, 0.5, SkyButton.L, 1.0), + Note.SkyTap(beat(1, 1, 10), 0.5, 0.5, SkyButton.L, 1.0), + ) + judge.aimSample(1080.0, 0.1f, 0.1f) + judge.pressButton(SkyButton.L, 1090.0, 0.5f, 0.5f) + judge.finish() + assertEquals(1, judge.count(Judgement.JUSTICE_CRITICAL)) + assertEquals(2, judge.count(Judgement.MISS)) + } + + @Test + fun aClickDuringAFlickWindowDoesNotHelpASlideTickThatAlreadyPassed() { + val slide = Note.Slide( + SkyButton.L, + 0.1, + listOf(SlidePoint(beat(0), 0.5, 0.5, Ease.LINEAR), SlidePoint(beat(1, 1, 8), 0.5, 0.5, Ease.LINEAR)), + ) + val judge = judgeOf(flick(1, x = 0.9), slide) + judge.aimSample(995.0, 0.5f, 0.5f) + judge.pressButton(SkyButton.L, 1005.0, 0.5f, 0.5f) + judge.finish() + assertEquals(5, judge.count(Judgement.MISS), "the flick and every tick up to 1000 ms") + } + + @Test + fun aReplayWithNoAimSamplesGetsNoFreeTicks() { + val judge = judgeOf(flick(1), Note.Hold(beat(2), beat(10), 0)) + judge.pressLane(0, 500_000.0) + judge.finish() + assertEquals(0, judge.score) + assertEquals(judge.objectCount, judge.count(Judgement.MISS)) + } + + @Test + fun minimumSpeedAppliesOnTheYAxisToo() { + val tooSlow = judgeOf(flick()) + tooSlow.aimSample(-500.0, 0.5f, 0f) + tooSlow.aimSample(500.0, 0.5f, 1f) + assertEquals(miss, tooSlow.judgements(), "exactly 1 height per second isn't faster") + + val fastEnough = judgeOf(flick()) + fastEnough.aimSample(-500.0, 0.5f, 0f) + fastEnough.aimSample(490.0, 0.5f, 1f) + assertEquals(justice, fastEnough.judgements()) + } + + @Test + fun noSwipeMissesOnceASamplePassesTheDeadline() { + val judge = judgeOf(flick()) + judge.aimSample(166.0, 0.1f, 0.1f) + assertEquals(0, judge.judgedCount) + judge.aimSample(167.0, 0.1f, 0.1f) + assertEquals(miss, judge.judgements()) + assertTrue(judge.judgedDeltaMs(0).isNaN()) + } + + @Test + fun finishMissesAnUnswipedFlick() { + val judge = judgeOf(flick()) + judge.finish() + assertEquals(miss, judge.judgements()) + } + + @Test + fun sizeMultipliesTheHitArea() { + val judge = judgeOf(flick(size = 2.0)) + judge.aimSample(-5.0, 0.1f, 0.65f) + judge.aimSample(5.0, 0.9f, 0.65f) + assertEquals(1, judge.judgedCount) + } + + @Test + fun frameRateBarelyChangesTheCrossingTime() { + val deltas = ArrayList() + for (fps in listOf(60.0, 144.0, 360.0)) { + val judge = judgeOf(flick(1)) + val step = 1000.0 / fps + var time = 950.0 + while (judge.judgedCount == 0 && time < 1100.0) { + judge.aimSample(time, (0.2 + (time - 950.0) * 0.006).toFloat(), 0.5f) + time += step + } + deltas += judge.judgedDeltaMs(0) + } + assertTrue(deltas.max() - deltas.min() < 0.01, deltas.toString()) + } + + @Test + fun flicksCountTowardsScore() { + val judge = judgeOf(flick(1)) + assertEquals(1, judge.objectCount) + judge.aimSample(1000.0, 0.5f, 0.5f) + judge.aimSample(1010.0, 0.9f, 0.5f) + judge.finish() + assertEquals(1_010_000, judge.score) + assertEquals(ClearLamp.ALL_JUSTICE_CRITICAL, judge.clearLamp) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeGroundTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeGroundTest.kt new file mode 100644 index 0000000..e7d525f --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeGroundTest.kt @@ -0,0 +1,402 @@ +package net.trilleo.hexium.core.judge + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.BpmChange +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.Note + +class JudgeGroundTest { + /** A note at time 0, so window limits are exact in floating point. */ + private fun tapAt(pressMs: Double, difficulty: Difficulty = Difficulty.EXPERT): List { + val judge = judgeOf(Note.Tap(beat(0), 0), difficulty = difficulty) + judge.pressLane(0, pressMs) + judge.finish() + return judge.judgements() + } + + private val jc = listOf(Judgement.JUSTICE_CRITICAL) + private val justice = listOf(Judgement.JUSTICE) + private val attack = listOf(Judgement.ATTACK) + private val miss = listOf(Judgement.MISS) + + @Test + fun tapWindowsAreInclusiveOnBothSides() { + assertEquals(jc, tapAt(0.0)) + assertEquals(jc, tapAt(20.0)) + assertEquals(jc, tapAt(33.33)) + assertEquals(jc, tapAt(-33.33)) + assertEquals(justice, tapAt(33.34)) + assertEquals(justice, tapAt(-33.34)) + assertEquals(justice, tapAt(66.67)) + assertEquals(justice, tapAt(-66.67)) + assertEquals(attack, tapAt(66.68)) + assertEquals(attack, tapAt(-66.68)) + assertEquals(attack, tapAt(83.33)) + assertEquals(attack, tapAt(-83.33)) + } + + @Test + fun lateBeyondAttackIsAMissAndThePressDoesNothing() { + val judge = judgeOf(Note.Tap(beat(0), 0)) + judge.pressLane(0, 83.34) + assertEquals(miss, judge.judgements()) + judge.finish() + assertEquals(1, judge.judgedCount) + } + + @Test + fun earlyBeyondAttackUsesUpTheNoteAsAMissUpTo150Ms() { + assertEquals(miss, tapAt(-83.34)) + assertEquals(miss, tapAt(-150.0)) + val judge = judgeOf(Note.Tap(beat(0), 0)) + judge.pressLane(0, -100.0) + assertEquals(miss, judge.judgements()) + judge.releaseLane(0, -90.0) + judge.pressLane(0, 0.0) + assertEquals(1, judge.judgedCount, "the note is already used up") + } + + @Test + fun pressEarlierThan150MsDoesNothing() { + val judge = judgeOf(Note.Tap(beat(0), 0)) + judge.pressLane(0, -150.01) + assertEquals(0, judge.judgedCount) + judge.releaseLane(0, -100.0) + judge.pressLane(0, 10.0) + assertEquals(jc, judge.judgements()) + } + + @Test + fun basicAndAdvancedUseTheEasyAttackWindow() { + for (difficulty in listOf(Difficulty.BASIC, Difficulty.ADVANCED)) { + assertEquals(attack, tapAt(100.0, difficulty)) + assertEquals(attack, tapAt(-100.0, difficulty)) + assertEquals(miss, tapAt(100.01, difficulty)) + assertEquals(miss, tapAt(-100.01, difficulty)) + assertEquals(jc, tapAt(33.33, difficulty)) + assertEquals(justice, tapAt(66.67, difficulty)) + } + } + + @Test + fun expertAndMasterUseTheNormalAttackWindow() { + for (difficulty in listOf(Difficulty.EXPERT, Difficulty.MASTER)) { + assertEquals(attack, tapAt(83.33, difficulty)) + assertEquals(miss, tapAt(83.34, difficulty)) + } + } + + @Test + fun unpressedNoteMissesOnceItsWindowHasPassed() { + val judge = judgeOf(Note.Tap(beat(0), 0)) + judge.advanceTo(83.33) + assertEquals(0, judge.judgedCount) + judge.advanceTo(83.34) + assertEquals(miss, judge.judgements()) + } + + @Test + fun pressWithNoNoteNearbyDoesNothing() { + val judge = judgeOf(Note.Tap(beat(5), 0)) + judge.pressLane(0, 1000.0) + assertEquals(0, judge.judgedCount) + assertEquals(1, judgeOf(Note.Tap(beat(5), 0)).objectCount) + } + + @Test + fun otherLanesDoNotHitTheNote() { + val judge = judgeOf(Note.Tap(beat(1), 2)) + judge.pressLane(1, 1000.0) + assertEquals(0, judge.judgedCount) + judge.pressLane(2, 1000.0) + assertEquals(jc, judge.judgements()) + } + + @Test + fun lanesOutsideTheChartAreIgnored() { + val judge = judgeOf(Note.Tap(beat(1), 0)) + judge.pressLane(-1, 1000.0) + judge.pressLane(4, 1000.0) + judge.releaseLane(9, 1000.0) + assertEquals(0, judge.judgedCount) + } + + @Test + fun onePressResolvesOnlyTheEarliestNote() { + val judge = judgeOf(Note.Tap(beat(1), 0), Note.Tap(beat(1, 1, 10), 0)) + judge.pressLane(0, 1050.0) + assertEquals(justice, judge.judgements()) + judge.releaseLane(0, 1060.0) + judge.pressLane(0, 1100.0) + assertEquals(justice + jc, judge.judgements()) + } + + @Test + fun notesAreResolvedWhateverTheFileOrder() { + val judge = judgeOf(Note.Tap(beat(2), 0), Note.Tap(beat(1), 0)) + judge.pressLane(0, 1000.0) + judge.releaseLane(0, 1010.0) + judge.pressLane(0, 2000.0) + assertEquals(jc + jc, judge.judgements()) + assertEquals(1, judge.judgedNote(0)) + assertEquals(0, judge.judgedNote(1)) + } + + @Test + fun keyAlreadyDownDoesNotPressAgain() { + val judge = judgeOf(Note.Tap(beat(1), 0)) + judge.pressLane(0, 500.0) + judge.pressLane(0, 1000.0) + assertEquals(0, judge.judgedCount) + } + + @Test + fun missedNoteBeforeAPressGoesFirst() { + val judge = judgeOf(Note.Tap(beat(1), 0), Note.Tap(beat(2), 1)) + judge.pressLane(1, 2000.0) + assertEquals(miss + jc, judge.judgements()) + } + + @Test + fun recordsThePressOffset() { + val judge = judgeOf(Note.Tap(beat(1), 0)) + judge.pressLane(0, 980.0) + assertEquals(-20.0, judge.judgedDeltaMs(0), 1e-9) + val missed = judgeOf(Note.Tap(beat(1), 0)) + missed.finish() + assertTrue(missed.judgedDeltaMs(0).isNaN()) + } + + // Holds. Beat 1 is 1000 ms, so ticks every 1/4 beat are 250 ms apart. + + @Test + fun holdHeadIsJudgedLikeATap() { + val judge = judgeOf(Note.Hold(beat(1), beat(2), 0)) + judge.pressLane(0, 1040.0) + assertEquals(justice, judge.judgements()) + } + + @Test + fun ticksFallEveryQuarterBeatExcludingStartAndEnd() { + val chart = JudgeChart.compile(chartOf(Note.Hold(beat(1), beat(2), 0))) + assertEquals(4, chart.objectCount, "head plus ticks at 1250, 1500 and 1750") + val judge = Judge(chart) + judge.pressLane(0, 1000.0) + judge.advanceTo(1250.0) + assertEquals(1, judge.judgedCount) + judge.advanceTo(1250.01) + assertEquals(2, judge.judgedCount) + judge.advanceTo(1750.01) + assertEquals(4, judge.judgedCount) + judge.finish() + assertEquals(4, judge.judgedCount, "no tail") + assertEquals(jc + jc + jc + jc, judge.judgements()) + } + + @Test + fun ticksFromAnOffGridStartAreCountedFromIt() { + val judge = judgeOf(Note.Hold(beat(1, 1, 3), beat(2), 0)) + judge.pressLane(0, 1000.0 + 1000.0 / 3.0) + judge.advanceTo(1583.33) + assertEquals(1, judge.judgedCount, "first tick at 1583.33...") + judge.advanceTo(1583.34) + assertEquals(2, judge.judgedCount) + judge.advanceTo(1833.34) + assertEquals(3, judge.judgedCount) + judge.finish() + assertEquals(3, judge.judgedCount, "the next would be past the end") + } + + @Test + fun holdHeadsUseTheEasyWindowsAndTheEarlyMissToo() { + fun head(pressMs: Double, difficulty: Difficulty): Judgement { + val judge = judgeOf(Note.Hold(beat(0), beat(1), 0), difficulty = difficulty) + judge.pressLane(0, pressMs) + return judge.judgement(0) + } + assertEquals(Judgement.ATTACK, head(100.0, Difficulty.BASIC)) + assertEquals(Judgement.MISS, head(100.01, Difficulty.BASIC)) + assertEquals(Judgement.MISS, head(83.34, Difficulty.EXPERT)) + assertEquals(Judgement.MISS, head(-150.0, Difficulty.EXPERT)) + val tooEarly = judgeOf(Note.Hold(beat(0), beat(1), 0)) + tooEarly.pressLane(0, -150.01) + assertEquals(0, tooEarly.judgedCount) + } + + @Test + fun tickOnAnExactFractionOfTheEndIsLeftOut() { + val chart = JudgeChart.compile(chartOf(Note.Hold(beat(0, 1, 3), beat(0, 5, 6), 0))) + assertEquals(2, chart.objectCount, "1/3 + 1/2 beat long: head plus one tick, none on the end") + val longer = JudgeChart.compile(chartOf(Note.Hold(beat(0, 1, 3), beat(0, 6, 7), 0))) + assertEquals(3, longer.objectCount) + } + + @Test + fun holdTooShortForATickGetsOneAtItsEnd() { + val chart = JudgeChart.compile(chartOf(Note.Hold(beat(1), beat(1, 1, 8), 0))) + assertEquals(2, chart.objectCount) + val judge = Judge(chart) + judge.pressLane(0, 1000.0) + judge.advanceTo(1125.0) + assertEquals(1, judge.judgedCount) + judge.advanceTo(1125.01) + assertEquals(2, judge.judgedCount) + val exact = JudgeChart.compile(chartOf(Note.Hold(beat(1), beat(1, 1, 4), 0))) + assertEquals(2, exact.objectCount, "exactly 1/4 beat long also has no tick between") + } + + @Test + fun ticksFollowBpmChanges() { + val chart = chartOf(Note.Hold(beat(0), beat(2), 0)) + val compiled = JudgeChart.compile(chart.copy(bpm = chart.bpm + BpmChange(beat(1), 120.0))) + val judge = Judge(compiled) + judge.pressLane(0, 0.0) + judge.advanceTo(1125.0) + assertEquals(1 + 3 + 1, judge.judgedCount, "ticks at 250, 500, 750 and 1000 ms") + judge.advanceTo(1125.01) + assertEquals(6, judge.judgedCount) + } + + private fun tickFor(age: Double): Judgement { + val judge = judgeOf(Note.Hold(beat(0), beat(0, 1, 8), 0)) + judge.pressLane(0, 0.0) + judge.releaseLane(0, 125.0 - age) + judge.finish() + assertEquals(2, judge.judgedCount) + return judge.judgement(1) + } + + @Test + fun tickWindowsAreOnHowLongAgoTheKeyWasDown() { + assertEquals(Judgement.JUSTICE_CRITICAL, tickFor(0.0)) + assertEquals(Judgement.JUSTICE_CRITICAL, tickFor(50.0)) + assertEquals(Judgement.JUSTICE, tickFor(50.5)) + assertEquals(Judgement.JUSTICE, tickFor(100.0)) + assertEquals(Judgement.ATTACK, tickFor(100.5)) + assertEquals(Judgement.ATTACK, tickFor(120.0)) + } + + @Test + fun tickWindowsEndAt150Ms() { + val attackJudge = judgeOf(Note.Hold(beat(1), beat(1, 1, 8), 0)) + attackJudge.pressLane(0, 975.0) + attackJudge.releaseLane(0, 975.0) + attackJudge.finish() + assertEquals(Judgement.ATTACK, attackJudge.judgement(1), "released exactly 150 ms before the tick") + + val missJudge = judgeOf(Note.Hold(beat(1), beat(1, 1, 8), 0)) + missJudge.pressLane(0, 974.5) + missJudge.releaseLane(0, 974.5) + missJudge.finish() + assertEquals(Judgement.MISS, missJudge.judgement(1)) + } + + @Test + fun tickWithTheKeyDownIsJusticeCritical() { + val judge = judgeOf(Note.Hold(beat(0), beat(1), 0)) + judge.pressLane(0, 0.0) + judge.finish() + assertEquals(List(4) { Judgement.JUSTICE_CRITICAL }, judge.judgements()) + } + + @Test + fun releasingAndPressingAgainInsideTheWindowKeepsJusticeCritical() { + val judge = judgeOf(Note.Hold(beat(0), beat(1), 0)) + judge.pressLane(0, 0.0) + judge.releaseLane(0, 230.0) + judge.pressLane(0, 260.0) + judge.finish() + assertEquals(List(4) { Judgement.JUSTICE_CRITICAL }, judge.judgements()) + } + + @Test + fun pressAfterATickDoesNotHelpIt() { + val judge = judgeOf(Note.Hold(beat(0), beat(1), 0)) + judge.pressLane(0, -1000.0) + judge.releaseLane(0, -1000.0) + judge.pressLane(0, 251.0) + judge.finish() + assertEquals( + listOf(Judgement.MISS, Judgement.JUSTICE_CRITICAL, Judgement.JUSTICE_CRITICAL), + judge.judgements().drop(1), + ) + } + + @Test + fun missedHeadDoesNotFailTheTicks() { + val judge = judgeOf(Note.Hold(beat(1), beat(2), 0)) + judge.pressLane(0, 1200.0) + judge.finish() + assertEquals(listOf(Judgement.MISS) + List(3) { Judgement.JUSTICE_CRITICAL }, judge.judgements()) + } + + @Test + fun neverPressedHoldMissesEverything() { + val judge = judgeOf(Note.Hold(beat(1), beat(2), 0)) + judge.finish() + assertEquals(List(4) { Judgement.MISS }, judge.judgements()) + } + + @Test + fun keyDownBeforeTheHoldCountsForItsTicks() { + val judge = judgeOf(Note.Hold(beat(1), beat(2), 0)) + judge.pressLane(0, 500.0) + judge.finish() + assertEquals(listOf(Judgement.MISS) + List(3) { Judgement.JUSTICE_CRITICAL }, judge.judgements()) + } + + @Test + fun holdingPastTheEndIsNeverPenalised() { + val judge = judgeOf(Note.Hold(beat(0), beat(1), 0)) + judge.pressLane(0, 0.0) + judge.advanceTo(100_000.0) + judge.finish() + assertEquals(List(4) { Judgement.JUSTICE_CRITICAL }, judge.judgements()) + } + + @Test + fun skippingAStepDoesNotChangeTheOrderOrResult() { + val notes = arrayOf( + Note.Hold(beat(1), beat(2), 0), + Note.Tap(beat(1, 1, 2), 1), + Note.Tap(beat(1, 3, 4), 2), + Note.Hold(beat(2), beat(3), 3), + ) + fun play(step: Double): List> { + val judge = judgeOf(*notes) + var time = 0.0 + fun advance(to: Double) { + while (time + step < to) { + time += step + judge.advanceTo(time) + } + time = to + judge.advanceTo(to) + } + advance(1000.0) + judge.pressLane(0, 1000.0) + advance(1750.0) + judge.pressLane(2, 1750.0) + advance(1900.0) + judge.releaseLane(0, 1900.0) + advance(2600.0) + judge.pressLane(3, 2600.0) + judge.finish() + return List(judge.judgedCount) { judge.judgedNote(it) to judge.judgement(it) } + } + val baseline = play(1000.0) + assertEquals(baseline, play(4.0)) + assertEquals(baseline, play(16.67)) + assertEquals(chartOf(*notes).let { JudgeChart.compile(it).objectCount }, baseline.size) + } + + @Test + fun inputTimesCannotGoBackwards() { + val judge = judgeOf(Note.Tap(beat(1), 0)) + judge.advanceTo(1020.0) + judge.pressLane(0, 1000.0) + assertEquals(20.0, judge.judgedDeltaMs(0), 1e-9) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeSkyTapTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeSkyTapTest.kt new file mode 100644 index 0000000..90b2814 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeSkyTapTest.kt @@ -0,0 +1,163 @@ +package net.trilleo.hexium.core.judge + +import kotlin.test.Test +import kotlin.test.assertEquals +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton + +class JudgeSkyTapTest { + private val jc = listOf(Judgement.JUSTICE_CRITICAL) + private val justice = listOf(Judgement.JUSTICE) + private val attack = listOf(Judgement.ATTACK) + private val miss = listOf(Judgement.MISS) + + private fun tap(whole: Int = 0, x: Double = 0.5, y: Double = 0.5, button: SkyButton = SkyButton.L, size: Double = 1.0) = + Note.SkyTap(beat(whole), x, y, button, size) + + private fun clickAt(ms: Double, difficulty: Difficulty = Difficulty.EXPERT): List { + val judge = judgeOf(tap(), difficulty = difficulty) + judge.pressButton(SkyButton.L, ms, 0.5f, 0.5f) + judge.finish() + return judge.judgements() + } + + @Test + fun windowsMatchGroundTaps() { + assertEquals(jc, clickAt(33.33)) + assertEquals(jc, clickAt(-33.33)) + assertEquals(justice, clickAt(66.67)) + assertEquals(justice, clickAt(-66.67)) + assertEquals(attack, clickAt(83.33)) + assertEquals(attack, clickAt(-83.33)) + assertEquals(miss, clickAt(83.34)) + } + + @Test + fun easyChartsUseTheEasyAttackWindow() { + assertEquals(attack, clickAt(100.0, Difficulty.BASIC)) + assertEquals(attack, clickAt(-100.0, Difficulty.ADVANCED)) + assertEquals(miss, clickAt(100.01, Difficulty.BASIC)) + } + + @Test + fun earlyBeyondAttackUsesUpTheNoteUpTo150Ms() { + val judge = judgeOf(tap()) + judge.pressButton(SkyButton.L, -150.0, 0.5f, 0.5f) + assertEquals(miss, judge.judgements()) + + val tooEarly = judgeOf(tap()) + tooEarly.pressButton(SkyButton.L, -150.01, 0.5f, 0.5f) + assertEquals(0, tooEarly.judgedCount) + } + + @Test + fun unclickedNoteMissesOnceItsWindowHasPassed() { + val judge = judgeOf(tap()) + judge.advanceTo(83.33) + assertEquals(0, judge.judgedCount) + judge.advanceTo(83.34) + assertEquals(miss, judge.judgements()) + } + + @Test + fun wrongButtonIsIgnoredAndTheNoteStaysHittable() { + for ((note, wrong, right) in listOf( + Triple(tap(button = SkyButton.L), SkyButton.R, SkyButton.L), + Triple(tap(button = SkyButton.R), SkyButton.L, SkyButton.R), + )) { + val judge = judgeOf(note) + judge.pressButton(wrong, 0.0, 0.5f, 0.5f) + assertEquals(0, judge.judgedCount) + judge.pressButton(right, 10.0, 0.5f, 0.5f) + assertEquals(jc, judge.judgements()) + } + } + + @Test + fun clickOutsideTheHitAreaIsIgnoredAndCanTryAgain() { + val judge = judgeOf(tap()) + judge.pressButton(SkyButton.L, 0.0, 0.5f, 0.59f) + assertEquals(0, judge.judgedCount) + judge.releaseButton(SkyButton.L, 5.0) + judge.pressButton(SkyButton.L, 10.0, 0.5f, 0.5f) + assertEquals(jc, judge.judgements()) + } + + @Test + fun hitAreaIsACircleMeasuredInScreenHeights() { + fun hits(x: Float, y: Float, size: Double = 1.0): Boolean { + val judge = judgeOf(tap(size = size)) + judge.pressButton(SkyButton.L, 0.0, x, y) + return judge.judgedCount == 1 + } + assertEquals(true, hits(0.5f, 0.579f), "base radius is 0.08 of the height") + assertEquals(false, hits(0.5f, 0.581f)) + assertEquals(true, hits(0.539f, 0.5f), "x is half as far because the screen is 2:1") + assertEquals(false, hits(0.541f, 0.5f)) + assertEquals(false, hits(0.535f, 0.57f), "inside the box, outside the circle") + assertEquals(true, hits(0.5f, 0.65f, size = 2.0), "size multiplies the radius") + assertEquals(false, hits(0.5f, 0.55f, size = 0.5)) + } + + @Test + fun theEdgeOfTheHitAreaCounts() { + val config = JudgementConfig(baseHitRadius = 0.25) + fun judge() = Judge(JudgeChart.compile(chartOf(tap()), config)) + val inside = judge() + inside.pressButton(SkyButton.L, 0.0, 0.5f, 0.75f) + assertEquals(1, inside.judgedCount) + val outside = judge() + outside.pressButton(SkyButton.L, 0.0, 0.5f, 0.7501f) + assertEquals(0, outside.judgedCount) + } + + @Test + fun clickResolvesOnlyTheEarliestNoteUnderIt() { + val judge = judgeOf(Note.SkyTap(beat(1), 0.5, 0.5, SkyButton.L, 1.0), Note.SkyTap(beat(1, 1, 20), 0.5, 0.5, SkyButton.L, 1.0)) + judge.pressButton(SkyButton.L, 1000.0, 0.5f, 0.5f) + assertEquals(jc, judge.judgements()) + assertEquals(0, judge.judgedNote(0)) + judge.releaseButton(SkyButton.L, 1010.0) + judge.pressButton(SkyButton.L, 1050.0, 0.5f, 0.5f) + assertEquals(jc + jc, judge.judgements()) + } + + @Test + fun clickSkipsAnEarlierNoteElsewhereOnScreen() { + val judge = judgeOf(Note.SkyTap(beat(1), 0.1, 0.1, SkyButton.L, 1.0), Note.SkyTap(beat(1, 1, 20), 0.9, 0.9, SkyButton.L, 1.0)) + judge.pressButton(SkyButton.L, 1040.0, 0.9f, 0.9f) + assertEquals(1, judge.judgedCount) + assertEquals(1, judge.judgedNote(0)) + judge.releaseButton(SkyButton.L, 1041.0) + judge.pressButton(SkyButton.L, 1042.0, 0.1f, 0.1f) + assertEquals(0, judge.judgedNote(1)) + } + + @Test + fun eachButtonHasItsOwnNotes() { + val judge = judgeOf(tap(1, button = SkyButton.L), tap(1, button = SkyButton.R)) + judge.pressButton(SkyButton.R, 1000.0, 0.5f, 0.5f) + assertEquals(1, judge.judgedNote(0)) + judge.pressButton(SkyButton.L, 1000.0, 0.5f, 0.5f) + assertEquals(0, judge.judgedNote(1)) + } + + @Test + fun buttonAlreadyDownDoesNotClickAgain() { + val judge = judgeOf(tap(1)) + judge.pressButton(SkyButton.L, 500.0, 0.5f, 0.5f) + judge.pressButton(SkyButton.L, 1000.0, 0.5f, 0.5f) + assertEquals(0, judge.judgedCount) + } + + @Test + fun skyTapsCountTowardsScore() { + val judge = judgeOf(tap(1), Note.Tap(beat(2), 0)) + assertEquals(2, judge.objectCount) + judge.pressButton(SkyButton.L, 1000.0, 0.5f, 0.5f) + judge.pressLane(0, 2000.0) + judge.finish() + assertEquals(1_010_000, judge.score) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeSlideTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeSlideTest.kt new file mode 100644 index 0000000..628b89e --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeSlideTest.kt @@ -0,0 +1,276 @@ +package net.trilleo.hexium.core.judge + +import kotlin.test.Test +import kotlin.test.assertEquals +import net.trilleo.hexium.core.chart.Ease +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.SlidePoint + +class JudgeSlideTest { + /** Beat 1 to 2 (1000 to 2000 ms), straight across the middle, with ticks at 1250, 1500 and 1750 ms. */ + private val slide = Note.Slide( + SkyButton.L, + 0.06, + listOf(SlidePoint(beat(1), 0.2, 0.5, Ease.LINEAR), SlidePoint(beat(2), 0.8, 0.5, Ease.LINEAR)), + ) + + private fun onPath(ms: Double) = (0.2 + 0.6 * (ms - 1000.0) / 1000.0).toFloat() + + private fun Judge.follow(fromMs: Double, toMs: Double, stepMs: Double = 8.0, offsetY: Float = 0f) { + var time = fromMs + while (time <= toMs) { + aimSample(time, onPath(time), 0.5f + offsetY) + time += stepMs + } + } + + private val allJc = List(3) { Judgement.JUSTICE_CRITICAL } + + @Test + fun ticksOnlyWithNoHeadOrTail() { + assertEquals(3, judgeOf(slide).objectCount) + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + assertEquals(0, judge.judgedCount, "the click isn't a head") + judge.follow(1000.0, 2000.0) + judge.finish() + assertEquals(allJc, judge.judgements()) + } + + @Test + fun slideTooShortForATickGetsOneAtItsEnd() { + val short = Note.Slide( + SkyButton.L, + 0.06, + listOf(SlidePoint(beat(1), 0.2, 0.5, Ease.LINEAR), SlidePoint(beat(1, 1, 8), 0.3, 0.5, Ease.LINEAR)), + ) + val chart = JudgeChart.compile(chartOf(short)) + assertEquals(1, chart.objectCount) + val judge = Judge(chart) + judge.advanceTo(1125.0) + assertEquals(0, judge.judgedCount) + judge.advanceTo(1125.01) + assertEquals(1, judge.judgedCount) + } + + private fun tickTimes(note: Note.Slide, chart: net.trilleo.hexium.core.chart.DifficultyChart): List { + val judge = Judge(JudgeChart.compile(chart.copy(notes = listOf(note)))) + val times = ArrayList() + for (ms in 0..6000) { + val before = judge.judgedCount + judge.advanceTo(ms + 0.5) + repeat(judge.judgedCount - before) { times += ms } + } + return times + } + + @Test + fun ticksRunAcrossEveryPointOfALongerSlide() { + val long = Note.Slide( + SkyButton.L, + 0.1, + listOf( + SlidePoint(beat(1), 0.2, 0.5, Ease.LINEAR), + SlidePoint(beat(1, 3, 8), 0.3, 0.5, Ease.IN), + SlidePoint(beat(2), 0.4, 0.5, Ease.OUT), + ), + ) + assertEquals(listOf(1250, 1500, 1750), tickTimes(long, chartOf())) + } + + @Test + fun ticksFromAnOffGridStartAreCountedFromIt() { + val off = Note.Slide( + SkyButton.L, + 0.1, + listOf(SlidePoint(beat(1, 1, 8), 0.2, 0.5, Ease.LINEAR), SlidePoint(beat(1, 5, 8), 0.3, 0.5, Ease.LINEAR)), + ) + assertEquals(listOf(1375), tickTimes(off, chartOf())) + } + + @Test + fun ticksFollowBpmChanges() { + val plain = chartOf() + val changing = plain.copy(bpm = plain.bpm + net.trilleo.hexium.core.chart.BpmChange(beat(1, 1, 2), 120.0)) + assertEquals(listOf(1250, 1500, 1625), tickTimes(slide, changing)) + } + + @Test + fun neverClickedMissesEveryTick() { + val judge = judgeOf(slide) + judge.follow(1000.0, 2000.0) + judge.finish() + assertEquals(List(3) { Judgement.MISS }, judge.judgements()) + } + + @Test + fun wrongButtonMissesEveryTick() { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.R, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 2000.0) + judge.finish() + assertEquals(List(3) { Judgement.MISS }, judge.judgements()) + } + + @Test + fun crosshairOutsideTheRadiusMissesThoseTicks() { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 2000.0, offsetY = 0.07f) + judge.finish() + assertEquals(List(3) { Judgement.MISS }, judge.judgements()) + } + + @Test + fun crosshairInsideTheRadiusButOffCentreStillCounts() { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 2000.0, offsetY = 0.05f) + judge.finish() + assertEquals(allJc, judge.judgements()) + } + + @Test + fun radiusIsAFractionOfTheHeightOnBothAxes() { + fun tick(offsetX: Float): Judgement { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + var time = 1000.0 + while (time <= 2000.0) { + judge.aimSample(time, onPath(time) + offsetX, 0.5f) + time += 8.0 + } + judge.finish() + return judge.judgement(0) + } + assertEquals(Judgement.JUSTICE_CRITICAL, tick(0.029f), "x is half as far because the screen is 2:1") + assertEquals(Judgement.MISS, tick(0.031f)) + } + + /** Follows the path, then stops being held [age] ms before the 1500 ms tick. */ + private fun middleTickAfterRelease(age: Double): Judgement { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 1250.0) + judge.aimSample(1500.0 - age, onPath(1500.0 - age), 0.5f) + judge.releaseButton(SkyButton.L, 1500.0 - age) + judge.aimSample(1500.0, onPath(1500.0), 0.5f) + judge.advanceTo(1500.01) + return judge.judgement(1) + } + + @Test + fun tickWindowsAreOnTheLastHeldSample() { + assertEquals(Judgement.JUSTICE_CRITICAL, middleTickAfterRelease(50.0)) + assertEquals(Judgement.JUSTICE, middleTickAfterRelease(50.5)) + assertEquals(Judgement.JUSTICE, middleTickAfterRelease(100.0)) + assertEquals(Judgement.ATTACK, middleTickAfterRelease(100.5)) + assertEquals(Judgement.ATTACK, middleTickAfterRelease(150.0)) + assertEquals(Judgement.MISS, middleTickAfterRelease(150.5)) + } + + @Test + fun leavingAndComingBackInsideTheWindowKeepsJusticeCritical() { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 1480.0) + judge.aimSample(1490.0, onPath(1490.0), 0.9f) + judge.aimSample(1510.0, onPath(1510.0), 0.5f) + judge.follow(1518.0, 2000.0) + judge.finish() + assertEquals(allJc, judge.judgements()) + } + + @Test + fun comingBackAfterATickDoesNotHelpIt() { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 1300.0, offsetY = 0.3f) + judge.follow(1304.0, 2000.0) + judge.finish() + assertEquals(listOf(Judgement.MISS, Judgement.JUSTICE_CRITICAL, Judgement.JUSTICE_CRITICAL), judge.judgements()) + } + + @Test + fun aSampleAfterATickDoesNotHelpIt() { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, 0.9f, 0.9f) + judge.aimSample(1260.0, onPath(1260.0), 0.5f) + assertEquals(listOf(Judgement.MISS), judge.judgements()) + } + + @Test + fun theClickItselfCountsAsAnAimSample() { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1250.0, onPath(1250.0), 0.5f) + judge.advanceTo(1250.01) + assertEquals(listOf(Judgement.JUSTICE_CRITICAL), judge.judgements()) + } + + @Test + fun theCrosshairMustFollowAnEasedPath() { + val eased = Note.Slide( + SkyButton.L, + 0.03, + listOf(SlidePoint(beat(1), 0.0, 0.5, Ease.IN), SlidePoint(beat(2), 0.0, 1.0, Ease.LINEAR)), + ) + fun tick(y: Float): Judgement { + val judge = judgeOf(eased) + judge.pressButton(SkyButton.L, 1500.0, 0.0f, y) + judge.advanceTo(1500.01) + return judge.judgement(1) + } + assertEquals(Judgement.JUSTICE_CRITICAL, tick(0.625f), "eased in, the path is at 0.25 of the way at the halfway tick") + assertEquals(Judgement.MISS, tick(0.75f), "a linear path would be here") + } + + @Test + fun positionsBeforeTheFirstPointUseTheFirstPoint() { + val judge = judgeOf( + Note.Slide( + SkyButton.L, + 0.06, + listOf(SlidePoint(beat(1), 0.2, 0.5, Ease.LINEAR), SlidePoint(beat(1, 1, 8), 0.2, 0.5, Ease.LINEAR)), + ), + ) + judge.pressButton(SkyButton.L, 990.0, 0.2f, 0.5f) + judge.releaseButton(SkyButton.L, 1000.0) + judge.advanceTo(1125.01) + assertEquals(listOf(Judgement.ATTACK), judge.judgements(), "the click was on the first point, 135 ms before the tick") + } + + @Test + fun clickingASkyTapAlsoHoldsASlide() { + val judge = judgeOf(slide, Note.SkyTap(beat(1), 0.2, 0.5, SkyButton.L, 1.0)) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + assertEquals(1, judge.judgedCount) + judge.follow(1000.0, 2000.0) + judge.finish() + assertEquals(4, judge.judgedCount) + assertEquals(0, judge.count(Judgement.MISS)) + } + + @Test + fun twoSlidesAreJudgedSeparately() { + val second = slide.copy(button = SkyButton.R, points = slide.points.map { it.copy(y = 0.9) }) + val judge = judgeOf(slide, second) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + judge.pressButton(SkyButton.R, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 2000.0) + judge.finish() + assertEquals(3, judge.count(Judgement.JUSTICE_CRITICAL)) + assertEquals(3, judge.count(Judgement.MISS)) + } + + @Test + fun lowFrameRatesStillHoldASlide() { + for (step in listOf(1000.0 / 30, 1000.0 / 60, 1000.0 / 144, 1000.0 / 360)) { + val judge = judgeOf(slide) + judge.pressButton(SkyButton.L, 1000.0, onPath(1000.0), 0.5f) + judge.follow(1000.0, 2000.0, stepMs = step) + judge.finish() + assertEquals(allJc, judge.judgements(), "step $step") + } + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeTestCharts.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeTestCharts.kt new file mode 100644 index 0000000..6002cbf --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgeTestCharts.kt @@ -0,0 +1,28 @@ +package net.trilleo.hexium.core.judge + +import net.trilleo.hexium.core.chart.Beat +import net.trilleo.hexium.core.chart.BpmChange +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.MeterChange +import net.trilleo.hexium.core.chart.Note + +internal fun beat(whole: Int, num: Int = 0, den: Int = 1) = Beat(whole, num, den) + +/** At 60 BPM with no offset, beat N is N seconds, which keeps expected times readable. */ +internal fun chartOf(vararg notes: Note, difficulty: Difficulty = Difficulty.EXPERT, bpm: Double = 60.0) = DifficultyChart( + formatVersion = 1, + difficulty = difficulty, + level = 1, + laneCount = 4, + offsetMs = 0.0, + bpm = listOf(BpmChange(beat(0), bpm)), + meter = listOf(MeterChange(beat(0), 4, 4)), + notes = notes.toList(), +) + +internal fun judgeOf(vararg notes: Note, difficulty: Difficulty = Difficulty.EXPERT) = + Judge(JudgeChart.compile(chartOf(*notes, difficulty = difficulty))) + +/** What was judged, in order. */ +internal fun Judge.judgements(): List = List(judgedCount) { judgement(it) } diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgedPressTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgedPressTest.kt new file mode 100644 index 0000000..65905ff --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/JudgedPressTest.kt @@ -0,0 +1,37 @@ +package net.trilleo.hexium.core.judge + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.Beat +import net.trilleo.hexium.core.chart.BpmChange +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.Note + +class JudgedPressTest { + private val chart = DifficultyChart( + 1, + Difficulty.BASIC, + 1, + 4, + 0.0, + listOf(BpmChange(Beat(0, 0, 1), 60.0)), + emptyList(), + listOf(Note.Tap(Beat(1, 0, 1), 0), Note.Hold(Beat(2, 0, 1), Beat(3, 0, 1), 1)), + ) + + @Test + fun tellsPressesFromHoldTicks() { + val judge = Judge(JudgeChart.compile(chart)) + judge.pressLane(0, 1000.0) + judge.releaseLane(0, 1010.0) + judge.pressLane(1, 2000.0) + judge.finish() + assertEquals(5, judge.judgedCount) + assertTrue(judge.judgedIsPress(0), "the tap") + assertTrue(judge.judgedIsPress(1), "the hold's head") + for (i in 2 until judge.judgedCount) assertFalse(judge.judgedIsPress(i), "tick $i") + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/judge/ScoreTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/judge/ScoreTest.kt new file mode 100644 index 0000000..c71b5b2 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/judge/ScoreTest.kt @@ -0,0 +1,129 @@ +package net.trilleo.hexium.core.judge + +import kotlin.test.Test +import kotlin.test.assertEquals +import net.trilleo.hexium.core.chart.Note + +class ScoreTest { + private fun play(presses: List): Judge { + val notes = Array(presses.size) { Note.Tap(beat(it + 1), 0) } + val judge = judgeOf(*notes) + for (i in presses.indices) { + val offset = presses[i] ?: continue + val time = (i + 1) * 1000.0 + offset + judge.pressLane(0, time) + judge.releaseLane(0, time + 1.0) + } + judge.finish() + return judge + } + + private val jc = 0.0 + private val justice = 50.0 + private val attack = 70.0 + + @Test + fun perfectPlayScores1010000() { + val judge = play(listOf(jc, jc, jc)) + assertEquals(1_010_000, judge.score) + assertEquals(ClearLamp.ALL_JUSTICE_CRITICAL, judge.clearLamp) + } + + @Test + fun weightsAre101And100And50And0() { + assertEquals(1_010_000, play(listOf(jc)).score) + assertEquals(1_000_000, play(listOf(justice)).score) + assertEquals(500_000, play(listOf(attack)).score) + assertEquals(0, play(listOf(null)).score) + } + + @Test + fun scoreIsRoundedDown() { + assertEquals(333_333, play(listOf(justice, null, null)).score) + assertEquals(673_333, play(listOf(jc, jc, null)).score) + } + + @Test + fun everyObjectCountsTowardsTheTotal() { + val judge = judgeOf(Note.Hold(beat(1), beat(2), 0), Note.Tap(beat(3), 1)) + assertEquals(5, judge.objectCount) + judge.pressLane(0, 1000.0) + judge.finish() + assertEquals(4 * 1_010_000 / 5, judge.score, "head and three ticks out of five") + } + + @Test + fun scoreBuildsUpDuringPlay() { + val judge = judgeOf(Note.Tap(beat(1), 0), Note.Tap(beat(2), 0)) + judge.pressLane(0, 1000.0) + assertEquals(505_000, judge.score) + } + + @Test + fun comboGrowsWithEveryObjectAndAMissBreaksIt() { + val judge = judgeOf(Note.Tap(beat(1), 0), Note.Tap(beat(2), 0), Note.Tap(beat(3), 0), Note.Tap(beat(4), 0)) + judge.pressLane(0, 1000.0) + judge.releaseLane(0, 1001.0) + judge.pressLane(0, 2070.0) + judge.releaseLane(0, 2071.0) + assertEquals(2, judge.combo) + judge.advanceTo(3100.0) + assertEquals(0, judge.combo) + judge.pressLane(0, 4000.0) + assertEquals(1, judge.combo) + assertEquals(2, judge.maxCombo) + } + + @Test + fun ticksAddToCombo() { + val judge = judgeOf(Note.Hold(beat(1), beat(2), 0)) + judge.pressLane(0, 1000.0) + judge.finish() + assertEquals(4, judge.combo) + assertEquals(4, judge.maxCombo) + } + + @Test + fun countsEachJudgement() { + val judge = play(listOf(jc, jc, justice, attack, null)) + assertEquals(2, judge.count(Judgement.JUSTICE_CRITICAL)) + assertEquals(1, judge.count(Judgement.JUSTICE)) + assertEquals(1, judge.count(Judgement.ATTACK)) + assertEquals(1, judge.count(Judgement.MISS)) + } + + @Test + fun lampsFollowTheWorstJudgement() { + assertEquals(ClearLamp.ALL_JUSTICE_CRITICAL, play(listOf(jc, jc)).clearLamp) + assertEquals(ClearLamp.ALL_JUSTICE, play(listOf(jc, justice)).clearLamp) + assertEquals(ClearLamp.FULL_COMBO, play(listOf(jc, attack)).clearLamp) + assertEquals(ClearLamp.NONE, play(listOf(jc, null)).clearLamp) + } + + @Test + fun noLampBeforeTheEnd() { + val judge = judgeOf(Note.Tap(beat(1), 0), Note.Tap(beat(2), 0)) + judge.pressLane(0, 1000.0) + assertEquals(ClearLamp.NONE, judge.clearLamp) + } + + @Test + fun chartWithNoObjectsScoresZeroWithNoLamp() { + val judge = judgeOf() + judge.finish() + assertEquals(0, judge.score) + assertEquals(ClearLamp.NONE, judge.clearLamp) + } + + @Test + fun largeChartsDoNotOverflow() { + val judge = judgeOf(*Array(200_000) { Note.Tap(beat(it + 1), it % 4) }) + for (i in 0 until 200_000) { + val time = (i + 1) * 1000.0 + judge.pressLane(i % 4, time) + judge.releaseLane(i % 4, time + 1.0) + } + judge.finish() + assertEquals(1_010_000, judge.score) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/replay/PlayInputSkyTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/replay/PlayInputSkyTest.kt new file mode 100644 index 0000000..8d25853 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/replay/PlayInputSkyTest.kt @@ -0,0 +1,318 @@ +package net.trilleo.hexium.core.replay + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.Beat +import net.trilleo.hexium.core.chart.BpmChange +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.MeterChange +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.SlidePoint +import net.trilleo.hexium.core.chart.Ease +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.Judgement + +/** Sky buttons and aim through [PlayInput]: the same hold-back and pause rule as lane keys. */ +class PlayInputSkyTest { + private fun beat(whole: Int) = Beat(whole, 0, 1) + + /** At 120 BPM a beat is 500 ms: an L sky tap at 10 s mid-screen, and a flick at 12.5 s on the right. */ + private val chart = JudgeChart.compile( + DifficultyChart( + 1, Difficulty.EXPERT, 1, 4, 0.0, + listOf(BpmChange(beat(0), 120.0)), + listOf(MeterChange(beat(0), 4, 4)), + listOf(Note.SkyTap(beat(20), 0.5, 0.5, SkyButton.L, 1.0), Note.Flick(beat(25), 0.8, 0.5, 1.0)), + ), + ) + private val recorder = ReplayRecorder(chart, ByteArray(32), 0.0, 1000) + private val input = PlayInput(recorder, 4) + + private fun events(): List { + val replay = recorder.toReplay() + return (0 until replay.eventCount).map { + val position = if (replay.event(it) == ReplayEvent.LANE_DOWN || replay.event(it) == ReplayEvent.LANE_UP || replay.event(it) == ReplayEvent.BUTTON_UP) "" else " (${replay.x(it)}, ${replay.y(it)})" + "${replay.event(it)} ${replay.index(it)} at ${replay.timeMs(it)}$position" + } + } + + private fun buttonEvents(): List = events().filter { it.startsWith("BUTTON") } + + private fun pauseAndComeBack(atMs: Double): Double { + input.pause(atMs) + return input.resume() + } + + @Test + fun aClickGoesStraightToTheJudgeWithItsPosition() { + input.button(SkyButton.L, true, 10000.0, 0.5f, 0.5f) + assertEquals(Judgement.JUSTICE_CRITICAL, recorder.judge.judgement(0)) + assertEquals(listOf("BUTTON_DOWN 0 at 10000.0 (0.5, 0.5)"), events()) + assertTrue(input.isButtonDown(SkyButton.L)) + assertFalse(input.isButtonDown(SkyButton.R)) + } + + @Test + fun aReleaseIsRecordedWithoutAPosition() { + input.button(SkyButton.R, true, 1000.0, 0.1f, 0.2f) + input.button(SkyButton.R, false, 1100.0, 0.3f, 0.4f) + assertEquals(listOf("BUTTON_DOWN 1 at 1000.0 (0.1, 0.2)", "BUTTON_UP 1 at 1100.0"), events()) + assertFalse(input.isButtonDown(SkyButton.R)) + } + + @Test + fun aClickLandsAmongTheAimSamplesInTimeOrder() { + input.frame(1000.0, 0.5f, 0.5f) + input.frame(1006.0, 0.5f, 0.5f) + input.frame(1012.0, 0.5f, 0.5f) + input.button(SkyButton.L, true, 1009.0, 0.5f, 0.5f) + input.finish() + val replay = recorder.toReplay() + assertEquals(listOf(1000.0, 1006.0, 1009.0, 1012.0), (0 until replay.eventCount).map { replay.timeMs(it) }) + assertEquals(ReplayEvent.BUTTON_DOWN, replay.event(2)) + } + + @Test + fun aClickOlderThanTheHoldBackIsMovedUpAndCounted() { + input.frame(10100.0, 0.5f, 0.5f) + input.button(SkyButton.L, true, 10040.0, 0.5f, 0.5f) + assertEquals(listOf("BUTTON_DOWN 0 at 10050.0 (0.5, 0.5)"), buttonEvents()) + assertEquals(1, input.lateKeyCount) + } + + @Test + fun nothingFromTheMouseIsJudgedOrRecordedWhilePaused() { + input.pause(5000.0) + input.frame(20000.0, 0.5f, 0.5f) + input.button(SkyButton.L, true, 10000.0, 0.5f, 0.5f) + assertEquals(0, recorder.toReplay().eventCount) + assertTrue(input.isButtonDown(SkyButton.L)) + } + + @Test + fun aButtonReleasedDuringThePauseIsReleasedAtThePausePoint() { + input.button(SkyButton.L, true, 1000.0, 0.5f, 0.5f) + pauseAndComeBack(5000.0) + input.button(SkyButton.L, false, 3000.0, 0.5f, 0.5f) + input.frame(5001.0, 0.5f, 0.5f) + assertEquals(listOf("BUTTON_DOWN 0 at 1000.0 (0.5, 0.5)", "BUTTON_UP 0 at 5000.0"), buttonEvents()) + } + + @Test + fun aButtonStillDownFromTheCountdownIsPressedAtThePausePointWhereTheCrosshairWas() { + input.frame(9900.0, 0.1f, 0.1f) + pauseAndComeBack(10000.0) + input.frame(9990.0, 0.4f, 0.4f) + input.button(SkyButton.L, true, 9995.0, 0.9f, 0.9f) + input.frame(10010.0, 0.6f, 0.6f) + assertEquals(listOf("BUTTON_DOWN 0 at 10000.0 (0.5, 0.5)"), buttonEvents()) + assertEquals(Judgement.JUSTICE_CRITICAL, recorder.judge.judgement(0)) + } + + @Test + fun aClickDuringTheCountdownIsForgotten() { + pauseAndComeBack(5000.0) + input.button(SkyButton.R, true, 3000.0, 0.5f, 0.5f) + input.button(SkyButton.R, false, 3100.0, 0.5f, 0.5f) + input.frame(5001.0, 0.5f, 0.5f) + assertEquals(emptyList(), buttonEvents()) + } + + @Test + fun aClickPastThePausePointReopensAndKeepsItsOwnTimeAndPosition() { + pauseAndComeBack(5000.0) + input.button(SkyButton.L, true, 5200.0, 0.3f, 0.7f) + assertTrue(input.isOpen) + assertEquals(listOf("BUTTON_DOWN 0 at 5200.0 (0.3, 0.7)"), buttonEvents()) + } + + @Test + fun pausingRecordsWhereTheCrosshairWasAtThePausePoint() { + input.frame(1000.0, 0.2f, 0.3f) + input.pause(1012.0) + assertEquals(listOf("AIM 0 at 1000.0 (0.2, 0.3)", "AIM 0 at 1012.0 (0.2, 0.3)"), events()) + } + + @Test + fun reopeningOnAFrameRecordsTheCrosshairOnItsWayThere() { + input.frame(1000.0, 0.2f, 0.3f) + pauseAndComeBack(1012.0) + input.frame(1004.0, 0.6f, 0.7f) + input.frame(1020.0, 0.8f, 0.9f) + // Halfway in time from the last countdown frame to this one, so its movement keeps its real speed. + val replay = recorder.toReplay() + assertEquals(3, replay.eventCount) + assertEquals(1012.0, replay.timeMs(2)) + assertEquals(0.7f, replay.x(2), 1e-6f) + assertEquals(0.8f, replay.y(2), 1e-6f) + input.finish() + assertEquals("AIM 0 at 1020.0 (0.8, 0.9)", events().last()) + } + + @Test + fun reopeningOnAKeyRecordsWhereTheCrosshairWasLastSeen() { + input.frame(1000.0, 0.2f, 0.3f) + pauseAndComeBack(1012.0) + input.frame(1004.0, 0.6f, 0.7f) + input.lane(0, true, 1015.0) + assertEquals( + listOf("AIM 0 at 1000.0 (0.2, 0.3)", "AIM 0 at 1012.0 (0.2, 0.3)", "AIM 0 at 1012.0 (0.6, 0.7)", "LANE_DOWN 0 at 1015.0"), + events(), + ) + } + + @Test + fun aButtonHeldBeforeAnyAimIsNotPressedAtAMadeUpPosition() { + input.pause(1000.0) + input.button(SkyButton.L, true, 900.0, 0.5f, 0.5f) + input.resume() + input.lane(0, true, 1001.0) + assertEquals(emptyList(), buttonEvents()) + assertTrue(input.isButtonDown(SkyButton.L)) + // It reaches the judge once there's a crosshair, at the next pause point. + input.frame(1010.0, 0.4f, 0.6f) + input.pause(1020.0) + input.resume() + input.frame(1030.0, 0.4f, 0.6f) + assertEquals(listOf("BUTTON_DOWN 0 at 1020.0 (0.4, 0.6)"), buttonEvents()) + } + + @Test + fun aPauseBeforeAnyAimRecordsNoPosition() { + pauseAndComeBack(1000.0) + input.lane(0, true, 1001.0) + assertEquals(listOf("LANE_DOWN 0 at 1001.0"), events()) + } + + /** The flick is the chart's second note. */ + private fun flickResult(): Judgement? { + val judge = recorder.judge + for (i in 0 until judge.judgedCount) if (judge.judgedNote(i) == 1) return judge.judgement(i) + return null + } + + /** + * Moves the crosshair from x 0.2 to 0.9 at mid-height, across the flick, while paused. The + * countdown's frames are off the grid of the ones before, so none lands on the pause point. + */ + private fun moveAcrossTheFlickWhilePaused(input: PlayInput) { + var frameMs = 12000.0 + while (frameMs < 12460.0) { + input.frame(frameMs, 0.2f, 0.5f) + frameMs += 6.0 + } + input.pause(12460.0) + input.resume() + frameMs = 9463.0 + while (frameMs < 12460.0) { + input.frame(frameMs, 0.9f, 0.5f) + frameMs += 6.0 + } + while (frameMs < 13000.0) { + input.frame(frameMs, 0.9f, 0.5f) + frameMs += 6.0 + } + input.finish() + } + + @Test + fun movingTheMouseDuringAPauseDoesNotHitAFlick() { + moveAcrossTheFlickWhilePaused(input) + assertEquals(Judgement.MISS, flickResult()) + assertReJudgesTheSame() + } + + @Test + fun movingTheMouseDuringAPauseDoesNotHitAFlickWithAJudgementOffset() { + val offsetRecorder = ReplayRecorder(chart, ByteArray(32), 37.5, 1000) + moveAcrossTheFlickWhilePaused(PlayInput(offsetRecorder, 4)) + val judge = offsetRecorder.judge + assertEquals(Judgement.MISS, (0 until judge.judgedCount).first { judge.judgedNote(it) == 1 }.let(judge::judgement)) + } + + @Test + fun aSwipeAfterReopeningStillHitsAFlick() { + var frameMs = 12000.0 + while (frameMs < 12400.0) { + input.frame(frameMs, 0.2f, 0.5f) + frameMs += 6.0 + } + pauseAndComeBack(12400.0) + frameMs = 9403.0 + while (frameMs < 12460.0) { + input.frame(frameMs, 0.2f, 0.5f) + frameMs += 6.0 + } + var x = 0.2f + while (frameMs < 13000.0) { + input.frame(frameMs, x, 0.5f) + x = minOf(x + 0.02f, 1f) + frameMs += 6.0 + } + input.finish() + assertEquals(Judgement.JUSTICE, flickResult()) + assertReJudgesTheSame() + } + + @Test + fun aButtonLetGoWhilePausedDoesNotHoldASlideAtThePausePoint() { + // An L slide sitting mid-screen from 10 s to 12 s, with a tick every 125 ms from 10125. + val slideChart = JudgeChart.compile( + DifficultyChart( + 1, Difficulty.EXPERT, 1, 4, 0.0, + listOf(BpmChange(beat(0), 120.0)), + listOf(MeterChange(beat(0), 4, 4)), + listOf(Note.Slide(SkyButton.L, 0.06, listOf(SlidePoint(beat(20), 0.5, 0.5, Ease.LINEAR), SlidePoint(beat(24), 0.5, 0.5, Ease.LINEAR)))), + ), + ) + val slideRecorder = ReplayRecorder(slideChart, ByteArray(32), 0.0, 2000) + val play = PlayInput(slideRecorder, 4) + play.button(SkyButton.L, true, 9000.0, 0.5f, 0.5f) + var frameMs = 9000.0 + while (frameMs < 10100.0) { + // On the path until 10 s, then off it. + play.frame(frameMs, if (frameMs < 10000.0) 0.5f else 0.1f, 0.5f) + frameMs += 6.0 + } + play.pause(10100.0) + play.button(SkyButton.L, false, 8000.0, 0.5f, 0.5f) + play.resume() + frameMs = 7103.0 + while (frameMs < 10300.0) { + play.frame(frameMs, 0.5f, 0.5f) + frameMs += 6.0 + } + play.finish() + val judge = slideRecorder.judge + // Last held at 9996, so the tick at 10125 is 129 ms on. + assertEquals(Judgement.ATTACK, judge.judgement(0)) + } + + @Test + fun aPausedClickAndSwipeReJudgeTheSame() { + input.frame(9900.0, 0.5f, 0.5f) + input.button(SkyButton.L, true, 9990.0, 0.5f, 0.5f) + pauseAndComeBack(10010.0) + input.button(SkyButton.L, false, 8000.0, 0.5f, 0.5f) + input.frame(10020.0, 0.4f, 0.5f) + input.button(SkyButton.R, true, 10030.0, 0.4f, 0.5f) + input.frame(10040.0, 0.4f, 0.5f) + assertReJudgesTheSame() + } + + private fun assertReJudgesTheSame() { + input.finish() + val replayed = ReplayJudge.play(chart, ReplayFile.read(ReplayFile.write(recorder.toReplay())).replay!!) + val live = recorder.judge + assertEquals(live.score, replayed.score) + assertEquals(live.judgedCount, replayed.judgedCount) + for (i in 0 until live.judgedCount) { + assertEquals(live.judgement(i), replayed.judgement(i)) + assertEquals(live.judgedDeltaMs(i), replayed.judgedDeltaMs(i)) + } + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/replay/PlayInputTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/replay/PlayInputTest.kt new file mode 100644 index 0000000..ac81436 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/replay/PlayInputTest.kt @@ -0,0 +1,479 @@ +package net.trilleo.hexium.core.replay + +import java.lang.management.ManagementFactory +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.Beat +import net.trilleo.hexium.core.chart.BpmChange +import net.trilleo.hexium.core.chart.Difficulty +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.MeterChange +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.judge.Judge +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.Judgement + +class PlayInputTest { + private fun beat(whole: Int) = Beat(whole, 0, 1) + + /** At 120 BPM a beat is 500 ms, so beat 20 is at 10 s. */ + private val chart = JudgeChart.compile( + DifficultyChart( + 1, Difficulty.EXPERT, 1, 4, 0.0, + listOf(BpmChange(beat(0), 120.0)), + listOf(MeterChange(beat(0), 4, 4)), + listOf(Note.Tap(beat(20), 0), Note.Hold(beat(20), beat(24), 1), Note.Tap(beat(30), 2)), + ), + ) + private val recorder = ReplayRecorder(chart, ByteArray(32), 0.0, 100) + private val input = PlayInput(recorder, 4) + + private fun laneEvents(): List { + val replay = recorder.toReplay() + return (0 until replay.eventCount).filter { replay.event(it) != ReplayEvent.AIM } + .map { "${replay.event(it)} ${replay.index(it)} at ${replay.timeMs(it)}" } + } + + private fun pauseAndComeBack(atMs: Double): Double { + input.pause(atMs) + return input.resume() + } + + @Test + fun beforeAnyPauseInputGoesStraightToTheJudge() { + assertTrue(input.isOpen) + input.lane(0, true, 10000.0) + assertEquals(Judgement.JUSTICE_CRITICAL, recorder.judge.judgement(0)) + assertEquals(listOf("LANE_DOWN 0 at 10000.0"), laneEvents()) + assertTrue(input.isLaneDown(0)) + } + + @Test + fun aFrameSendsAnAimSampleAndMovesTheJudgeOn() { + input.frame(20000.0, 0.5f, 0.5f) + assertEquals(Judgement.MISS, recorder.judge.judgement(0)) + assertEquals(0, recorder.toReplay().eventCount) + input.frame(20000.0 + PlayInput.HOLD_BACK_MS, 0.5f, 0.5f) + assertEquals(1, recorder.toReplay().eventCount) + } + + @Test + fun nothingIsJudgedOrRecordedWhilePaused() { + input.pause(5000.0) + assertFalse(input.isOpen) + input.frame(20000.0, 0.5f, 0.5f) + input.lane(0, true, 10000.0) + assertEquals(0, recorder.toReplay().eventCount) + assertEquals(0, recorder.judge.judgedCount) + assertTrue(input.isLaneDown(0)) + } + + @Test + fun resumingRewindsThreeSecondsFromThePausePoint() { + assertEquals(2000.0, pauseAndComeBack(5000.0)) + assertEquals(5000.0, input.playedUntilMs) + } + + @Test + fun theRewindCanGoBeforeTheSong() { + assertEquals(-3500.0, pauseAndComeBack(-500.0)) + } + + @Test + fun nothingIsJudgedOrRecordedUntilThePausePointComesBack() { + pauseAndComeBack(5000.0) + input.frame(4999.0, 0.5f, 0.5f) + assertFalse(input.isOpen) + assertEquals(0, recorder.toReplay().eventCount) + input.frame(5000.0, 0.5f, 0.5f) + assertTrue(input.isOpen) + // Where the crosshair was when judging reopened, then that frame's own sample. + input.frame(5000.0 + PlayInput.HOLD_BACK_MS, 0.5f, 0.5f) + assertEquals(listOf(5000.0, 5000.0), allEventTimes()) + } + + @Test + fun aKeyReleasedDuringThePauseIsReleasedAtThePausePoint() { + input.lane(0, true, 1000.0) + pauseAndComeBack(5000.0) + input.lane(0, false, 3000.0) + input.frame(5001.0, 0.5f, 0.5f) + assertEquals(listOf("LANE_DOWN 0 at 1000.0", "LANE_UP 0 at 5000.0"), laneEvents()) + } + + @Test + fun aKeyStillDownFromTheCountdownIsPressedAtThePausePoint() { + input.pause(10000.0) + input.lane(0, true, 10000.0) + input.resume() + input.frame(10001.0, 0.5f, 0.5f) + assertEquals(listOf("LANE_DOWN 0 at 10000.0"), laneEvents()) + assertEquals(Judgement.JUSTICE_CRITICAL, recorder.judge.judgement(0)) + } + + @Test + fun aTapDuringTheCountdownIsForgotten() { + pauseAndComeBack(5000.0) + input.lane(0, true, 3000.0) + input.lane(0, false, 3100.0) + input.frame(5001.0, 0.5f, 0.5f) + assertEquals(emptyList(), laneEvents()) + assertFalse(input.isLaneDown(0)) + } + + @Test + fun aKeyLetGoAndPressedAgainBeforeThePausePointNeverLeftTheJudgesView() { + input.lane(1, true, 9990.0) + pauseAndComeBack(10100.0) + input.lane(1, false, 8000.0) + input.lane(1, true, 8100.0) + input.frame(10500.0, 0.5f, 0.5f) + assertEquals(listOf("LANE_DOWN 1 at 9990.0"), laneEvents()) + assertTrue(recorder.judge.combo > 0) + } + + @Test + fun anEventPastThePausePointSyncsTheKeysFirstAndKeepsItsOwnTime() { + input.lane(0, true, 1000.0) + pauseAndComeBack(5000.0) + input.lane(0, false, 3000.0) + input.lane(2, true, 5200.0) + assertTrue(input.isOpen) + assertEquals(listOf("LANE_DOWN 0 at 1000.0", "LANE_UP 0 at 5000.0", "LANE_DOWN 2 at 5200.0"), laneEvents()) + } + + @Test + fun pausingAgainDuringTheCountdownKeepsTheFirstPausePoint() { + pauseAndComeBack(5000.0) + input.frame(3000.0, 0.5f, 0.5f) + input.pause(3000.0) + assertEquals(2000.0, input.resume()) + assertEquals(5000.0, input.playedUntilMs) + } + + @Test + fun pausingAgainAfterTheCountdownMovesThePausePoint() { + pauseAndComeBack(5000.0) + input.frame(6000.0, 0.5f, 0.5f) + assertEquals(4000.0, pauseAndComeBack(7000.0)) + } + + @Test + fun aPausedPlayReJudgesToTheSameResult() { + input.lane(0, true, 10010.0) + input.lane(0, false, 10050.0) + input.lane(1, true, 10020.0) + input.frame(10500.0, 0.5f, 0.5f) + pauseAndComeBack(10600.0) + input.lane(1, false, 8000.0) + input.frame(9000.0, 0.5f, 0.5f) + input.frame(10600.0, 0.5f, 0.5f) + input.lane(1, true, 10700.0) + input.frame(15500.0, 0.5f, 0.5f) + assertReJudgesTheSame() + } + + /** A re-judge always runs to the end of the chart, so the live play must have too. */ + private fun assertReJudgesTheSame() { + input.finish() + assertSameResults(recorder.judge, ReplayJudge.play(chart, ReplayFile.read(ReplayFile.write(recorder.toReplay())).replay!!)) + } + + private fun assertSameResults(expected: Judge, actual: Judge) { + assertEquals(expected.score, actual.score) + assertEquals(expected.maxCombo, actual.maxCombo) + assertEquals(expected.judgedCount, actual.judgedCount) + for (i in 0 until expected.judgedCount) { + assertEquals(expected.judgement(i), actual.judgement(i)) + assertEquals(expected.judgedDeltaMs(i), actual.judgedDeltaMs(i)) + } + } + + @Test + fun anEventExactlyOnThePausePointReopensAndCounts() { + pauseAndComeBack(5000.0) + input.lane(2, true, 5000.0) + assertTrue(input.isOpen) + assertEquals(listOf("LANE_DOWN 2 at 5000.0"), laneEvents()) + } + + @Test + fun anEventPastThePausePointKeepsItsTimeEvenIfAFrameHasPassedIt() { + pauseAndComeBack(5000.0) + input.frame(5010.0, 0.5f, 0.5f) + input.lane(2, true, 5005.0) + assertEquals(listOf("LANE_DOWN 2 at 5005.0"), laneEvents()) + assertEquals(0, input.lateKeyCount) + } + + @Test + fun aStampFromBeforeThePausePointCountsAsThePoint() { + pauseAndComeBack(5000.0) + input.frame(5010.0, 0.5f, 0.5f) + input.lane(2, true, 4990.0) + assertEquals(listOf("LANE_DOWN 2 at 5000.0"), laneEvents()) + assertEquals(1, input.lateKeyCount) + } + + @Test + fun aPauseDuringTheLeadInReopensBeforeTheSong() { + pauseAndComeBack(-1000.0) + input.lane(0, true, -2000.0) + input.frame(-1000.0, 0.5f, 0.5f) + assertTrue(input.isOpen) + assertEquals(listOf("LANE_DOWN 0 at -1000.0"), laneEvents()) + assertReJudgesTheSame() + } + + @Test + fun severalKeysSyncTogetherAcrossTwoPauses() { + input.lane(0, true, 1000.0) + input.lane(1, true, 1000.0) + pauseAndComeBack(5000.0) + input.lane(0, false, 3000.0) + input.lane(2, true, 3100.0) + input.frame(3500.0, 0.5f, 0.5f) + input.pause(3500.0) + input.lane(1, false, 3500.0) + input.resume() + input.frame(5000.0, 0.5f, 0.5f) + assertEquals( + listOf("LANE_DOWN 0 at 1000.0", "LANE_DOWN 1 at 1000.0", "LANE_UP 0 at 5000.0", "LANE_UP 1 at 5000.0", "LANE_DOWN 2 at 5000.0"), + laneEvents(), + ) + } + + @Test + fun aHoldLetGoDuringThePauseIsTreatedAsLetGoAtThePausePoint() { + input.lane(1, true, 10000.0) + input.frame(10300.0, 0.5f, 0.5f) + pauseAndComeBack(10300.0) + input.lane(1, false, 8000.0) + input.frame(11500.0, 0.5f, 0.5f) + assertEquals(listOf("LANE_DOWN 1 at 10000.0", "LANE_UP 1 at 10300.0"), laneEvents()) + assertTrue(recorder.judge.count(Judgement.MISS) > 0) + assertReJudgesTheSame() + } + + private fun allEventTimes(): List { + val replay = recorder.toReplay() + return (0 until replay.eventCount).map { replay.timeMs(it) } + } + + @Test + fun aKeyOlderThanTheLastFrameKeepsItsOwnTime() { + input.frame(10000.0, 0.5f, 0.5f) + input.frame(10006.0, 0.5f, 0.5f) + input.lane(0, true, 10003.0) + assertEquals(listOf("LANE_DOWN 0 at 10003.0"), laneEvents()) + assertEquals(3.0, recorder.judge.judgedDeltaMs(0)) + assertEquals(0, input.lateKeyCount) + } + + @Test + fun aKeyIsJudgedStraightAwayEvenThoughSamplesAreHeldBack() { + input.frame(10000.0, 0.5f, 0.5f) + input.lane(0, true, 10000.0) + assertEquals(Judgement.JUSTICE_CRITICAL, recorder.judge.judgement(0)) + } + + @Test + fun aKeyLandsAmongTheAimSamplesInTimeOrder() { + input.frame(1000.0, 0.5f, 0.5f) + input.frame(1006.0, 0.5f, 0.5f) + input.frame(1012.0, 0.5f, 0.5f) + input.lane(3, true, 1009.0) + input.finish() + assertEquals(listOf(1000.0, 1006.0, 1009.0, 1012.0), allEventTimes()) + assertEquals(listOf("LANE_DOWN 3 at 1009.0"), laneEvents()) + } + + @Test + fun aKeyArrivingLateNearTheEndOfItsWindowIsNotMissed() { + input.frame(10120.0, 0.5f, 0.5f) + input.lane(0, true, 10080.0) + assertEquals(Judgement.ATTACK, recorder.judge.judgement(0)) + assertEquals(80.0, recorder.judge.judgedDeltaMs(0)) + } + + @Test + fun aKeyExactlyAtTheHoldBackKeepsItsTime() { + input.frame(10100.0, 0.5f, 0.5f) + input.lane(0, true, 10100.0 - PlayInput.HOLD_BACK_MS) + assertEquals(listOf("LANE_DOWN 0 at 10050.0"), laneEvents()) + assertEquals(0, input.lateKeyCount) + } + + @Test + fun aKeyOlderThanTheHoldBackIsMovedUpAndCounted() { + input.frame(10100.0, 0.5f, 0.5f) + input.lane(0, true, 10040.0) + assertEquals(listOf("LANE_DOWN 0 at 10050.0"), laneEvents()) + assertEquals(1, input.lateKeyCount) + } + + @Test + fun keysSyncedAfterAPauseAreNotCountedAsLate() { + input.lane(0, true, 1000.0) + pauseAndComeBack(5000.0) + input.lane(0, false, 3000.0) + input.frame(5001.0, 0.5f, 0.5f) + assertEquals(0, input.lateKeyCount) + } + + @Test + fun pausingSendsEverySampleStillWaitingAndOneAtThePausePoint() { + input.frame(1000.0, 0.5f, 0.5f) + input.frame(1010.0, 0.5f, 0.5f) + assertEquals(0, recorder.toReplay().eventCount) + input.pause(1012.0) + assertEquals(listOf(1000.0, 1010.0, 1012.0), allEventTimes()) + } + + @Test + fun pausingJudgesEverythingDueBeforeThePausePoint() { + input.frame(10080.0, 0.5f, 0.5f) + assertEquals(0, recorder.judge.judgedCount) + input.pause(10100.0) + assertEquals(2, recorder.judge.count(Judgement.MISS)) + } + + @Test + fun finishingSendsEverySampleStillWaiting() { + input.frame(1000.0, 0.5f, 0.5f) + input.finish() + assertEquals(listOf(1000.0), allEventTimes()) + } + + @Test + fun moreSamplesThanTheHoldBackHasRoomForAreAllKeptInOrder() { + val frames = 1000 + for (i in 0 until frames) input.frame(1000.0 + i * 0.01, 0.5f, 0.5f) + input.finish() + assertEquals(List(frames) { 1000.0 + it * 0.01 }, allEventTimes()) + } + + @Test + fun aTimeThatIsNotFiniteIsIgnoredAndBlocksNothing() { + input.frame(Double.NaN, 0.5f, 0.5f) + input.frame(1000.0, 0.5f, 0.5f) + input.finish() + assertEquals(listOf(1000.0), allEventTimes()) + } + + /** Keys reach the frame after they happened, as on a real machine, and still give what perfect delivery would. */ + @Test + fun keysArrivingAFrameLateGiveTheSameResultAsInputInTimeOrder() { + // The release lands just before a hold tick at 11875, where a moved time would change that tick's result. + val keys = listOf(Triple(0, true, 10003.0), Triple(1, true, 10011.0), Triple(0, false, 10049.0), Triple(1, false, 11874.0), Triple(2, true, 14995.0)) + for (frameLength in doubleArrayOf(6.0, 16.7, 33.3)) { + val inOrder = ReplayRecorder(chart, ByteArray(32), 0.0, 100) + var next = 0 + var frameMs = 9900.0 + while (frameMs < 15500.0) { + while (next < keys.size && keys[next].third <= frameMs) { + val (lane, down, time) = keys[next++] + if (down) inOrder.pressLane(lane, time) else inOrder.releaseLane(lane, time) + } + inOrder.aimSample(frameMs, 0.5f, 0.5f) + frameMs += frameLength + } + inOrder.finish() + + val liveRecorder = ReplayRecorder(chart, ByteArray(32), 0.0, 100) + val live = PlayInput(liveRecorder, 4) + next = 0 + frameMs = 9900.0 + while (frameMs < 15500.0) { + // A key stamped in the frame before this one is only seen now, after that frame's sample. + while (next < keys.size && keys[next].third <= frameMs - frameLength) { + val (lane, down, time) = keys[next++] + live.lane(lane, down, time) + } + live.frame(frameMs, 0.5f, 0.5f) + frameMs += frameLength + } + live.finish() + + assertEquals(0, live.lateKeyCount) + assertSameResults(inOrder.judge, liveRecorder.judge) + assertSameResults(liveRecorder.judge, ReplayJudge.play(chart, ReplayFile.read(ReplayFile.write(liveRecorder.toReplay())).replay!!)) + } + } + + @Test + fun samplesKeepTheirOwnTimesAndPositions() { + input.frame(1000.0, 0.1f, 0.2f) + input.frame(1006.0, 0.3f, 0.4f) + input.frame(1060.0, 0.5f, 0.6f) + val replay = recorder.toReplay() + assertEquals(2, replay.eventCount) + assertEquals(listOf(1000.0, 1006.0), allEventTimes()) + assertEquals(listOf(0.1f, 0.3f), listOf(replay.x(0), replay.x(1))) + assertEquals(listOf(0.2f, 0.4f), listOf(replay.y(0), replay.y(1))) + } + + @Test + fun aMovedUpKeyReJudgesTheSame() { + input.frame(10100.0, 0.5f, 0.5f) + input.lane(0, true, 10040.0) + assertEquals(1, input.lateKeyCount) + assertReJudgesTheSame() + } + + /** A swipe across a flick, with a key arriving late, must re-judge exactly and hit the flick at its crossing. */ + @Test + fun aMovingAimAndALateKeyReJudgeTheSame() { + val skyChart = JudgeChart.compile( + DifficultyChart( + 1, Difficulty.EXPERT, 1, 4, 0.0, + listOf(BpmChange(beat(0), 120.0)), + listOf(MeterChange(beat(0), 4, 4)), + listOf(Note.Tap(beat(20), 0), Note.Flick(beat(20), 0.5, 0.5, 1.0)), + ), + ) + val liveRecorder = ReplayRecorder(skyChart, ByteArray(32), 0.0, 100) + val live = PlayInput(liveRecorder, 4) + var frameMs = 9700.0 + var pressed = false + while (frameMs < 10500.0) { + if (!pressed && frameMs >= 10010.0) { + live.lane(0, true, frameMs - 8.0) + pressed = true + } + live.frame(frameMs, (0.1 + (frameMs - 9700.0) / 750.0).toFloat(), 0.5f) + frameMs += 6.0 + } + live.finish() + assertEquals(0, liveRecorder.judge.count(Judgement.MISS)) + assertSameResults(liveRecorder.judge, ReplayJudge.play(skyChart, ReplayFile.read(ReplayFile.write(liveRecorder.toReplay())).replay!!)) + } + + @Test + fun playingDoesNotAllocate() { + val threads = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + val bigRecorder = ReplayRecorder(chart, ByteArray(32), 0.0, 500_000) + val play = PlayInput(bigRecorder, 4) + val thread = Thread.currentThread().threadId() + val before = threads.getThreadAllocatedBytes(thread) + var i = 0 + while (i < 200_000) { + val time = i * 2.0 + if (i % 50 == 0) play.lane(i % 4, i % 100 == 0, time - 3.0) + if (i % 70 == 0) play.button(if (i % 140 == 0) SkyButton.L else SkyButton.R, i % 280 < 140, time - 2.0, 0.4f, 0.6f) + play.frame(time, 0.5f, 0.5f) + if (i % 10_000 == 9_999) { + play.pause(time) + play.resume() + play.frame(time, 0.5f, 0.5f) + } + i++ + } + play.finish() + val allocated = threads.getThreadAllocatedBytes(thread) - before + assertTrue(allocated < 64 * 1024, "allocated $allocated bytes") + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayFileTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayFileTest.kt new file mode 100644 index 0000000..537ddbd --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayFileTest.kt @@ -0,0 +1,167 @@ +package net.trilleo.hexium.core.replay + +import java.io.ByteArrayInputStream +import java.util.zip.GZIPInputStream +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.SkyButton + +class ReplayFileTest { + private val allKinds = listOf( + aimEvent(0, 0, 1.5, 0.25f, -0.5f), + event(1, 3, 2.0), + event(2, 3, 2.0), + aimEvent(3, 1, 3.0, 1.5f, 0.75f), + event(4, 1, 4.0), + ) + + private fun assertRejected(bytes: ByteArray, expectedInMessage: String) { + val result = ReplayFile.read(bytes) + assertNull(result.replay) + val error = assertNotNull(result.error) + assertTrue(expectedInMessage in error, error) + } + + private fun read(bytes: ByteArray): Replay { + val result = ReplayFile.read(gzip(bytes)) + assertEquals(null, result.error) + return assertNotNull(result.replay) + } + + @Test + fun readsEveryFieldFromAHandBuiltFile() { + val replay = read(fileBytes(judgeVersion = 7, offsetMs = -3.25, events = allKinds)) + assertEquals(7, replay.judgeVersion) + assertContentEquals(HASH, replay.chartHash) + assertEquals(-3.25, replay.judgementOffsetMs) + assertEquals(5, replay.eventCount) + assertEquals( + listOf(ReplayEvent.AIM, ReplayEvent.LANE_DOWN, ReplayEvent.LANE_UP, ReplayEvent.BUTTON_DOWN, ReplayEvent.BUTTON_UP), + List(5) { replay.event(it) }, + ) + assertEquals(listOf(0, 3, 3, 1, 1), List(5) { replay.index(it) }) + assertEquals(listOf(1.5, 2.0, 2.0, 3.0, 4.0), List(5) { replay.timeMs(it) }) + assertEquals(0.25f, replay.x(0)) + assertEquals(-0.5f, replay.y(0)) + assertEquals(1.5f, replay.x(3)) + assertEquals(0.75f, replay.y(3)) + } + + @Test + fun writesExactlyTheDocumentedBytes() { + val written = ReplayFile.write(read(fileBytes(events = allKinds))) + val unpacked = GZIPInputStream(ByteArrayInputStream(written)).readAllBytes() + assertContentEquals(fileBytes(events = allKinds), unpacked) + } + + @Test + fun writingIsStable() { + val replay = read(fileBytes(events = allKinds)) + assertContentEquals(ReplayFile.write(replay), ReplayFile.write(replay)) + } + + @Test + fun emptyReplayIsValid() { + assertEquals(0, read(fileBytes()).eventCount) + } + + @Test + fun numbersKeepTheirExactBits() { + val time = Math.nextUp(1234.5678) + val x = Math.nextUp(0.3f) + val once = read(fileBytes(events = listOf(aimEvent(0, 0, time, x, 0f)))) + val replay = assertNotNull(ReplayFile.read(ReplayFile.write(once)).replay) + assertEquals(time, replay.timeMs(0)) + assertEquals(x, replay.x(0)) + } + + @Test + fun notGzipIsRejected() { + assertRejected(byteArrayOf(1, 2, 3, 4), "compressed") + assertRejected(ByteArray(0), "compressed") + } + + @Test + fun truncatedGzipIsRejected() { + val bytes = gzip(fileBytes(events = allKinds)) + assertRejected(bytes.copyOf(bytes.size - 12), "compressed") + } + + @Test + fun wrongMagicIsRejected() { + assertRejected(gzip(fileBytes(magic = "HXRQ")), "not a Hexium replay") + } + + @Test + fun unknownFormatVersionIsRejected() { + assertRejected(gzip(fileBytes(formatVersion = 2)), "format version 2") + } + + @Test + fun everyTruncationIsRejected() { + val whole = fileBytes(events = allKinds) + for (length in 0 until whole.size) { + val result = ReplayFile.read(gzip(whole.copyOf(length))) + assertNull(result.replay, "cut to $length bytes") + assertNotNull(result.error) + } + } + + @Test + fun bytesAfterTheLastEventAreRejected() { + assertRejected(gzip(fileBytes(events = allKinds) + 0), "after the last event") + assertRejected(gzip(fileBytes(eventCount = 4, events = allKinds)), "after the last event") + } + + @Test + fun unknownEventKindIsRejected() { + assertRejected(gzip(fileBytes(events = listOf(event(5, 0, 1.0)))), "kind 5") + } + + @Test + fun badIndexIsRejected() { + assertRejected(gzip(fileBytes(events = listOf(aimEvent(3, 2, 1.0, 0f, 0f)))), "button") + assertRejected(gzip(fileBytes(events = listOf(event(4, 2, 1.0)))), "button") + assertRejected(gzip(fileBytes(events = listOf(aimEvent(0, 1, 1.0, 0f, 0f)))), "index") + } + + @Test + fun timesGoingDownAreRejected() { + assertRejected(gzip(fileBytes(events = listOf(event(1, 0, 2.0), event(2, 0, 1.0)))), "event 1") + assertEquals(2, read(fileBytes(events = listOf(event(1, 0, 2.0), event(2, 0, 2.0)))).eventCount) + } + + @Test + fun numbersThatAreNotFiniteAreRejected() { + assertRejected(gzip(fileBytes(events = listOf(event(1, 0, Double.NaN)))), "event 0") + assertRejected(gzip(fileBytes(events = listOf(event(1, 0, Double.POSITIVE_INFINITY)))), "event 0") + assertRejected(gzip(fileBytes(events = listOf(aimEvent(0, 0, 1.0, Float.NaN, 0f)))), "event 0") + assertRejected(gzip(fileBytes(events = listOf(aimEvent(3, 0, 1.0, 0f, Float.POSITIVE_INFINITY)))), "event 0") + assertRejected(gzip(fileBytes(offsetMs = Double.NaN)), "offset") + } + + @Test + fun aHugeClaimedEventCountIsRejectedWithoutAllocatingForIt() { + assertRejected(gzip(fileBytes(eventCount = Int.MAX_VALUE)), "events") + assertRejected(gzip(fileBytes(eventCount = -1)), "events") + assertRejected(gzip(fileBytes(eventCount = Replay.MAX_EVENTS + 1)), "events") + assertRejected(gzip(fileBytes(eventCount = Replay.MAX_EVENTS)), "cut short") + } + + @Test + fun aSmallFileThatUnpacksIntoSomethingHugeIsRejected() { + val bomb = gzip(ByteArray(200 * 1024 * 1024)) + assertTrue(bomb.size < 1024 * 1024) + assertRejected(bomb, "too large") + } + + @Test + fun buttonIndexesMatchSkyButton() { + assertEquals(0, SkyButton.L.ordinal) + assertEquals(1, SkyButton.R.ordinal) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayPlayTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayPlayTest.kt new file mode 100644 index 0000000..cf8e1f4 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayPlayTest.kt @@ -0,0 +1,250 @@ +package net.trilleo.hexium.core.replay + +import java.lang.management.ManagementFactory +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import net.trilleo.hexium.core.chart.ChartParser +import net.trilleo.hexium.core.chart.ChartWriter +import net.trilleo.hexium.core.chart.DifficultyChart +import net.trilleo.hexium.core.chart.Ease +import net.trilleo.hexium.core.chart.Note +import net.trilleo.hexium.core.chart.SkyButton +import net.trilleo.hexium.core.chart.SlidePoint +import net.trilleo.hexium.core.judge.ClearLamp +import net.trilleo.hexium.core.judge.Judge +import net.trilleo.hexium.core.judge.JudgeChart +import net.trilleo.hexium.core.judge.Judgement +import net.trilleo.hexium.core.judge.JudgementConfig +import net.trilleo.hexium.core.judge.beat +import net.trilleo.hexium.core.judge.chartOf + +class ReplayPlayTest { + private val chart: DifficultyChart = chartOf( + Note.Tap(beat(1), 0), + Note.Hold(beat(2), beat(3), 1), + Note.SkyTap(beat(3), 0.25, 0.5, SkyButton.R, 1.0), + Note.Slide( + SkyButton.L, + 0.1, + listOf(SlidePoint(beat(4), 0.2, 0.5, Ease.IN_OUT), SlidePoint(beat(5), 0.8, 0.5, Ease.LINEAR)), + ), + Note.Flick(beat(6), 0.5, 0.5, 1.0), + Note.Tap(beat(7), 3), + ) + private val chartFile = ChartWriter.writeDifficulty(chart).toByteArray() + + private fun results(judge: Judge) = List(judge.judgedCount) { + Triple(judge.judgedNote(it), judge.judgement(it), judge.judgedDeltaMs(it)) + } + + /** Plays the chart at a frame rate, a little off perfect, with [offsetMs] of input lag. */ + private fun play(recorder: ReplayRecorder, offsetMs: Double, stepMs: Double) { + fun aim(ms: Double): Float = when { + ms < 4000.0 -> 0.2f + ms < 5000.0 -> { + val t = (ms - 4000.0) / 1000.0 + (0.2 + 0.6 * t * t * (3 - 2 * t)).toFloat() + } + else -> (0.1 + (ms - 5900.0) * 0.004).toFloat() + } + val inputs = sortedMapOf( + 1010.0 to 0, 1050.0 to 1, 2000.0 to 2, 3000.0 to 3, 3050.0 to 4, + 3990.0 to 5, 5000.0 to 6, 7070.0 to 7, + ) + var time = 900.0 + while (time < 7400.0) { + val raw = time + offsetMs + for ((inputMs, id) in inputs.subMap(time, time + stepMs)) { + val at = inputMs + offsetMs + when (id) { + 0 -> recorder.pressLane(0, at) + 1 -> recorder.releaseLane(0, at) + 2 -> recorder.pressLane(1, at) + 3 -> { + recorder.releaseLane(1, at) + recorder.pressButton(SkyButton.R, at, 0.25f, 0.5f) + } + 4 -> recorder.releaseButton(SkyButton.R, at) + 5 -> recorder.pressButton(SkyButton.L, at, 0.2f, 0.5f) + 6 -> recorder.releaseButton(SkyButton.L, at) + 7 -> recorder.pressLane(3, at) + } + } + recorder.aimSample(raw, aim(time), 0.5f) + recorder.advanceTo(raw) + time += stepMs + } + recorder.finish() + } + + private fun recorded(offsetMs: Double = 0.0, stepMs: Double = 1000.0 / 240): ReplayRecorder { + val recorder = ReplayRecorder(JudgeChart.compile(chart), Replay.hashOf(chartFile), offsetMs, 2_000) + play(recorder, offsetMs, stepMs) + return recorder + } + + @Test + fun theScriptedPlayIsAFairTest() { + val judge = recorded().judge + assertEquals(judge.objectCount, judge.judgedCount) + assertEquals(0, judge.count(Judgement.MISS), results(judge).toString()) + assertEquals(1, judge.count(Judgement.ATTACK), "the last tap is 70 ms late") + assertEquals(ClearLamp.FULL_COMBO, judge.clearLamp) + } + + @Test + fun rePlayingGivesExactlyTheSameResults() { + val recorder = recorded() + val replayed = ReplayJudge.play(JudgeChart.compile(chart), recorder.toReplay()) + assertEquals(results(recorder.judge), results(replayed)) + assertEquals(recorder.judge.score, replayed.score) + assertEquals(recorder.judge.maxCombo, replayed.maxCombo) + assertEquals(recorder.judge.clearLamp, replayed.clearLamp) + } + + @Test + fun aReplayThroughTheFileGivesExactlyTheSameResults() { + val recorder = recorded(offsetMs = 17.25) + val read = assertNotNull(ReplayFile.read(ReplayFile.write(recorder.toReplay())).replay) + val replayed = ReplayJudge.play(JudgeChart.compile(chart), read) + assertEquals(results(recorder.judge), results(replayed)) + } + + @Test + fun offsetBShiftsEveryInputAndLeavesTheResultAlone() { + val plain = recorded().judge + val shifted = recorded(offsetMs = 40.0).judge + assertEquals(plain.score, shifted.score) + assertEquals(plain.judgements(), shifted.judgements()) + val replayed = ReplayJudge.play(JudgeChart.compile(chart), recorded(offsetMs = 40.0).toReplay()) + assertEquals(plain.score, replayed.score) + } + + private fun Judge.judgements() = List(judgedCount) { judgement(it) } + + @Test + fun offsetBAppliesToTapsDirectly() { + val judge = Judge(JudgeChart.compile(chartOf(Note.Tap(beat(1), 0))), 30.0) + judge.pressLane(0, 1030.0) + assertEquals(0.0, judge.judgedDeltaMs(0)) + val expiring = Judge(JudgeChart.compile(chartOf(Note.Tap(beat(1), 0))), 30.0) + expiring.advanceTo(1113.0) + assertEquals(0, expiring.judgedCount) + expiring.advanceTo(1114.0) + assertEquals(1, expiring.judgedCount) + } + + @Test + fun recorderKeepsHeaderFields() { + val replay = recorded(offsetMs = 5.0).toReplay() + assertEquals(JudgementConfig.JUDGE_VERSION, replay.judgeVersion) + assertContentEquals(Replay.hashOf(chartFile), replay.chartHash) + assertEquals(5.0, replay.judgementOffsetMs) + assertTrue(replay.eventCount > 1000) + } + + @Test + fun anEventOlderThanTheCurrentTimeIsRecordedAsNow() { + val chart = chartOf(Note.Tap(beat(1), 0)) + val recorder = ReplayRecorder(JudgeChart.compile(chart), Replay.hashOf(ByteArray(0)), 0.0, 4) + recorder.advanceTo(1020.0) + recorder.pressLane(0, 1000.0) + recorder.aimSample(900.0, 0f, 0f) + val replay = recorder.toReplay() + assertEquals(1020.0, replay.timeMs(0)) + assertEquals(1020.0, replay.timeMs(1)) + val replayed = ReplayJudge.play(JudgeChart.compile(chart), replay) + assertEquals(recorder.judge.judgedDeltaMs(0), replayed.judgedDeltaMs(0)) + } + + @Test + fun theRecorderGrowsPastItsExpectedSize() { + val recorder = ReplayRecorder(JudgeChart.compile(chartOf()), Replay.hashOf(ByteArray(0)), 0.0, 1) + for (i in 0 until 1000) recorder.aimSample(i.toDouble(), 0f, 0f) + assertEquals(1000, recorder.toReplay().eventCount) + assertEquals(999.0, recorder.toReplay().timeMs(999)) + } + + @Test + fun theRecorderStopsAtTheEventLimitAndStillJudges() { + val chart = chartOf(Note.Tap(beat(1), 0)) + val recorder = ReplayRecorder(JudgeChart.compile(chart), Replay.hashOf(ByteArray(0)), 0.0, 4) + for (i in 0 until Replay.MAX_EVENTS + 5) recorder.aimSample(0.0, 0f, 0f) + assertEquals(true, recorder.isFull) + recorder.pressLane(0, 1000.0) + assertEquals(1, recorder.judge.judgedCount) + assertEquals(Replay.MAX_EVENTS, recorder.toReplay().eventCount) + } + + @Test + fun recordingWithinItsExpectedSizeDoesNotAllocate() { + val threads = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + val chart = chartOf(Note.Tap(beat(1), 0)) + val recorder = ReplayRecorder(JudgeChart.compile(chart), Replay.hashOf(ByteArray(0)), 0.0, 400_000) + val thread = Thread.currentThread().threadId() + val before = threads.getThreadAllocatedBytes(thread) + var i = 0 + while (i < 100_000) { + val time = i.toDouble() + recorder.pressLane(0, time) + recorder.aimSample(time, 0.5f, 0.5f) + recorder.releaseLane(0, time) + recorder.advanceTo(time) + i++ + } + val allocated = threads.getThreadAllocatedBytes(thread) - before + assertTrue(allocated < 64 * 1024, "allocated $allocated bytes") + } + + // Re-judging from the files the server would hold. + + @Test + fun rejudgeGivesTheRecordedResult() { + val recorder = recorded() + val result = ReplayJudge.rejudge(chartFile, recorder.toReplay()) + assertNull(result.error) + val judge = assertNotNull(result.judge) + assertEquals(recorder.judge.score, judge.score) + assertEquals(results(recorder.judge), results(judge)) + } + + @Test + fun rejudgeRejectsAReplayOfADifferentChart() { + val other = ChartWriter.writeDifficulty(chart.copy(level = 2)).toByteArray() + val result = ReplayJudge.rejudge(other, recorded().toReplay()) + assertNull(result.judge) + assertTrue("different chart" in result.error.orEmpty(), result.error) + } + + @Test + fun rejudgeRejectsAnotherJudgeVersion() { + val bytes = fileBytes(judgeVersion = JudgementConfig.JUDGE_VERSION + 1, hash = Replay.hashOf(chartFile)) + val replay = assertNotNull(ReplayFile.read(gzip(bytes)).replay) + val result = ReplayJudge.rejudge(chartFile, replay) + assertNull(result.judge) + assertTrue("judge version" in result.error.orEmpty(), result.error) + } + + @Test + fun rejudgeRejectsABrokenChartFile() { + val broken = "{ not json".toByteArray() + val replay = assertNotNull(ReplayFile.read(gzip(fileBytes(hash = Replay.hashOf(broken), judgeVersion = JudgementConfig.JUDGE_VERSION))).replay) + val result = ReplayJudge.rejudge(broken, replay) + assertNull(result.judge) + assertTrue("chart" in result.error.orEmpty(), result.error) + } + + @Test + fun rejudgeRejectsAChartTheValidatorRejects() { + val invalid = ChartWriter.writeDifficulty(chart.copy(level = 0)).toByteArray() + assertNotNull(ChartParser.parseDifficulty(String(invalid)).value) + val replay = assertNotNull(ReplayFile.read(gzip(fileBytes(hash = Replay.hashOf(invalid), judgeVersion = JudgementConfig.JUDGE_VERSION))).replay) + val result = ReplayJudge.rejudge(invalid, replay) + assertNull(result.judge) + assertTrue("level" in result.error.orEmpty(), result.error) + } +} diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayTestSupport.kt b/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayTestSupport.kt new file mode 100644 index 0000000..c5be3e8 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/replay/ReplayTestSupport.kt @@ -0,0 +1,41 @@ +package net.trilleo.hexium.core.replay + +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.util.zip.GZIPOutputStream + +internal val HASH = ByteArray(32) { it.toByte() } + +internal fun gzip(bytes: ByteArray): ByteArray { + val out = ByteArrayOutputStream() + GZIPOutputStream(out).use { it.write(bytes) } + return out.toByteArray() +} + +/** Builds a file's contents by hand, separately from the writer, so these tests pin the format itself. */ +internal fun fileBytes( + magic: String = "HXRP", + formatVersion: Int = 1, + judgeVersion: Int = 1, + hash: ByteArray = HASH, + offsetMs: Double = 12.5, + eventCount: Int? = null, + events: List = emptyList(), +): ByteArray { + val size = events.sumOf { it.size } + val buffer = ByteBuffer.allocate(magic.length + 4 + 4 + hash.size + 8 + 4 + size) + buffer.put(magic.toByteArray(Charsets.US_ASCII)) + buffer.putInt(formatVersion) + buffer.putInt(judgeVersion) + buffer.put(hash) + buffer.putDouble(offsetMs) + buffer.putInt(eventCount ?: events.size) + for (event in events) buffer.put(event) + return buffer.array() +} + +internal fun event(kind: Int, index: Int, timeMs: Double): ByteArray = + ByteBuffer.allocate(9).put(((kind shl 4) or index).toByte()).putDouble(timeMs).array() + +internal fun aimEvent(kind: Int, index: Int, timeMs: Double, x: Float, y: Float): ByteArray = + ByteBuffer.allocate(17).put(((kind shl 4) or index).toByte()).putDouble(timeMs).putFloat(x).putFloat(y).array() diff --git a/core/src/test/kotlin/net/trilleo/hexium/core/settings/PlayerSettingsTest.kt b/core/src/test/kotlin/net/trilleo/hexium/core/settings/PlayerSettingsTest.kt new file mode 100644 index 0000000..82439e4 --- /dev/null +++ b/core/src/test/kotlin/net/trilleo/hexium/core/settings/PlayerSettingsTest.kt @@ -0,0 +1,98 @@ +package net.trilleo.hexium.core.settings + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class PlayerSettingsTest { + private val custom = PlayerSettings(noteSpeed = 60, visualOffsetMs = -35, judgementOffsetMs = 42, mouseSensitivity = 150, playFov = 80, viewAssist = 3) + + @Test + fun whatIsWrittenReadsBackTheSame() { + assertEquals(custom, PlayerSettings.parse(PlayerSettings.write(custom))) + } + + @Test + fun brokenTextGivesTheDefaults() { + assertEquals(PlayerSettings(), PlayerSettings.parse("not json {")) + assertEquals(PlayerSettings(), PlayerSettings.parse("[1, 2]")) + assertEquals(PlayerSettings(), PlayerSettings.parse("")) + } + + @Test + fun aMissingOrBrokenFieldGivesItsDefaultAndKeepsTheOthers() { + val parsed = PlayerSettings.parse("""{ "noteSpeed": "fast", "visualOffsetMs": 20 }""") + assertEquals(PlayerSettings(visualOffsetMs = 20), parsed) + } + + @Test + fun unknownFieldsAreIgnored() { + assertEquals(PlayerSettings(noteSpeed = 30), PlayerSettings.parse("""{ "noteSpeed": 30, "later": { "a": 1 } }""")) + } + + @Test + fun valuesOutOfRangeComeBackInRange() { + val parsed = PlayerSettings.parse("""{ "noteSpeed": 100000, "visualOffsetMs": -100000, "judgementOffsetMs": 100000 }""") + assertEquals(PlayerSettings.MAX_NOTE_SPEED, parsed.noteSpeed) + assertEquals(-PlayerSettings.MAX_OFFSET_MS, parsed.visualOffsetMs) + assertEquals(PlayerSettings.MAX_OFFSET_MS, parsed.judgementOffsetMs) + } + + @Test + fun aNumberTooBigForAnIntComesBackInRange() { + assertEquals(PlayerSettings.MAX_NOTE_SPEED, PlayerSettings.parse("""{ "noteSpeed": 99999999999999 }""").noteSpeed) + } + + @Test + fun aFractionalNumberIsRounded() { + assertEquals(PlayerSettings(judgementOffsetMs = 13), PlayerSettings.parse("""{ "judgementOffsetMs": 12.6 }""")) + } + + @Test + fun anythingThatIsNotAFiniteNumberGivesTheDefault() { + for (value in listOf("NaN", "Infinity", "-Infinity", "true", "null", "word", "\"30\"", "1e400", "[1]", "{}")) { + assertEquals(PlayerSettings(visualOffsetMs = 5), PlayerSettings.parse("{ \"noteSpeed\": $value, \"visualOffsetMs\": 5 }"), value) + } + } + + @Test + fun extremeNestingGivesTheDefaults() { + assertEquals(PlayerSettings(), PlayerSettings.parse("[".repeat(200_000))) + } + + @Test + fun inRangeClampsEveryField() { + val clamped = PlayerSettings(noteSpeed = 1, visualOffsetMs = 9999, judgementOffsetMs = -9999, mouseSensitivity = 1, playFov = 500, viewAssist = -2).inRange() + val expected = PlayerSettings( + PlayerSettings.MIN_NOTE_SPEED, PlayerSettings.MAX_OFFSET_MS, -PlayerSettings.MAX_OFFSET_MS, + PlayerSettings.MIN_MOUSE_SENSITIVITY, PlayerSettings.MAX_PLAY_FOV, 0, + ) + assertEquals(expected, clamped) + val high = PlayerSettings(mouseSensitivity = 9999, playFov = 1, viewAssist = 99).inRange() + assertEquals(PlayerSettings(mouseSensitivity = PlayerSettings.MAX_MOUSE_SENSITIVITY, playFov = PlayerSettings.MIN_PLAY_FOV, viewAssist = PlayerSettings.MAX_VIEW_ASSIST), high) + } + + /** A new player turns the camera as vanilla does, sees vanilla's default view, and gets no help. */ + @Test + fun comfortSettingsStartAsVanilla() { + val settings = PlayerSettings() + assertEquals(100, settings.mouseSensitivity) + assertEquals(70, settings.playFov) + assertEquals(0, settings.viewAssist) + } + + /** A file from before these settings existed still reads, with their defaults. */ + @Test + fun anOlderFileGetsTheComfortDefaults() { + val parsed = PlayerSettings.parse("""{ "formatVersion": 1, "noteSpeed": 40, "visualOffsetMs": 5, "judgementOffsetMs": -5 }""") + assertEquals(PlayerSettings(noteSpeed = 40, visualOffsetMs = 5, judgementOffsetMs = -5), parsed) + } + + @Test + fun comfortSettingsAreWrittenUnderTheirNames() { + val text = PlayerSettings.write(custom) + for (name in listOf("\"mouseSensitivity\": 150", "\"playFov\": 80", "\"viewAssist\": 3")) { + assertTrue(name in text, "$name in $text") + } + } +} diff --git a/core/src/test/resources/golden/attack_advanced.expected b/core/src/test/resources/golden/attack_advanced.expected new file mode 100644 index 0000000..885bf12 --- /dev/null +++ b/core/src/test/resources/golden/attack_advanced.expected @@ -0,0 +1,32 @@ +score 746206 +lamp FULL_COMBO +maxCombo 29 +0 ATTACK 90.0 +1 ATTACK 90.0 +2 ATTACK 90.0 +3 ATTACK 90.0 +4 ATTACK 90.0 +5 ATTACK 90.0 +6 ATTACK 90.0 +6 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +7 ATTACK 90.0 +6 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +8 ATTACK 90.0 +6 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +9 ATTACK 90.0 +6 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +11 ATTACK 90.0 +12 ATTACK 90.0 +13 ATTACK 90.0 +14 ATTACK 90.0 +15 ATTACK 90.0 diff --git a/core/src/test/resources/golden/attack_advanced.hexreplay b/core/src/test/resources/golden/attack_advanced.hexreplay new file mode 100644 index 0000000..91a6c5d Binary files /dev/null and b/core/src/test/resources/golden/attack_advanced.hexreplay differ diff --git a/core/src/test/resources/golden/ground_only_expert.expected b/core/src/test/resources/golden/ground_only_expert.expected new file mode 100644 index 0000000..3f46cf4 --- /dev/null +++ b/core/src/test/resources/golden/ground_only_expert.expected @@ -0,0 +1,56 @@ +score 762264 +lamp NONE +maxCombo 10 +0 JUSTICE_CRITICAL 0.0 +1 JUSTICE_CRITICAL 0.0 +2 JUSTICE_CRITICAL 0.0 +3 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 MISS NaN +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +6 MISS NaN +4 JUSTICE_CRITICAL 0.0 +7 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +8 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +9 MISS NaN +9 MISS NaN +9 MISS NaN +10 JUSTICE_CRITICAL 0.0 +9 MISS NaN +9 MISS NaN +11 JUSTICE_CRITICAL 0.0 +9 MISS NaN +9 MISS NaN +12 MISS NaN +14 JUSTICE_CRITICAL 0.0 +13 MISS NaN +14 JUSTICE_CRITICAL 0.0 +15 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +16 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +17 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +18 JUSTICE_CRITICAL 0.0 +19 JUSTICE_CRITICAL 0.0 +20 MISS NaN +21 JUSTICE_CRITICAL 0.0 +22 JUSTICE_CRITICAL 0.0 +23 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +25 MISS NaN +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +27 JUSTICE_CRITICAL 0.0 diff --git a/core/src/test/resources/golden/ground_only_expert.hexreplay b/core/src/test/resources/golden/ground_only_expert.hexreplay new file mode 100644 index 0000000..9c654ac Binary files /dev/null and b/core/src/test/resources/golden/ground_only_expert.hexreplay differ diff --git a/core/src/test/resources/golden/late_basic.expected b/core/src/test/resources/golden/late_basic.expected new file mode 100644 index 0000000..cfea757 --- /dev/null +++ b/core/src/test/resources/golden/late_basic.expected @@ -0,0 +1,32 @@ +score 1004827 +lamp ALL_JUSTICE +maxCombo 29 +0 JUSTICE 50.0 +1 JUSTICE 50.0 +2 JUSTICE 50.0 +3 JUSTICE 50.0 +4 JUSTICE 50.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 JUSTICE 50.0 +6 JUSTICE 50.0 +7 JUSTICE 50.0 +8 JUSTICE 50.0 +9 JUSTICE 50.0 +10 JUSTICE 50.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +11 JUSTICE 50.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +12 JUSTICE 50.0 +13 JUSTICE 50.0 +14 JUSTICE 50.0 diff --git a/core/src/test/resources/golden/late_basic.hexreplay b/core/src/test/resources/golden/late_basic.hexreplay new file mode 100644 index 0000000..2be575f Binary files /dev/null and b/core/src/test/resources/golden/late_basic.hexreplay differ diff --git a/core/src/test/resources/golden/none_advanced.expected b/core/src/test/resources/golden/none_advanced.expected new file mode 100644 index 0000000..f34a909 --- /dev/null +++ b/core/src/test/resources/golden/none_advanced.expected @@ -0,0 +1,32 @@ +score 0 +lamp NONE +maxCombo 0 +0 MISS NaN +1 MISS NaN +2 MISS NaN +3 MISS NaN +4 MISS NaN +5 MISS NaN +6 MISS NaN +6 MISS NaN +6 MISS NaN +7 MISS NaN +6 MISS NaN +6 MISS NaN +8 MISS NaN +6 MISS NaN +6 MISS NaN +9 MISS NaN +6 MISS NaN +10 MISS NaN +10 MISS NaN +10 MISS NaN +10 MISS NaN +10 MISS NaN +10 MISS NaN +10 MISS NaN +11 MISS NaN +12 MISS NaN +13 MISS NaN +14 MISS NaN +15 MISS NaN diff --git a/core/src/test/resources/golden/none_advanced.hexreplay b/core/src/test/resources/golden/none_advanced.hexreplay new file mode 100644 index 0000000..b76f3c6 Binary files /dev/null and b/core/src/test/resources/golden/none_advanced.hexreplay differ diff --git a/core/src/test/resources/golden/perfect_advanced.expected b/core/src/test/resources/golden/perfect_advanced.expected new file mode 100644 index 0000000..06d01c5 --- /dev/null +++ b/core/src/test/resources/golden/perfect_advanced.expected @@ -0,0 +1,32 @@ +score 1010000 +lamp ALL_JUSTICE_CRITICAL +maxCombo 29 +0 JUSTICE_CRITICAL 0.0 +1 JUSTICE_CRITICAL 0.0 +2 JUSTICE_CRITICAL 0.0 +3 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +7 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +8 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +9 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +11 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +13 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +15 JUSTICE_CRITICAL 0.0 diff --git a/core/src/test/resources/golden/perfect_advanced.hexreplay b/core/src/test/resources/golden/perfect_advanced.hexreplay new file mode 100644 index 0000000..89b80c8 Binary files /dev/null and b/core/src/test/resources/golden/perfect_advanced.hexreplay differ diff --git a/core/src/test/resources/golden/perfect_basic.expected b/core/src/test/resources/golden/perfect_basic.expected new file mode 100644 index 0000000..504c4c8 --- /dev/null +++ b/core/src/test/resources/golden/perfect_basic.expected @@ -0,0 +1,32 @@ +score 1010000 +lamp ALL_JUSTICE_CRITICAL +maxCombo 29 +0 JUSTICE_CRITICAL 0.0 +1 JUSTICE_CRITICAL 0.0 +2 JUSTICE_CRITICAL 0.0 +3 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +7 JUSTICE_CRITICAL 0.0 +8 JUSTICE_CRITICAL 0.0 +9 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +11 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +13 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 diff --git a/core/src/test/resources/golden/perfect_basic.hexreplay b/core/src/test/resources/golden/perfect_basic.hexreplay new file mode 100644 index 0000000..501bcc6 Binary files /dev/null and b/core/src/test/resources/golden/perfect_basic.hexreplay differ diff --git a/core/src/test/resources/golden/perfect_expert.expected b/core/src/test/resources/golden/perfect_expert.expected new file mode 100644 index 0000000..a8a5d36 --- /dev/null +++ b/core/src/test/resources/golden/perfect_expert.expected @@ -0,0 +1,56 @@ +score 1010000 +lamp ALL_JUSTICE_CRITICAL +maxCombo 53 +0 JUSTICE_CRITICAL 0.0 +1 JUSTICE_CRITICAL 0.0 +2 JUSTICE_CRITICAL 0.0 +3 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +6 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +7 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +8 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +9 JUSTICE_CRITICAL -4.02298850574698 +9 JUSTICE_CRITICAL -6.89655172413768 +9 JUSTICE_CRITICAL -1.43678160919535 +10 JUSTICE_CRITICAL 0.0 +9 JUSTICE_CRITICAL -4.31034482758605 +9 JUSTICE_CRITICAL -7.18390804597675 +11 JUSTICE_CRITICAL 0.0 +9 JUSTICE_CRITICAL -1.7241379310348748 +9 JUSTICE_CRITICAL -4.59770114942512 +12 JUSTICE_CRITICAL -13.333331182085203 +13 JUSTICE_CRITICAL -38.83535726520722 +14 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +15 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +16 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +17 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +18 JUSTICE_CRITICAL 0.0 +19 JUSTICE_CRITICAL 0.0 +20 JUSTICE_CRITICAL 0.0 +21 JUSTICE_CRITICAL 0.0 +22 JUSTICE_CRITICAL 0.0 +23 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +25 JUSTICE_CRITICAL -19.99999413545993 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +27 JUSTICE_CRITICAL 0.0 diff --git a/core/src/test/resources/golden/perfect_expert.hexreplay b/core/src/test/resources/golden/perfect_expert.hexreplay new file mode 100644 index 0000000..1aa08ce Binary files /dev/null and b/core/src/test/resources/golden/perfect_expert.hexreplay differ diff --git a/core/src/test/resources/golden/recorded/test-pattern-advanced-20261104-225251.expected b/core/src/test/resources/golden/recorded/test-pattern-advanced-20261104-225251.expected new file mode 100644 index 0000000..156bb86 --- /dev/null +++ b/core/src/test/resources/golden/recorded/test-pattern-advanced-20261104-225251.expected @@ -0,0 +1,471 @@ +score 1003141 +lamp NONE +maxCombo 259 +0 JUSTICE -54.41719924403333 +1 JUSTICE -44.24715822199232 +2 JUSTICE -33.895165461472516 +3 JUSTICE -38.652088864888356 +4 JUSTICE_CRITICAL 1.0876921515268805 +5 JUSTICE -48.62954572864328 +6 JUSTICE_CRITICAL -23.6426845720689 +7 JUSTICE_CRITICAL -13.647579679074624 +8 JUSTICE -48.934353423938774 +9 JUSTICE_CRITICAL -8.599200932261738 +10 JUSTICE -43.54526637490926 +11 JUSTICE_CRITICAL -18.812421992718555 +12 JUSTICE_CRITICAL 6.63809360000414 +12 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +12 JUSTICE_CRITICAL 0.0 +13 JUSTICE_CRITICAL -23.810245840517382 +14 JUSTICE -43.13811334425918 +15 JUSTICE_CRITICAL 1.1169896488481754 +16 JUSTICE_CRITICAL -8.496457725497748 +17 JUSTICE_CRITICAL -13.640934034512611 +18 JUSTICE_CRITICAL -0.17210255205827707 +19 JUSTICE_CRITICAL 6.415008366175243 +20 JUSTICE_CRITICAL 0.8172421088565898 +21 JUSTICE_CRITICAL 0.052182118324708426 +22 JUSTICE_CRITICAL 21.511371425791367 +23 JUSTICE -43.308481884612775 +24 JUSTICE_CRITICAL -18.364682627703587 +25 JUSTICE_CRITICAL 21.53663631636664 +26 JUSTICE_CRITICAL 16.609122311134342 +26 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +26 JUSTICE_CRITICAL 0.0 +27 JUSTICE_CRITICAL -14.073345445704035 +28 JUSTICE_CRITICAL -18.679487694607815 +29 JUSTICE_CRITICAL -8.853250594976998 +30 JUSTICE_CRITICAL 16.22440047132477 +31 JUSTICE_CRITICAL -18.221356955011288 +32 JUSTICE_CRITICAL -22.479814061403886 +33 JUSTICE_CRITICAL 1.1525204247627698 +34 JUSTICE_CRITICAL -19.42309063279754 +35 JUSTICE_CRITICAL -8.409902094535937 +36 JUSTICE_CRITICAL -13.86421411370975 +37 JUSTICE_CRITICAL -3.7207052801168174 +38 JUSTICE_CRITICAL -8.808243803196092 +39 JUSTICE_CRITICAL 16.130887334715226 +40 JUSTICE_CRITICAL -15.721112785588048 +40 JUSTICE_CRITICAL 0.0 +40 JUSTICE_CRITICAL 0.0 +40 JUSTICE_CRITICAL 0.0 +40 JUSTICE_CRITICAL 0.0 +40 JUSTICE_CRITICAL 0.0 +40 JUSTICE_CRITICAL 0.0 +40 JUSTICE_CRITICAL 0.0 +41 JUSTICE_CRITICAL 11.429486247030582 +42 JUSTICE_CRITICAL 6.795696192195464 +43 JUSTICE_CRITICAL 1.7259278762867325 +44 JUSTICE_CRITICAL 11.571999703464826 +45 JUSTICE 36.452831964019424 +46 JUSTICE -58.0997842336692 +47 JUSTICE_CRITICAL -32.567671028213226 +48 JUSTICE -38.0679352644147 +49 JUSTICE_CRITICAL 1.2497703140907106 +50 JUSTICE_CRITICAL -0.25114817111898446 +51 JUSTICE_CRITICAL -8.744935329934378 +52 JUSTICE_CRITICAL -13.86738848828827 +53 JUSTICE_CRITICAL -3.8388153467676602 +54 JUSTICE_CRITICAL 6.903348323427053 +54 JUSTICE_CRITICAL 0.0 +54 JUSTICE_CRITICAL 0.0 +54 JUSTICE_CRITICAL 0.0 +54 JUSTICE_CRITICAL 0.0 +54 JUSTICE_CRITICAL 0.0 +54 JUSTICE_CRITICAL 0.0 +54 JUSTICE_CRITICAL 0.0 +55 JUSTICE_CRITICAL 6.6421377562001 +56 JUSTICE_CRITICAL -28.48242991905863 +57 JUSTICE -33.42432880002161 +58 JUSTICE_CRITICAL -21.65913553574501 +59 JUSTICE_CRITICAL 16.548168247914873 +60 JUSTICE_CRITICAL 11.627327396585315 +61 JUSTICE_CRITICAL -8.571310096012894 +62 JUSTICE_CRITICAL 5.262468567285396 +63 JUSTICE -48.429655501218804 +64 JUSTICE_CRITICAL -8.618143049177888 +65 JUSTICE_CRITICAL 16.443536998580385 +66 JUSTICE 41.3066538612693 +67 JUSTICE_CRITICAL -9.152074778219685 +68 JUSTICE_CRITICAL -12.297014601084811 +68 JUSTICE_CRITICAL 0.0 +68 JUSTICE_CRITICAL 0.0 +68 JUSTICE_CRITICAL 0.0 +68 JUSTICE_CRITICAL 0.0 +68 JUSTICE_CRITICAL 0.0 +68 JUSTICE_CRITICAL 0.0 +68 JUSTICE_CRITICAL 0.0 +69 JUSTICE_CRITICAL 1.3304526390929823 +70 JUSTICE_CRITICAL -18.39621712747612 +71 JUSTICE_CRITICAL -23.635116858160472 +72 JUSTICE -44.00459015554952 +73 JUSTICE -33.90472324143775 +74 JUSTICE_CRITICAL -9.133650500982185 +75 JUSTICE_CRITICAL 1.2791194265155355 +76 JUSTICE_CRITICAL -3.8621636059469893 +77 JUSTICE -38.601920688357495 +78 JUSTICE_CRITICAL 1.2422493721096544 +79 JUSTICE_CRITICAL 11.453308595904673 +80 JUSTICE -38.05671192709997 +81 JUSTICE_CRITICAL 3.2390150957508013 +82 JUSTICE_CRITICAL 14.886272473304416 +82 JUSTICE_CRITICAL 0.0 +82 JUSTICE_CRITICAL 0.0 +82 JUSTICE_CRITICAL 0.0 +82 JUSTICE_CRITICAL 0.0 +82 JUSTICE_CRITICAL 0.0 +82 JUSTICE_CRITICAL 0.0 +82 JUSTICE_CRITICAL 0.0 +83 JUSTICE -33.39734743543522 +84 JUSTICE_CRITICAL -21.162064488162287 +85 JUSTICE_CRITICAL 32.058983540518966 +86 JUSTICE_CRITICAL -18.486151863835403 +87 JUSTICE_CRITICAL 6.67671457851975 +88 JUSTICE_CRITICAL 20.44972207104729 +89 JUSTICE_CRITICAL -17.700666400931368 +90 JUSTICE_CRITICAL 6.774512936855899 +91 JUSTICE_CRITICAL 31.832469039596617 +92 JUSTICE_CRITICAL -12.79169770005683 +93 JUSTICE_CRITICAL 21.87695868276205 +94 JUSTICE_CRITICAL 19.68418462244881 +95 JUSTICE_CRITICAL -33.2422913913324 +96 JUSTICE_CRITICAL 21.756632339864154 +96 JUSTICE_CRITICAL 0.0 +96 JUSTICE_CRITICAL 0.0 +96 JUSTICE_CRITICAL 0.0 +96 JUSTICE_CRITICAL 0.0 +96 JUSTICE_CRITICAL 0.0 +96 JUSTICE_CRITICAL 0.0 +96 JUSTICE_CRITICAL 0.0 +97 JUSTICE_CRITICAL -8.134666274345363 +98 JUSTICE_CRITICAL 31.585464303570916 +99 JUSTICE -33.76328097564692 +100 JUSTICE -38.59987218400056 +101 JUSTICE_CRITICAL -7.72500968354143 +102 JUSTICE_CRITICAL -19.088222831167514 +103 JUSTICE_CRITICAL -23.900184047757648 +104 JUSTICE_CRITICAL 15.673832874657819 +105 JUSTICE_CRITICAL -19.186229815677507 +106 JUSTICE_CRITICAL -8.942944854185043 +107 JUSTICE_CRITICAL -10.715109215656412 +108 JUSTICE_CRITICAL -18.997904742056562 +109 JUSTICE_CRITICAL 6.455470423316001 +110 JUSTICE_CRITICAL 16.740203862391354 +110 JUSTICE_CRITICAL 0.0 +110 JUSTICE_CRITICAL 0.0 +110 JUSTICE_CRITICAL 0.0 +110 JUSTICE_CRITICAL 0.0 +110 JUSTICE_CRITICAL 0.0 +110 JUSTICE_CRITICAL 0.0 +110 JUSTICE_CRITICAL 0.0 +111 JUSTICE -58.35775646831462 +112 JUSTICE -33.36040759108437 +113 JUSTICE -38.11271986666543 +114 JUSTICE -57.889906913784216 +115 JUSTICE_CRITICAL -18.045457433574484 +116 JUSTICE_CRITICAL -4.843053277989384 +117 JUSTICE_CRITICAL -28.49911083855841 +118 JUSTICE_CRITICAL -18.502835416875314 +119 JUSTICE -38.993493330519414 +120 JUSTICE_CRITICAL 16.538024318870157 +121 JUSTICE_CRITICAL -3.737058958853595 +122 JUSTICE -38.96287182686501 +123 JUSTICE_CRITICAL -13.826244624637184 +124 JUSTICE -33.83034621490515 +124 JUSTICE_CRITICAL 0.0 +124 JUSTICE_CRITICAL 0.0 +124 JUSTICE_CRITICAL 0.0 +124 JUSTICE_CRITICAL 0.0 +124 JUSTICE_CRITICAL 0.0 +124 JUSTICE_CRITICAL 0.0 +124 JUSTICE_CRITICAL 0.0 +125 JUSTICE -33.876842129131546 +126 JUSTICE -38.08844909835898 +127 JUSTICE_CRITICAL -28.621859405669966 +128 JUSTICE_CRITICAL -18.83425887703197 +129 JUSTICE_CRITICAL 6.8062008996348595 +130 JUSTICE_CRITICAL 1.1029396796802757 +131 JUSTICE_CRITICAL -3.6647235628624912 +132 JUSTICE_CRITICAL 21.58817939675646 +133 JUSTICE_CRITICAL -28.389697790626087 +134 JUSTICE_CRITICAL -18.557971293776063 +135 JUSTICE_CRITICAL 6.532792702229926 +136 JUSTICE_CRITICAL 16.303800558074727 +137 JUSTICE_CRITICAL 11.161893530588713 +138 JUSTICE_CRITICAL -8.365284990082728 +138 JUSTICE_CRITICAL 0.0 +138 JUSTICE_CRITICAL 0.0 +138 JUSTICE_CRITICAL 0.0 +138 JUSTICE_CRITICAL 0.0 +138 JUSTICE_CRITICAL 0.0 +138 JUSTICE_CRITICAL 0.0 +138 JUSTICE_CRITICAL 0.0 +139 JUSTICE_CRITICAL -8.04269396768359 +140 JUSTICE_CRITICAL -13.225581123813754 +141 JUSTICE_CRITICAL 4.409515800492954 +142 JUSTICE_CRITICAL 6.830391581635922 +143 JUSTICE_CRITICAL -12.756867030868307 +144 JUSTICE_CRITICAL 11.242063305035117 +145 JUSTICE_CRITICAL -8.408897148183314 +146 JUSTICE_CRITICAL -27.947517451029853 +147 JUSTICE 57.04236681989278 +148 JUSTICE -48.65455640461005 +149 JUSTICE -42.832481156263384 +150 JUSTICE_CRITICAL -17.645827260654187 +151 JUSTICE_CRITICAL 7.389696760146762 +152 JUSTICE_CRITICAL 6.661095405637752 +152 JUSTICE_CRITICAL 0.0 +152 JUSTICE_CRITICAL 0.0 +152 JUSTICE_CRITICAL 0.0 +152 JUSTICE_CRITICAL 0.0 +152 JUSTICE_CRITICAL 0.0 +152 JUSTICE_CRITICAL 0.0 +152 JUSTICE_CRITICAL 0.0 +153 JUSTICE_CRITICAL 32.137722187966574 +154 JUSTICE_CRITICAL -17.763502323257853 +155 JUSTICE_CRITICAL -22.848631700049737 +156 JUSTICE_CRITICAL -27.52262209446053 +157 JUSTICE_CRITICAL -17.476171408809023 +158 JUSTICE_CRITICAL 7.064392739062896 +159 JUSTICE 46.931417058440275 +160 JUSTICE_CRITICAL 16.667205130535876 +161 JUSTICE_CRITICAL -8.21581948918174 +162 JUSTICE_CRITICAL -12.847197360024438 +163 JUSTICE_CRITICAL -32.77763219176268 +164 JUSTICE_CRITICAL -22.873742289681104 +165 JUSTICE_CRITICAL -12.798140512342798 +166 JUSTICE_CRITICAL -0.6584412435477134 +166 JUSTICE_CRITICAL 0.0 +166 JUSTICE_CRITICAL 0.0 +166 JUSTICE_CRITICAL 0.0 +166 JUSTICE_CRITICAL 0.0 +166 JUSTICE_CRITICAL 0.0 +166 JUSTICE_CRITICAL 0.0 +166 JUSTICE_CRITICAL 0.0 +167 JUSTICE_CRITICAL -32.94711307580292 +168 JUSTICE -37.40366470429581 +169 JUSTICE_CRITICAL 2.087923956074519 +170 JUSTICE_CRITICAL -17.844005723673035 +171 JUSTICE_CRITICAL -23.063847704732325 +172 JUSTICE_CRITICAL 17.269361548882443 +173 JUSTICE_CRITICAL -18.054579730538535 +174 JUSTICE_CRITICAL -23.078760141608655 +175 MISS NaN +176 JUSTICE_CRITICAL -3.334399845218286 +177 JUSTICE_CRITICAL -8.169724837076501 +178 JUSTICE_CRITICAL 1.7636209796619369 +179 JUSTICE_CRITICAL -17.931536187476013 +180 JUSTICE_CRITICAL -7.76659535348881 +180 JUSTICE_CRITICAL 0.0 +180 JUSTICE_CRITICAL 0.0 +180 JUSTICE_CRITICAL 0.0 +180 JUSTICE_CRITICAL 0.0 +180 JUSTICE_CRITICAL 0.0 +180 JUSTICE_CRITICAL 0.0 +180 JUSTICE_CRITICAL 0.0 +181 ATTACK -83.21942908140772 +182 JUSTICE_CRITICAL 6.424672459019348 +183 JUSTICE_CRITICAL 11.699919733699062 +184 JUSTICE_CRITICAL 6.583542422042228 +185 JUSTICE_CRITICAL 1.5744610690744594 +186 JUSTICE 42.14954827679321 +187 JUSTICE_CRITICAL -22.88674822660687 +188 JUSTICE_CRITICAL 17.10108097003831 +189 JUSTICE_CRITICAL 26.842203666790738 +190 JUSTICE_CRITICAL -22.902469659456983 +191 JUSTICE_CRITICAL -10.017658641780145 +192 JUSTICE_CRITICAL -33.19788163117482 +193 JUSTICE_CRITICAL -8.249917898880085 +194 JUSTICE 47.98522545215383 +194 JUSTICE_CRITICAL 0.0 +194 JUSTICE_CRITICAL 0.0 +194 JUSTICE_CRITICAL 0.0 +194 JUSTICE_CRITICAL 0.0 +194 JUSTICE_CRITICAL 0.0 +194 JUSTICE_CRITICAL 0.0 +194 JUSTICE_CRITICAL 0.0 +195 JUSTICE_CRITICAL -26.953893371275626 +196 JUSTICE_CRITICAL -3.221250975460862 +197 JUSTICE_CRITICAL -23.074081993487198 +198 JUSTICE_CRITICAL -28.057588662879425 +199 JUSTICE_CRITICAL -18.618618516935385 +200 JUSTICE_CRITICAL -8.323854917369317 +201 JUSTICE_CRITICAL -27.58250675353338 +202 JUSTICE_CRITICAL -3.277194493537536 +203 JUSTICE_CRITICAL -8.171043534617638 +204 JUSTICE_CRITICAL -12.892811168858316 +205 JUSTICE_CRITICAL -33.20139431513962 +206 JUSTICE_CRITICAL -23.299940963901463 +207 JUSTICE_CRITICAL 1.6585230877390131 +208 JUSTICE_CRITICAL -18.550458563113352 +208 JUSTICE_CRITICAL 0.0 +208 JUSTICE_CRITICAL 0.0 +208 JUSTICE_CRITICAL 0.0 +208 JUSTICE_CRITICAL 0.0 +208 JUSTICE_CRITICAL 0.0 +208 JUSTICE_CRITICAL 0.0 +208 JUSTICE_CRITICAL 0.0 +209 JUSTICE_CRITICAL -33.282746650947956 +210 JUSTICE -53.28150287628523 +211 JUSTICE -43.31632052849454 +212 JUSTICE -48.510989977483405 +213 JUSTICE -38.51849402251537 +214 JUSTICE -55.20923702638538 +215 JUSTICE_CRITICAL -18.238298984637368 +216 JUSTICE -53.2283944668452 +217 JUSTICE_CRITICAL -28.367532800373738 +218 JUSTICE -33.64755871849775 +219 JUSTICE -53.51077934805653 +220 JUSTICE_CRITICAL 16.152299298439175 +221 JUSTICE_CRITICAL -18.894671968431794 +222 JUSTICE_CRITICAL 6.470774995497777 +222 JUSTICE_CRITICAL 0.0 +222 JUSTICE_CRITICAL 0.0 +222 JUSTICE_CRITICAL 0.0 +222 JUSTICE_CRITICAL 0.0 +222 JUSTICE_CRITICAL 0.0 +222 JUSTICE_CRITICAL 0.0 +222 JUSTICE_CRITICAL 0.0 +223 JUSTICE_CRITICAL -23.469322118151467 +224 JUSTICE_CRITICAL -13.333239365936606 +225 JUSTICE_CRITICAL -3.4832444220228354 +226 JUSTICE_CRITICAL -23.61391674722836 +227 JUSTICE_CRITICAL -28.115554142161272 +228 JUSTICE_CRITICAL -17.99216302385321 +229 JUSTICE_CRITICAL -7.874395588529296 +230 JUSTICE -57.78049367773929 +231 JUSTICE_CRITICAL -33.10149436141364 +232 JUSTICE_CRITICAL 6.740062964614481 +233 JUSTICE_CRITICAL 32.24223296082346 +234 JUSTICE_CRITICAL -18.03575555063435 +235 JUSTICE 36.979753779975 +236 JUSTICE -57.564092423563125 +236 JUSTICE_CRITICAL 0.0 +236 JUSTICE_CRITICAL 0.0 +236 JUSTICE_CRITICAL 0.0 +236 JUSTICE_CRITICAL 0.0 +236 JUSTICE_CRITICAL 0.0 +236 JUSTICE_CRITICAL 0.0 +236 JUSTICE_CRITICAL 0.0 +237 JUSTICE -42.89766291322303 +238 JUSTICE_CRITICAL -32.95535519643454 +239 JUSTICE -37.97969462524634 +240 JUSTICE_CRITICAL 5.623607687040931 +241 JUSTICE_CRITICAL 12.007641532021808 +242 JUSTICE_CRITICAL 6.950989018107066 +243 JUSTICE_CRITICAL 17.143705157272052 +244 JUSTICE_CRITICAL -17.502900778577896 +245 JUSTICE_CRITICAL 6.782464268122567 +246 JUSTICE -43.01296987157548 +247 JUSTICE_CRITICAL 12.275124117790256 +248 JUSTICE_CRITICAL 7.172526766749797 +249 JUSTICE -54.68148012610618 +250 JUSTICE_CRITICAL -32.96708349196706 +250 JUSTICE_CRITICAL 0.0 +250 JUSTICE_CRITICAL 0.0 +250 JUSTICE_CRITICAL 0.0 +250 JUSTICE_CRITICAL 0.0 +250 JUSTICE_CRITICAL 0.0 +250 JUSTICE_CRITICAL 0.0 +250 JUSTICE_CRITICAL 0.0 +251 JUSTICE_CRITICAL -33.11324650730239 +252 JUSTICE_CRITICAL -7.967819897952722 +253 JUSTICE_CRITICAL -27.809681511949748 +254 JUSTICE_CRITICAL -17.145618496841053 +255 JUSTICE_CRITICAL 22.498417994997 +256 JUSTICE_CRITICAL -12.741703187959502 +257 JUSTICE_CRITICAL 12.314510222669924 +258 JUSTICE -53.09424246981507 +259 JUSTICE_CRITICAL -28.255312657158356 +260 JUSTICE_CRITICAL -18.021775119414087 +261 JUSTICE_CRITICAL -23.171020337031223 +262 JUSTICE_CRITICAL -7.279386070178589 +263 JUSTICE -44.99381692754105 +264 JUSTICE_CRITICAL -7.813442422571825 +264 JUSTICE_CRITICAL 0.0 +264 JUSTICE_CRITICAL 0.0 +264 JUSTICE_CRITICAL 0.0 +264 JUSTICE_CRITICAL 0.0 +264 JUSTICE_CRITICAL 0.0 +264 JUSTICE_CRITICAL 0.0 +264 JUSTICE_CRITICAL 0.0 +265 JUSTICE -53.26053890422918 +266 JUSTICE_CRITICAL 5.730540577147622 +267 JUSTICE_CRITICAL -32.730522060533985 +268 JUSTICE_CRITICAL -7.591248622746207 +269 JUSTICE_CRITICAL -12.958258926490089 +270 JUSTICE_CRITICAL -32.98035081187845 +271 JUSTICE_CRITICAL -21.799094549700385 +272 JUSTICE_CRITICAL 17.205565578507958 +273 JUSTICE -62.92632875114214 +274 JUSTICE_CRITICAL -23.367730488535017 +275 JUSTICE -43.50747503674938 +276 JUSTICE -63.4843039160769 +277 JUSTICE_CRITICAL -8.397808766487287 +278 JUSTICE_CRITICAL -28.310222144791624 +278 JUSTICE_CRITICAL 0.0 +278 JUSTICE_CRITICAL 0.0 +278 JUSTICE_CRITICAL 0.0 +278 JUSTICE_CRITICAL 0.0 +278 JUSTICE_CRITICAL -38.8645976302505 +278 JUSTICE_CRITICAL 0.0 +278 JUSTICE_CRITICAL 0.0 +279 JUSTICE -43.29438730125548 +280 JUSTICE_CRITICAL -18.203006157884374 +281 JUSTICE_CRITICAL -23.392905775050167 +282 JUSTICE_CRITICAL -13.232029819890158 +283 JUSTICE_CRITICAL -18.107474233052926 +284 JUSTICE_CRITICAL -5.464743812277447 +285 JUSTICE_CRITICAL 16.584924555470934 +286 ATTACK 71.8675240581506 +287 JUSTICE_CRITICAL 6.8859597193368245 +288 JUSTICE_CRITICAL -13.11770837122458 +289 JUSTICE_CRITICAL 11.902330493467161 +290 JUSTICE -38.44884653441841 +291 JUSTICE_CRITICAL -13.324687875167001 +292 JUSTICE_CRITICAL 30.290075930999592 +292 JUSTICE_CRITICAL 0.0 +292 JUSTICE_CRITICAL 0.0 +292 JUSTICE_CRITICAL -18.1104697889823 +292 JUSTICE_CRITICAL 0.0 +292 JUSTICE_CRITICAL 0.0 +292 JUSTICE_CRITICAL -18.230746535555227 +292 JUSTICE_CRITICAL 0.0 +293 JUSTICE_CRITICAL 11.679122979112435 +294 JUSTICE_CRITICAL -8.563453729817411 +295 JUSTICE -43.24716148333391 +296 JUSTICE -44.040378246456385 +297 JUSTICE -53.61380827170797 +298 JUSTICE_CRITICAL -13.660925612726714 +299 JUSTICE_CRITICAL -0.6857116901664995 +300 JUSTICE_CRITICAL 6.161679340992123 +301 JUSTICE_CRITICAL -28.399621493474115 +302 JUSTICE_CRITICAL -18.33571146556642 +303 JUSTICE_CRITICAL 21.722046001261333 +304 JUSTICE_CRITICAL 16.57471893314505 +305 JUSTICE_CRITICAL 27.019977391435532 +306 JUSTICE 36.635734979383415 +306 JUSTICE_CRITICAL 0.0 +306 JUSTICE_CRITICAL 0.0 +306 JUSTICE_CRITICAL 0.0 +306 JUSTICE_CRITICAL 0.0 +306 JUSTICE_CRITICAL 0.0 +306 JUSTICE_CRITICAL 0.0 +306 JUSTICE_CRITICAL 0.0 +307 JUSTICE -37.903834664815804 +308 ATTACK -72.91556271445006 +309 JUSTICE -63.42399353600922 +310 JUSTICE_CRITICAL -6.668366006837459 +311 JUSTICE_CRITICAL 1.1033882715564687 +312 JUSTICE_CRITICAL 30.186023695510812 +313 JUSTICE_CRITICAL 6.913242873037234 diff --git a/core/src/test/resources/golden/recorded/test-pattern-advanced-20261104-225251.hexreplay b/core/src/test/resources/golden/recorded/test-pattern-advanced-20261104-225251.hexreplay new file mode 100644 index 0000000..194978a Binary files /dev/null and b/core/src/test/resources/golden/recorded/test-pattern-advanced-20261104-225251.hexreplay differ diff --git a/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-214057.expected b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-214057.expected new file mode 100644 index 0000000..99341b1 --- /dev/null +++ b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-214057.expected @@ -0,0 +1,32 @@ +score 938620 +lamp FULL_COMBO +maxCombo 29 +0 JUSTICE -64.08283283919673 +1 ATTACK -97.98093661986468 +2 JUSTICE_CRITICAL -30.25201526382034 +3 JUSTICE_CRITICAL -30.281834853641612 +4 JUSTICE_CRITICAL -26.11290235101933 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 JUSTICE_CRITICAL -25.696456403013144 +6 ATTACK -75.96909237911404 +7 ATTACK -76.0043569055324 +8 JUSTICE_CRITICAL -26.058744212119564 +9 JUSTICE_CRITICAL -15.202754839046975 +10 JUSTICE_CRITICAL -20.53252251721733 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +11 ATTACK 84.95707868178943 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL -40.7852578201946 +12 JUSTICE_CRITICAL -26.10836458331505 +13 JUSTICE -54.862518313177134 +14 JUSTICE -36.1036934650856 diff --git a/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-214057.hexreplay b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-214057.hexreplay new file mode 100644 index 0000000..7fd6248 Binary files /dev/null and b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-214057.hexreplay differ diff --git a/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-224108.expected b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-224108.expected new file mode 100644 index 0000000..a25a539 --- /dev/null +++ b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-224108.expected @@ -0,0 +1,32 @@ +score 1008965 +lamp ALL_JUSTICE +maxCombo 29 +0 JUSTICE_CRITICAL 0.933689763887287 +1 JUSTICE 43.91046764766679 +2 JUSTICE_CRITICAL -23.488740735698684 +3 JUSTICE_CRITICAL -28.48628893251498 +4 JUSTICE_CRITICAL -18.770895311134154 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 JUSTICE_CRITICAL 10.15670733888146 +6 JUSTICE_CRITICAL -10.250749876573536 +7 JUSTICE_CRITICAL 16.436597797965987 +8 JUSTICE_CRITICAL 26.780555586216906 +9 JUSTICE_CRITICAL 5.18015418187133 +10 JUSTICE_CRITICAL 3.7140301123399695 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +11 JUSTICE_CRITICAL -19.50088198989397 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +10 JUSTICE_CRITICAL 0.0 +12 JUSTICE 35.04590358581845 +13 JUSTICE -34.81583820636297 +14 JUSTICE_CRITICAL -4.768318561556953 diff --git a/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-224108.hexreplay b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-224108.hexreplay new file mode 100644 index 0000000..430a113 Binary files /dev/null and b/core/src/test/resources/golden/recorded/test-pattern-basic-20261104-224108.hexreplay differ diff --git a/core/src/test/resources/golden/sloppy_expert.expected b/core/src/test/resources/golden/sloppy_expert.expected new file mode 100644 index 0000000..c82a9c2 --- /dev/null +++ b/core/src/test/resources/golden/sloppy_expert.expected @@ -0,0 +1,56 @@ +score 778490 +lamp FULL_COMBO +maxCombo 53 +0 ATTACK 70.0 +1 ATTACK 70.0 +2 ATTACK 70.0 +3 ATTACK 70.0 +4 ATTACK 70.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +5 ATTACK 70.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +6 ATTACK 70.0 +4 JUSTICE_CRITICAL 0.0 +4 JUSTICE_CRITICAL 0.0 +7 ATTACK 70.0 +4 JUSTICE_CRITICAL 0.0 +8 ATTACK 70.0 +9 JUSTICE_CRITICAL -4.02298850574698 +9 JUSTICE_CRITICAL -6.89655172413768 +9 JUSTICE_CRITICAL -1.43678160919535 +9 JUSTICE_CRITICAL -4.31034482758605 +10 ATTACK 70.0 +9 JUSTICE_CRITICAL -7.18390804597675 +9 JUSTICE_CRITICAL -1.7241379310348748 +11 ATTACK 70.0 +9 JUSTICE_CRITICAL -4.59770114942512 +12 JUSTICE 136.6666688179148 +13 JUSTICE 111.16464273479278 +14 ATTACK 70.0 +14 JUSTICE_CRITICAL 0.0 +14 JUSTICE_CRITICAL 0.0 +15 ATTACK 70.0 +14 JUSTICE_CRITICAL 0.0 +16 ATTACK 70.0 +14 JUSTICE_CRITICAL 0.0 +17 ATTACK 70.0 +14 JUSTICE_CRITICAL 0.0 +18 ATTACK 70.0 +19 ATTACK 70.0 +20 ATTACK 70.0 +21 ATTACK 70.0 +22 ATTACK 70.0 +23 ATTACK 70.0 +24 ATTACK 70.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +25 JUSTICE 130.00000586454007 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +24 JUSTICE_CRITICAL 0.0 +26 ATTACK 70.0 +27 ATTACK 70.0 diff --git a/core/src/test/resources/golden/sloppy_expert.hexreplay b/core/src/test/resources/golden/sloppy_expert.hexreplay new file mode 100644 index 0000000..b2aba79 Binary files /dev/null and b/core/src/test/resources/golden/sloppy_expert.hexreplay differ diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 38018f6..9e8501c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -4,16 +4,18 @@ The music's playback position is the only clock. Minecraft's 20 TPS tick (50 ms) ## Toolchain -Minecraft 26.3 is unobfuscated, so no mappings are needed. The project uses Gradle 9.8.2, Fabric Loom 1.19, Fabric Loader 0.20.1, Fabric API 0.165.0+26.3, Kotlin 2.4.21 and Fabric Language Kotlin 1.14.2, on Java 25. `gradle.properties` and the Gradle wrapper are the source of truth for versions; update this line when they change. Hexium is written in Kotlin with Gradle Kotlin DSL build scripts. The mod depends on Fabric Language Kotlin, which players install alongside Fabric API. Mixins stay in Java: each one is a few lines that call into Kotlin. +Minecraft 26.3 is unobfuscated, so no mappings are needed. The project uses Gradle 9.8.2, Fabric Loom 1.19, Fabric Loader 0.20.1, Fabric API 0.165.0+26.3, Kotlin 2.4.21, Fabric Language Kotlin 1.14.2 and kotlinx-serialization-json 1.11.0, on Java 25. `gradle.properties` and the Gradle wrapper are the source of truth for versions; update this line when they change. Hexium is written in Kotlin with Gradle Kotlin DSL build scripts. The mod depends on Fabric Language Kotlin, which players install alongside Fabric API. Mixins stay in Java: each one is a few lines that call into Kotlin. + +`core` reads and writes chart JSON with kotlinx-serialization-json's tree API (`JsonElement`), without the compiler plugin or annotations on the model, so the parser can report every error in a file with its path. The mod doesn't bundle the library: Fabric Language Kotlin already ships it, so `kotlinx_serialization_version` in `gradle.properties` must stay on the version Fabric Language Kotlin bundles. When bumping Fabric Language Kotlin, also raise its minimum version in `fabric.mod.json`. ## Gradle modules | Module | Depends on | Holds | | --- | --- | --- | -| `core` | nothing (plain Kotlin/JVM, Java 25) | Chart model, parser, validator, timing map (BPM changes → ms), judge engine, scoring, replay format | +| `core` | only kotlinx-serialization-json (plain Kotlin/JVM, Java 25) | Chart model, parser, validator, timing map (BPM changes → ms), judge engine, scoring, replay format | | `mod` | `core`, Fabric API, Fabric Language Kotlin | Menu, session, stage loading, audio clock, input capture, rendering, HUD, screens, editor, network client | | `server` | `core` | Backend API, auth, chart storage, leaderboards, replay verifier | -| `tools` | `core` | CLI: chart lint, chart convert, replay re-judge (used by CI and developers) | +| `tools` | `core` | CLI: chart lint, replay re-judge, replay dump (used by CI and developers) | Only `core` knows the rules. The mod, the server and the `tools` CLI all depend on it. @@ -32,30 +34,44 @@ Hexium is client-only (`"environment": "client"` in `fabric.mod.json`), so nearl ## Session gating ("normal worlds are untouched") - The title screen gets one extra button that opens the mod's menu. That menu is the only place a `HexiumSession` is ever created. -- Every mixin and event hook starts with `if (!HexiumSession.active()) return;`. Joining a normal world or server means no session, so vanilla behaviour stays as it was. -- The stage is a template world bundled in the mod. It's copied into the mod's own folder (for example `.minecraft/hexium/stages/`), not `saves/`, so it never shows up in the vanilla world list. It's loaded on the integrated server with frozen game rules: no daylight cycle, no mobs, no random ticks, no weather. -- The player entity is placed on the stand spot and locked. Gameplay never depends on the server; the world is just scenery. +- Every mixin and event hook starts with `if (!HexiumSession.active()) return;`, except the title screen button, which only adds that button. Joining a normal world or server means no session, so vanilla behaviour stays as it was. +- The stage is a flat black floor with a small platform for the player, made in code (`StageWorld`) and created fresh for each session in the mod's own folder, `.minecraft/hexium/stages/`, not `saves/`, so it never shows up in the vanilla world list. Making it in code means a Minecraft update can't ask to upgrade it. Chart-authored stages may bring template worlds in Milestone 8. It runs on the integrated server, with its rules frozen once the player joins: no daylight cycle, mobs, random ticks or weather. +- The player is in adventure mode on Peaceful, placed on the stand spot on top of the platform. Gameplay never depends on the server; the world is just scenery. +- While a session is active, mixins hold the player still (`KeyboardInput`), stop every key that method handles (`Minecraft.handleKeybinds`: attack, items, hotbar, inventory, chat, F1, F5 and so on) and hotbar scrolling, keep vanilla's tutorial from starting, since it would end itself for good outside survival, and replace vanilla's pause menu. The camera turns with the mouse, but stops 1.54 blocks past the sky screen's edges (`Aim`, with the maths in `ScreenPlane` in `core`), so the player can't spin away from the stage. Vanilla's HUD stays apart from the hunger bar, which is hidden, and Hexium draws combo, judgement and score over it. While no screen is open, vanilla doesn't see lane keys at all, so the play loop tells it there was input, or it would lower the frame rate. A player arriving in third person or with the HUD hidden gets the normal view, and their own comes back afterwards. +- A session ends when the connection closes, and also whenever the title screen or the Hexium menu opens, so a failed load can't leave one running. ## Audio and clock -- Songs are not played through Minecraft's sound manager. The mod decodes OGG with stb_vorbis (bundled with LWJGL) and streams it into its own OpenAL source on the game's existing OpenAL context. -- Song position comes from `AL_SAMPLE_OFFSET`, plus the OpenAL Soft latency extension if it's there. This raw value updates in steps, so the clock runs on `System.nanoTime()` and is gently nudged toward the audio position. It never jumps backwards. +- Songs are not played through Minecraft's sound manager. The mod decodes OGG with stb_vorbis (bundled with LWJGL) on a background thread and streams it into its own OpenAL source on the game's existing OpenAL context (`SongStream`). Minecraft destroys that context when the audio device changes or sounds reload, so a mixin stops the stream first, and it rebuilds its source on the new one at the clock's current time. The song is silent while Minecraft's loading screen covers the game. +- Song position comes from `AL_SEC_OFFSET_LATENCY_SOFT` (the OpenAL Soft latency extension), or `AL_SAMPLE_OFFSET` if it isn't there. This raw value updates in steps, so the clock runs on SDL's tick counter, the clock input events are stamped with, and is gently pulled toward the audio position. It only jumps if the audio is over 100 ms away, or for the first position after a lead-in, and never runs backwards: it holds still until the music catches up. The logic is `SongClock` in `core`, which has no time source of its own, so it can be tested. `AudioClock` in `mod` feeds it. +- Vanilla music is held for the length of a session. - Draw time = song time − visual offset (A). Judgement time = input song time − judgement offset (B). ## Input timing -- Hook the keyboard and mouse callbacks (Minecraft's keyboard and mouse handlers). Stamp each event with `glfwGetTime()` when it arrives and convert it to song time with the clock's mapping. -- GLFW delivers events once per frame, so timestamp error is at most one frame. Tell players to run uncapped or at 240+ FPS during play (about 4 ms of error). Keep rendering fast so this holds. -- Every frame, record an aim sample (song time, yaw, pitch → crosshair point on the screen plane). Slides and flicks are judged from these samples. Flicks test the line between two samples, so fast swipes at low FPS still register. -- Events go into a queue that the judge drains every frame. Every input event and aim sample is also appended to the replay. +- Minecraft 26.3 uses SDL3, not GLFW. Read lane keys in `SDLEventHandler` (`LaneInput`), since it hands keys on to the keyboard handler later in the frame, and the left and right mouse buttons there too (`SkyInput`). A click that grabs the mouse back after the window lost focus still reaches vanilla, so it can, and a release always goes wherever its press went, so vanilla never sees half a click. Keys are physical positions, so the left hand sits the same on any layout. Each SDL event carries a `timestamp` from SDL's tick counter (`SDL_GetTicksNS`), the same clock the song clock runs on, so convert that to song time with the clock's mapping. +- Events are polled once per frame, so without a real timestamp from the OS the error is at most one frame. The debug overlay's `key stamp age` hints at whether stamps are real: at a low frame rate they should spread from about 0 up to a frame. Tell players to run uncapped or at 240+ FPS during play (about 4 ms of error). Keep rendering fast so this holds. +- Every frame, record an aim sample: where the camera's look ray from the eye meets the screen plane (`ScreenPlane`), as normalised screen coordinates. Slides and flicks are judged from these samples. Flicks test the line between two samples, so fast swipes at low FPS still register. +- Events go into fixed rings. The play loop (`PlaySession`) reads the clock at the start of every frame, before anything reads the time. Vanilla turns the camera with the mouse later in the frame (`MouseHandler.handleAccumulatedMovement`), so only then does the play loop keep the camera within its limit, drain keys and buttons oldest first, and send the frame's aim sample, before anything is drawn. So a sample is where the camera really pointed that frame, and a click is placed there too: a click's own position within the frame isn't known. A play has a 3-second lead-in with the clock running before the music, and stays open 2 seconds after the last note. +- Pausing stops the song and clock together. Resuming goes back 3 seconds, or to before the song if that's where it lands, and plays on from there under a 3-2-1 countdown. `PlayInput` in `core` holds the rule: nothing is judged or recorded until the song is back at the pause point, and any lane key or sky button that changed in between is pressed or released at exactly that time. The crosshair is recorded where it last was at the pause point, and again where it is on its way to the frame that reopens judging, at that same time, so moving the mouse while paused isn't a swipe ([REPLAY_FORMAT.md](REPLAY_FORMAT.md)). Keys are read while the pause screen is open too, so this knows which are really down. Notes already judged stay hidden during the countdown, and so does the part of a hold already played. +- A finished play opens `ResultsScreen` and saves its replay. Retry, on that screen and the pause screen, loads a new `PlaySession` for the same chart and keeps the stage. Leaving or retrying part way through saves nothing. +- A key usually arrives after a later frame has read the time: on a Mac at 170 FPS, most stamps were already older than the last frame. So `PlayInput` holds aim samples and the judge's clock 50 ms behind the song. A key is judged at once at its own stamp, after the samples older than it, so hits show straight away and only Misses, ticks and, from Milestone 3, slide and flick results show up to 50 ms later. Sky buttons go through `PlayInput` the same way, with the crosshair at the click, never straight to `ReplayRecorder`, or they would land out of order with the held-back samples. A key or button older than the judge's current time moves up to it and counts as a `late key`: that takes a stamp more than 50 ms behind the previous frame, or one older than a newer key or the pause point. Calibration reads the same stamps, so offset B applies to the times it was measured on. +- Events go through the judge every frame. Every input event and aim sample is also appended to the replay: the mod sends all input through `PlayInput`, then `ReplayRecorder`, which records it and passes it to the judge ([REPLAY_FORMAT.md](REPLAY_FORMAT.md)). + +## Calibration + +`CalibrationScreen` suggests offsets A and B on a plain screen, without the stage. It holds a session and plays the bundled click track on the same `AudioClock`, and `LaneInput` reads taps with the same SDL timestamps as a play, so it measures what a play would see. For the second step the song keeps running in silence, so the clock is the same. The maths is in `Calibration` in `core`. Taps from the first half second are ignored while the clock settles, as are the first two after that while the player finds the beat. Step one won't start with the music volume at 0, since steady taps to nothing would pass, and taps that slide off the beat or scatter are sent back. Vanilla holds this screen to 60 FPS, so against a 240 FPS play the notes it shows are about 6 ms older: this estimates A a little low, so taps may judge a few ms early. ## Rendering -- Hook Fabric's world-render event for 26.3 (check the exact name in Fabric's 26.x docs, since rendering APIs changed). Draw only notes inside the visible time window. -- Notes are block models (note block styles per type) batched into one vertex buffer per frame. Hold bodies are stretched quads, slide paths are ribbons, and the screen is a translucent pane with a frame. +- `TrackRenderer` draws through Fabric's `LevelRenderEvents.COLLECT_SUBMITS` and `submitCustomGeometry`, never raw OpenGL, since 26.3 can run on Vulkan. Only notes inside the visible time window are drawn: `GroundTrack` in `core` holds them in time order and finds where to start, and every position is worked out fresh from draw time, so a note can't drift from the clock. A note's distance up the lane is `(note time − draw time) × note speed`, and speed never changes when it arrives. +- For now the render type doesn't write depth and, with classic transparency, sorts quads by their centres, so a long floor quad could paint over a note behind its middle. So the floor, hold bodies and notes are each submitted in their own order, which are drawn in turn, and a note only emits the faces the camera can see. Improved transparency (the Fabulous preset) draws these on a different path; the game test takes a screenshot of it to check by eye. A note goes once the judge has its head, and a hold's body stops at the line, shortening as it plays. Vertices are relative to the camera on an untransformed pose, as vanilla's entities are, so no matrix is applied per vertex. +- Notes are plain coloured shapes until Milestone 5 brings block models (note block styles per type). Ground notes are cuboids and hold bodies stretched quads. `SkyRenderer` draws after the ground, in orders of its own: the sky notes, then the screen as a faint pane with a frame in front of them, so they show through it, then the rings on the screen. `SkyTrack` in `core` holds sky taps, slides and flicks in time order the way `GroundTrack` holds ground notes, with each note's hit radius from `JudgementConfig` and a slide's position at any time from the same `SlidePath` the judge uses. A sky note flies down the depth axis at the note speed as a flat octagon facing the player, just covering its hit circle: taps orange (L) or blue (R), flicks magenta. A slide is a trail of small beads on a fixed time grid down its path, with a ring where it crosses the screen now, white while its button is down. A tap or flick within 24 blocks also shows a faint ring on the screen where it will land, and a late one waits on the screen until it's judged or its window passes. During the rewind after a pause, the part of a slide before the pause point isn't drawn, as with hold bodies. +- Note speed and visual offset A live in `PlaySettings`, changed from the pause screen, and A also by calibration. They reach only `TrackRenderer` and `SkyRenderer`, so the judge and replays never see them. Offset B is read when a play starts and goes in its replay. +- The comfort settings live in `PlaySettings` too and act only on the camera (`Comfort`): play sensitivity scales the turn vanilla's `MouseHandler.turnPlayer` hands the player, play FOV replaces `Camera.calculateFov`'s result, and view assist eases the camera toward the rest view in the play loop, by song time, before the camera limit, when no sky note is due within 1.5 seconds or can still be judged. Outside a play they do nothing, so menus and normal worlds feel the same. - Hit effects are client-only particles and a short sound, with a hit-sound volume setting. -- Performance budget: 240 FPS with 300 notes on screen on a mid-range GPU. Add a debug overlay showing clock drift, frame time and input-to-judgement delay from Milestone 2. +- Performance budget: 240 FPS with 300 notes on screen on a mid-range GPU. F6 during a play shows a debug overlay with the song position, clock drift, frame time, the offsets, and input-to-judgement delay as `key stamp age`: how old a key's SDL timestamp is at the start of the frame that judges it (minimum, average, maximum). Judged times come from the stamp unless it's older than the judge's current time, which `late keys` counts, and it can't see the keyboard's own delay. It rebuilds its text every quarter second. It stays on across plays until the game closes, and F3+F6 still reaches vanilla. ## Local data -`.minecraft/hexium/` holds `charts/` (one folder per chart package), `replays/`, `scores.json` (best scores per chart) and `settings.json`. That's enough for v1. A real database only lives on the server. +`.minecraft/hexium/` holds `charts/` (one folder per chart package; the mod also bundles a test pack in `hexium_packs/`), `replays/` (one `---