Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
# app-web
- Never commit or publish build output (`.wasm`, `.js` bundles, HTML with the game in it), and
never link to a hosted build.
- The page's TypeScript (`src/main/ts`) runs in the browser with its types stripped
(`:app-web:pageScripts`, Node's `stripTypeScriptTypes`), with no bundler: erasable syntax only,
relative imports end in `.ts`, and anything testable goes in a module without side effects
(`loader.ts`, `cache-policy.ts`) rather than `boot.ts` or `sw.ts`.
- TypeScript: no `any`; every eslint-disable comment says why; only erasable syntax (no enums,
namespaces or parameter properties).
- The entry point sets library properties before anything reads them (`LibraryDefaults`: Netty in
heap mode, JOML); keep new ones there.
- Test: `npm run check`, and `./gradlew :app-web:test` (`MemoryParityTest`: the game's vertex and
image bytes over web-classlib's memory against LWJGL's; needs `./incari setup`).
- `@Async` methods complete with a value that says they failed and throw in Java, never through
`AsyncCallback.error`, which crashes the page (`platform-web/AGENTS.md`, `probes/FetchFailureProbe`).
+141
View File
@@ -0,0 +1,141 @@
# app-web: the browser build
The game in a browser tab. `WebMain` installs `platform-web` and the WebGL2 backend, then starts the
game's own `Main`. `tools/webbuild` compiles it with TeaVM into two builds (ADR 0036):
| Build | Output | Threads | Runs in |
| --- | --- | --- | --- |
| Fast (`-Pteavm.fast`) | `build/teavm-fast/` | JSPI | Chrome/Edge 137+, Firefox 153+ |
| Compatible (default) | `build/teavm/` | TeaVM coroutines: slower, twice the size | anything with WebAssembly GC, Safari too |
| Rust (experimental) | `build/rust/` | Web Workers (Horizon's own) | WebGPU: Chrome and Edge 113+ ([`rust/`](../rust/README.md), ADR 0068) |
`-Pteavm.fast` also makes `browserCheck`, `screenshotDiff` and `benchmark` use Fast. The page offers
the builds that are compiled; delete a build's folder to leave it out. Rust isn't a TeaVM build:
`./incari build --only rust` writes it, and the page opens its own page, `rust/index.html`, with its
own files and service worker.
## Tasks
```sh
./gradlew :app-web:teavm # compile (~10 minutes); -Pteavm.release for an optimized build
./gradlew :app-web:serve # serve on http://localhost:8080/
./gradlew :app-web:browserCheck # run headless until the game loop ticks
./gradlew :app-web:shaders # translate shaders only (seconds)
./gradlew :app-web:buildManifest # page scripts, asset pack, build.json (seconds)
./gradlew :app-web:checkDownloadSize # hold the download to download-budget.properties
./gradlew :app-web:screenshotDiff # desktop vs browser renders of fixed scenes (ADR 0012)
./gradlew :app-web:benchmark # profiler figures against a baseline (docs/benchmark.md)
```
Editing the page or its scripts needs no recompile: `serve` and `browserCheck` rebuild the manifest
and serve the page's files directly.
## Page options
| Option | Effect |
| --- | --- |
| `?build=fast` / `compatible` / `rust` | Pick a build, skipping the loading screen's choice. Rust's page gets the other options (Horizon reads `?args=`) |
| `?server=ws://host:port` | Join that server once the game starts |
| `?via=auto` / `off` / `1.8.9` | Via for that join (ADR 0071); without it, a new entry has Via off |
| `?name=` | Offline player name; skips Edit Profile |
| `?world=&seed=` | Create or open a singleplayer world |
| `?options=<file>` | Start with that options file, fetched from beside the page |
| `?online=<url>`, `?updates=on` | Another online service; show the update notice in a dev build |
| `?profile`, `?overlay` | Profiler collecting from the start; its overlay (F9 in game) |
| `?tier=`, `?particles=` | Force a quality tier |
| `?sw=off` | No service worker (and unregister it) |
| `?netwake=timers` | A server message's connection thread waits for TeaVM's timer, which play delays ~35 ms, instead of running as the message comes (ADR 0075) |
| `?wakeups=channel` / `timers` | The game's threads always wake through a `MessageChannel`; or always on the page's own timers. By default they use the page's timers while visible and a worker's timer while hidden, so a background tab still answers servers (ADR 0072) |
| `?fchord=on` / `off` | F then a digit as a function key; on by default only on ChromeOS |
| `?renderer=headless` | Run the game loop without drawing |
| `?shaders=eager` | Link every WebGL program at start-up |
| `?multidraw=off`, `?drawcensus`, `?gpucensus` | Compare terrain drawing; count draws |
| `?<switch>=game` (or `off`, `all`) | Turn one optimization off to compare it. `WebMain` lists every switch |
## Driving the page in checks
`browserCheck` can act like a player over the DevTools protocol, from inline steps or a script:
```sh
./gradlew :app-web:browserCheck -Pbrowser.steps="shot:build/title.png;click:0.5,0.45;sleep:2000"
./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/input.steps
```
Steps cover screenshots, mouse, keys (`key:F3+KeyB`), typing and input methods, clipboard, viewport
size, page assertions (`holds:`, `until:`), reloads, file choosers, downloads, dropped files, test
resource packs and RCON commands on a test server. `BrowserCheck.runStep` lists them all. The
scripts and the checklist for what needs a real browser are in [`browser-checks/`](browser-checks/README.md).
## Code map
| Where | What |
| --- | --- |
| `WebMain` | Entry point and page options |
| `WebStorage` | The game's files under `/incari`, kept by `platform-web` (ADR 0011) |
| `ClientJar` | Mounts the client jar's resources read-only; the storage worker downloads it once |
| `WebAssets` | Sound list and pack metadata from the asset index; sounds fetched when first played (ADR 0013, 0037) |
| `WebShaders`, `AssetPack` | The build's translated shaders and asset pack (ADR 0014) |
| `LoaderPage`, `Fetch` | Loading-screen steps; downloads before the game starts |
| `headless/` | A graphics device that draws nothing |
| `src/main/web/index.html` | The loader page |
| `src/main/ts/` | `boot.ts` (loader), `loader.ts` (its decisions), `jspi.ts`, `features.ts` (feature detection), `sw.ts` and `cache-policy.ts` (service worker), `offline.ts` (single-file shim, ADR 0057) |
## Packaging
- `build.json` lists every file with size and SHA-256, so the service worker keeps each file until
it changes. `incari.pack` holds build-time data (shaders, sprites, Via mappings). See ADR 0014.
- `./incari build` writes a folder for a static web server (ADR 0028); `--html` writes one HTML
file (ADR 0057). Neither may be shared ([`docs/self-hosting.md`](../docs/self-hosting.md)).
## Download budget
`download-budget.properties` limits what a player downloads at start (gzip level 9, plus raw module
size; brotli reported). Every file is classed `download`, `debug`, `report` or `vendor` (Mojang's
jar, measured but not ours). An unclassed file fails the check. Raise a limit in the PR that needs
it, and say why. CI doesn't compile the browser build, so it only unit-tests the budget logic.
```sh
./gradlew :app-web:checkDownloadSize -PdownloadSize.skipBuild # measure the existing build
```
## Screenshot diffs
Renders `screenshot-scenes/scenes.txt` on the desktop (OpenGL, the reference) and in headless
Chromium (WebGL2), on a fresh local server, and compares each pair by SSIM. Fails under a scene's
threshold, on any WebGL error, or on a skipped pipeline. Needs a display and GPU, so it runs
locally, not in CI. Output goes to `build/screenshots/` and is never committed.
```sh
./gradlew :app-web:screenshotDiff -Pscreenshots.skipBuild -Pscreenshots.only=sky,gui
./gradlew :app-web:screenshotDiff -Pscreenshots.reuseDesktop # browser side only
./gradlew :app-web:screenshotDiff -Pscreenshots.gpu=swiftshader # software WebGL, lower scores
```
Ports: `-Pscreenshots.port` (18210) and the five above it. The benchmark uses 18310 and four above.
## Probes
A full compile takes ten minutes. To test one behaviour of TeaVM or the class library, compile a
small program instead (seconds):
```sh
app-web/probes/run.sh <Name> [-Pteavm.fast]
```
[`probes/README.md`](probes/README.md) lists them. A one-off program runs the same way:
`./gradlew :app-web:browserCheck -Pteavm.main=Probe -Pteavm.classpath=<dir> "-Pbrowser.expect=probe done"`.
## Invariants
- **Builds are never committed or published.** The dev server binds to localhost only.
- **Mojang's assets and client jar are never copied into the build.** The page fetches them, and
the storage worker keeps the jar outside the game's heap.
- **TypeScript is strict**, lint-clean, and uses only syntax Node's type stripping can erase, so
tests run straight from source.
## How to test
```sh
npm ci && npm run check
./gradlew :app-web:browserCheck # needs Chromium (Playwright's, or INCARI_CHROME)
```
@@ -0,0 +1,230 @@
# The benchmark's baseline (ADR 0021; tools/webbuild's PerfBaseline). ./gradlew
# :app-web:benchmark fails when a figure is worse than this machine's recorded one by more than
# its rule allows: both more than the percentage and more than the absolute amount, so noise in a
# small figure doesn't fail a run. Figures without a rule are recorded but never fail.
#
# Re-record a machine with -Pbenchmark.updateBaseline (and say why in the pull request). Figures
# are machine-specific: -Pbenchmark.machine names the machine, and only its own lines are compared.
# They're recorded on the release build (-Pteavm.release, ADR 0025); the lobby's from then
# on are of the whole scene (its floor and signs, built once its chunks have loaded).
# docs/benchmark.md lists the reference machines.
#
# rule.<figure>=<higher|lower is better> <percent> <absolute>
# Frame rate and frame time.
rule.fpsMedian=higher 5 1
rule.fpsLow1=higher 15 3
rule.frameP99Millis=lower 15 2
# Where the frame's time goes (milliseconds a frame).
rule.tickMillis=lower 20 0.5
rule.extractMillis=lower 20 0.5
rule.renderMillis=lower 20 0.5
rule.gpuMillis=lower 20 0.5
# Draw calls: steady for a fixed scene, so tighter.
rule.drawCalls=lower 10 5
rule.terrainDrawCalls=lower 10 3
# Memory, in megabytes, and garbage collection pauses.
rule.heapMaxMB=lower 10 16
rule.nativeMaxMB=lower 10 16
rule.gcMaxPauseMillis=lower 30 4
# Loading (milliseconds from navigation) and the download (bytes, gzip).
rule.coldTitleMillis=lower 20 500
rule.warmTitleMillis=lower 20 500
rule.joinMillis=lower 20 500
rule.rejoinMillis=lower 20 500
rule.gzipBytes=lower 2 10000
desktop.combat.drawCalls=84.27
desktop.combat.extractMillis=0.40
desktop.combat.fpsLow1=46.54
desktop.combat.fpsMean=60.00
desktop.combat.fpsMedian=59.24
desktop.combat.frameP99Millis=20.69
desktop.combat.frames=2430
desktop.combat.gcCount=33
desktop.combat.gcMaxPauseMillis=1.81
desktop.combat.gcTotalMillis=25.36
desktop.combat.gpuMillis=0.87
desktop.combat.heapLiveMB=344.91
desktop.combat.heapMaxMB=409.06
desktop.combat.meshQueueMax=0
desktop.combat.meshQueueMean=0
desktop.combat.nativeLiveMB=52.46
desktop.combat.nativeMaxMB=74.44
desktop.combat.poolMillis=0
desktop.combat.renderMillis=0.69
desktop.combat.slow1.extractMillis=0.43
desktop.combat.slow1.frameMillis=5.75
desktop.combat.slow1.intervalMillis=21.49
desktop.combat.slow1.poolLateMillis=0
desktop.combat.slow1.poolMillis=0
desktop.combat.slow1.renderMillis=1.21
desktop.combat.slow1.tickMillis=4.04
desktop.combat.terrainDrawCalls=4
desktop.combat.terrainSections=521
desktop.combat.tickMillis=1.30
desktop.download.gzipBytes=20397515
desktop.flythrough.drawCalls=79.69
desktop.flythrough.extractMillis=0.38
desktop.flythrough.fpsLow1=45.74
desktop.flythrough.fpsMean=60.00
desktop.flythrough.fpsMedian=59.68
desktop.flythrough.frameP99Millis=20.86
desktop.flythrough.frames=3340
desktop.flythrough.gcCount=83
desktop.flythrough.gcMaxPauseMillis=5.48
desktop.flythrough.gcTotalMillis=88.74
desktop.flythrough.gpuMillis=0.73
desktop.flythrough.heapLiveMB=349.90
desktop.flythrough.heapMaxMB=524.32
desktop.flythrough.meshQueueMax=76
desktop.flythrough.meshQueueMean=4.27
desktop.flythrough.nativeLiveMB=51.90
desktop.flythrough.nativeMaxMB=74.44
desktop.flythrough.poolMillis=1.58
desktop.flythrough.renderMillis=0.99
desktop.flythrough.slow1.extractMillis=1.28
desktop.flythrough.slow1.frameMillis=6.44
desktop.flythrough.slow1.intervalMillis=21.86
desktop.flythrough.slow1.poolLateMillis=0.01
desktop.flythrough.slow1.poolMillis=2.24
desktop.flythrough.slow1.renderMillis=1.72
desktop.flythrough.slow1.tickMillis=3.26
desktop.flythrough.terrainDrawCalls=4.36
desktop.flythrough.terrainSections=568.07
desktop.flythrough.tickMillis=0.95
desktop.load.coldFirstFrameMillis=1737.96
desktop.load.coldTitleMillis=2845.94
desktop.load.joinMillis=5067.91
desktop.load.titleHeapLiveMB=264.58
desktop.load.titleNativeLiveMB=20.16
desktop.load.warmFirstFrameMillis=1112.94
desktop.load.warmReloadedMillis=1605.84
desktop.load.warmTitleMillis=2117.80
desktop.lobby.drawCalls=128.92
desktop.lobby.extractMillis=2.18
desktop.lobby.fpsLow1=41.77
desktop.lobby.fpsMean=59.98
desktop.lobby.fpsMedian=60.42
desktop.lobby.frameP99Millis=22.87
desktop.lobby.frames=2427
desktop.lobby.gcCount=200
desktop.lobby.gcMaxPauseMillis=3.70
desktop.lobby.gcTotalMillis=122.74
desktop.lobby.gpuMillis=0.65
desktop.lobby.heapLiveMB=337.17
desktop.lobby.heapMaxMB=539.22
desktop.lobby.meshQueueMax=19
desktop.lobby.meshQueueMean=1.58
desktop.lobby.nativeLiveMB=44.98
desktop.lobby.nativeMaxMB=74.44
desktop.lobby.poolMillis=0.47
desktop.lobby.renderMillis=9.89
desktop.lobby.slow1.extractMillis=4.21
desktop.lobby.slow1.frameMillis=18.85
desktop.lobby.slow1.intervalMillis=23.94
desktop.lobby.slow1.poolLateMillis=1.49
desktop.lobby.slow1.poolMillis=1.79
desktop.lobby.slow1.renderMillis=10.03
desktop.lobby.slow1.tickMillis=4.55
desktop.lobby.terrainDrawCalls=2
desktop.lobby.terrainSections=114.89
desktop.lobby.tickMillis=1.26
laptop-floor.combat.drawCalls=16.61
laptop-floor.combat.extractMillis=0.89
laptop-floor.combat.fpsLow1=22.98
laptop-floor.combat.fpsMean=59.20
laptop-floor.combat.fpsMedian=61.65
laptop-floor.combat.frameP99Millis=20.94
laptop-floor.combat.frames=2425
laptop-floor.combat.gcCount=18
laptop-floor.combat.gcMaxPauseMillis=4.36
laptop-floor.combat.gcTotalMillis=48.58
laptop-floor.combat.gpuMillis=6.17
laptop-floor.combat.heapLiveMB=335.05
laptop-floor.combat.heapMaxMB=398.42
laptop-floor.combat.meshQueueMax=1
laptop-floor.combat.meshQueueMean=0.00
laptop-floor.combat.nativeLiveMB=69.24
laptop-floor.combat.nativeMaxMB=92.56
laptop-floor.combat.poolMillis=0.00
laptop-floor.combat.renderMillis=1.91
laptop-floor.combat.slow1.extractMillis=0.74
laptop-floor.combat.slow1.frameMillis=29.54
laptop-floor.combat.slow1.intervalMillis=43.52
laptop-floor.combat.slow1.poolLateMillis=0
laptop-floor.combat.slow1.poolMillis=0
laptop-floor.combat.slow1.renderMillis=23.55
laptop-floor.combat.slow1.tickMillis=4.74
laptop-floor.combat.terrainDrawCalls=3
laptop-floor.combat.terrainSections=1028
laptop-floor.combat.tickMillis=1.43
laptop-floor.download.gzipBytes=20397515
laptop-floor.flythrough.drawCalls=18.83
laptop-floor.flythrough.extractMillis=0.79
laptop-floor.flythrough.fpsLow1=24.20
laptop-floor.flythrough.fpsMean=59.27
laptop-floor.flythrough.fpsMedian=60.24
laptop-floor.flythrough.frameP99Millis=23.44
laptop-floor.flythrough.frames=3298
laptop-floor.flythrough.gcCount=35
laptop-floor.flythrough.gcMaxPauseMillis=18.05
laptop-floor.flythrough.gcTotalMillis=333.28
laptop-floor.flythrough.gpuMillis=6.46
laptop-floor.flythrough.heapLiveMB=338.39
laptop-floor.flythrough.heapMaxMB=487.57
laptop-floor.flythrough.meshQueueMax=72
laptop-floor.flythrough.meshQueueMean=6.46
laptop-floor.flythrough.nativeLiveMB=69.21
laptop-floor.flythrough.nativeMaxMB=92.56
laptop-floor.flythrough.poolMillis=1.86
laptop-floor.flythrough.renderMillis=2.05
laptop-floor.flythrough.slow1.extractMillis=5.17
laptop-floor.flythrough.slow1.frameMillis=27.34
laptop-floor.flythrough.slow1.intervalMillis=41.33
laptop-floor.flythrough.slow1.poolLateMillis=2.66
laptop-floor.flythrough.slow1.poolMillis=4.24
laptop-floor.flythrough.slow1.renderMillis=7.64
laptop-floor.flythrough.slow1.tickMillis=12.63
laptop-floor.flythrough.terrainDrawCalls=4.45
laptop-floor.flythrough.terrainSections=861.95
laptop-floor.flythrough.tickMillis=0.99
laptop-floor.load.coldFirstFrameMillis=6345.27
laptop-floor.load.coldTitleMillis=12002.17
laptop-floor.load.joinMillis=14670.95
laptop-floor.load.rejoinMillis=11880.94
laptop-floor.load.titleHeapLiveMB=237.58
laptop-floor.load.titleNativeLiveMB=42.75
laptop-floor.load.warmFirstFrameMillis=3814.29
laptop-floor.load.warmReloadedMillis=7527.75
laptop-floor.load.warmTitleMillis=8035.69
laptop-floor.lobby.drawCalls=28.08
laptop-floor.lobby.extractMillis=3.38
laptop-floor.lobby.fpsLow1=32.60
laptop-floor.lobby.fpsMean=58.68
laptop-floor.lobby.fpsMedian=60.92
laptop-floor.lobby.frameP99Millis=25.46
laptop-floor.lobby.frames=2386
laptop-floor.lobby.gcCount=121
laptop-floor.lobby.gcMaxPauseMillis=7.13
laptop-floor.lobby.gcTotalMillis=422.09
laptop-floor.lobby.gpuMillis=5.65
laptop-floor.lobby.heapLiveMB=323.68
laptop-floor.lobby.heapMaxMB=497.13
laptop-floor.lobby.meshQueueMax=34
laptop-floor.lobby.meshQueueMean=3.62
laptop-floor.lobby.nativeLiveMB=62.91
laptop-floor.lobby.nativeMaxMB=92.56
laptop-floor.lobby.poolMillis=0.56
laptop-floor.lobby.renderMillis=9.34
laptop-floor.lobby.slow1.extractMillis=5.38
laptop-floor.lobby.slow1.frameMillis=25.26
laptop-floor.lobby.slow1.intervalMillis=30.68
laptop-floor.lobby.slow1.poolLateMillis=0.67
laptop-floor.lobby.slow1.poolMillis=1.47
laptop-floor.lobby.slow1.renderMillis=13.54
laptop-floor.lobby.slow1.tickMillis=5.72
laptop-floor.lobby.terrainDrawCalls=2
laptop-floor.lobby.terrainSections=271.76
laptop-floor.lobby.tickMillis=1.56
@@ -0,0 +1,141 @@
# The benchmark (ADR 0021): ./gradlew :app-web:benchmark plays these scenarios in the browser
# build and reports what the page's profiler measured. The format is tools/webbuild's
# BenchmarkScript; docs/benchmark.md explains the figures and how to run it on a Chromebook.
#
# The page joins a fresh world from server.properties' seed as IncariBench, with options.txt's
# options (render distance 8). The world is made ready before anyone joins: time and weather
# stopped, no natural spawns, and the terrain both scenarios see generated in advance, so a scenario
# measures the client loading and drawing it, not the server making it. The player watches each
# scenario as a spectator of an invisible armor stand: a camera the server moves, so every run
# sees the same frames. options.txt throttles the frame rate only when minimized.
server
rcon:gamerule advance_time false
rcon:gamerule advance_weather false
rcon:gamerule spawn_mobs false
rcon:gamerule spawn_patrols false
rcon:gamerule spawn_phantoms false
rcon:gamerule spawn_wandering_traders false
rcon:gamerule command_block_output false
rcon:gamerule mob_drops false
rcon:time set 6000
rcon:weather clear
# The fly-through's corridor, x -128 to 895 and z -128 to 127: the flight and its render
# distance. forceload takes 256 chunks at a time.
rcon:forceload add -128 -128 127 127
rcon:forceload add 128 -128 383 127
rcon:forceload add 384 -128 639 127
rcon:forceload add 640 -128 895 127
# The arena, 2000 blocks north, with its render distance.
rcon:forceload add -128 -2128 127 -1873
# The lobby, 2000 blocks south, with its render distance.
rcon:forceload add -128 1872 127 2127
rconwait:execute if loaded -128 64 -128 => passed
rconwait:execute if loaded 383 64 127 => passed
rconwait:execute if loaded 895 64 -128 => passed
rconwait:execute if loaded 895 64 127 => passed
rconwait:execute if loaded 127 64 -1873 => passed
rconwait:execute if loaded -128 64 -2128 => passed
rconwait:execute if loaded 127 64 2127 => passed
rconwait:execute if loaded -128 64 1872 => passed
rcon:forceload remove all
# The fly-through's engine: each tick, the camera moves 0.55 blocks east (11 blocks a second, a
# sprint-fly). Its chunk stays loaded so it always runs.
rcon:forceload add 0 0
rcon:setblock 0 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @e[tag=incari_camera] at @s run tp @s ~0.55 ~ ~"}
setup
rcon:gamemode spectator IncariBench
rcon:tp IncariBench 0.5 140 0.5 -90 25
sleep:5000
scenario flythrough A straight flight east over fresh terrain at 11 blocks a second, render distance 8
rcon:kill @e[tag=incari_camera]
rcon:summon minecraft:armor_stand 0.5 140 0.5 {Tags:["incari_camera"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[-90f,25f]}
rcon:spectate @e[tag=incari_camera,limit=1] IncariBench
sleep:3000
measure:55
# A teleport ends the spectating.
rcon:tp IncariBench 0.5 212 -2026 0 35
rcon:kill @e[tag=incari_camera]
scenario combat Iron golems against waves of vindicators, pillagers and husks in an arena, watched from its edge
rcon:tp IncariBench 0.5 212 -2026 0 35
# The teleport loads the arena's chunks a moment later: building before then fails.
rconwait:execute if loaded -17 199 -2017 => passed
rconwait:execute if loaded 17 204 -1983 => passed
rcon:fill -17 199 -2017 17 204 -1983 minecraft:barrier outline
rcon:fill -16 199 -2016 16 199 -1984 minecraft:smooth_stone
rcon:summon minecraft:armor_stand 0.5 212 -2026 {Tags:["incari_watch"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[0f,35f]}
rcon:spectate @e[tag=incari_watch,limit=1] IncariBench
rcon*10:summon minecraft:iron_golem 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon:spreadplayers 0 -2000 2 14 under 203 false @e[tag=incari_fighter]
sleep:5000
measure:10
rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
measure:10
rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
measure:10
rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
measure:10
rcon:kill @e[tag=incari_fighter]
rcon:kill @e[tag=incari_watch]
# The crowded lobby: a crowd of player-shaped mannequins in armor with their names shown, floating
# hologram text, signs, floating items, particle fountains, a sidebar and a boss bar, watched by a
# camera orbiting the crowd 20 blocks out (a command block moves it each tick: sideways and turning,
# so it circles the lobby's centre while facing it).
scenario lobby A crowded server lobby: 80 players in armor with name tags, holograms, signs and particles, circled by the camera
rcon:tp IncariBench 0.5 212 1980 0 25
# As in the arena: wait for the lobby's chunks before building it.
rconwait:execute if loaded -22 199 1978 => passed
rconwait:execute if loaded 22 214 2022 => passed
rcon:fill -22 199 1978 22 199 2022 minecraft:polished_andesite
rcon:fill -22 200 1978 22 214 2022 minecraft:air
rcon:fill -22 200 1978 22 200 1978 minecraft:oak_sign[rotation=0]{front_text:{messages:["Welcome","to the","Incari","lobby"]}}
rcon:fill -22 200 2022 22 200 2022 minecraft:oak_sign[rotation=8]{front_text:{messages:["Pick a","game","below","!"]}}
rcon:fill -22 200 1979 -22 200 2021 minecraft:oak_sign[rotation=12]{front_text:{messages:["Bedwars","Skywars","Duels","Parkour"]}}
rcon:fill 22 200 1979 22 200 2021 minecraft:oak_sign[rotation=4]{front_text:{messages:["Rules:","be kind","no hacks","have fun"]}}
rcon*80:summon minecraft:mannequin 0 200 2000 {Tags:["incari_lobby"],CustomName:"LobbyPlayer",CustomNameVisible:1b,equipment:{head:{id:"minecraft:iron_helmet"},chest:{id:"minecraft:diamond_chestplate"},legs:{id:"minecraft:iron_leggings"},feet:{id:"minecraft:golden_boots"},mainhand:{id:"minecraft:diamond_sword"}}}
rcon:spreadplayers 0 2000 1 15 under 205 false @e[tag=incari_lobby,type=minecraft:mannequin]
rcon*24:summon minecraft:armor_stand 0 203 2000 {Tags:["incari_lobby","incari_hologram"],Invisible:1b,Marker:1b,NoGravity:1b,CustomName:"Play now: 1,024 online",CustomNameVisible:1b}
rcon:spreadplayers 0 2000 2 18 under 205 false @e[tag=incari_hologram]
rcon*12:summon minecraft:text_display 0 205 2000 {Tags:["incari_lobby"],billboard:"center",text:"Incari Network",background:1073741824}
rcon:spreadplayers 0 2000 4 18 under 205 false @e[tag=incari_lobby,type=minecraft:text_display]
rcon*30:summon minecraft:item 0 201 2000 {Tags:["incari_lobby"],Item:{id:"minecraft:diamond",count:1},NoGravity:1b,Age:-32768,PickupDelay:32767}
rcon:spreadplayers 0 2000 1 16 under 205 false @e[tag=incari_lobby,type=minecraft:item]
rcon:setblock 1 318 1 minecraft:repeating_command_block{auto:1b,Command:"particle minecraft:end_rod 0 204 2000 10 3 10 0.01 30 force"}
rcon:setblock 2 318 0 minecraft:repeating_command_block{auto:1b,Command:"particle minecraft:happy_villager 0 202 2000 14 2 14 0 20 force"}
rcon:setblock 2 318 1 minecraft:repeating_command_block{auto:1b,Command:"particle minecraft:flame 0 201 2000 16 1 16 0.01 15 force"}
rcon:scoreboard objectives add incari_lobby dummy "Incari Network"
rcon:scoreboard objectives setdisplay sidebar incari_lobby
rcon:scoreboard players set Online incari_lobby 1024
rcon:scoreboard players set Bedwars incari_lobby 312
rcon:scoreboard players set Skywars incari_lobby 288
rcon:scoreboard players set Duels incari_lobby 201
rcon:scoreboard players set Parkour incari_lobby 97
rcon:bossbar add incari_lobby "Welcome to the Incari lobby"
rcon:bossbar set incari_lobby players @a
rcon:summon minecraft:armor_stand 0.5 207 1980 {Tags:["incari_lobbycam"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[0f,25f]}
rcon:spectate @e[tag=incari_lobbycam,limit=1] IncariBench
rcon:setblock 1 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @e[tag=incari_lobbycam] at @s run tp @s ^0.35 ^ ^ ~1 ~"}
sleep:5000
measure:40
rcon:setblock 1 318 0 minecraft:air
rcon:setblock 1 318 1 minecraft:air
rcon:setblock 2 318 0 minecraft:air
rcon:setblock 2 318 1 minecraft:air
rcon:bossbar remove incari_lobby
rcon:scoreboard objectives remove incari_lobby
rcon:tp IncariBench 0.5 212 1980 0 25
rcon:kill @e[tag=incari_lobby]
rcon:kill @e[tag=incari_lobbycam]
@@ -0,0 +1,32 @@
# The budgets, set for memory (ADR 0025) and start-up (ADR 0026): absolute limits the
# benchmark (tools/webbuild's PerfBudget) fails a figure over, whatever the baseline says. Figures are
# as report.json names them; a * stands for one part of the name (a scenario). Measured on the
# release build (-Pteavm.release), which is what players get.
#
# max.<figure>=<limit> for every machine: memory (the same build in the same scene keeps
# the same heap wherever it runs)
# <machine>.max.<figure>=<limit> for one machine: times, which are the machine's speed
#
# Raising a limit is fine when the pull request says why; the point is that growth is noticed.
# Memory, in megabytes. The live figures are what the page still holds after a full collection
# (the game's own memory, not garbage the browser hasn't collected yet). Set from the release build
# of 2026-10-01 (title screen 262 MB live; in the world 337 to 351 MB live, 45 to 53 MB of linear
# memory in use, 75 MB of it at its largest) with about a fifth of headroom.
max.load.titleHeapLiveMB=320
max.*.heapLiveMB=420
# Linear memory never shrinks: its largest is what the page keeps for good.
max.*.nativeMaxMB=128
# The memory gate: no garbage collection pause above 16 ms (a frame at 60 fps).
max.*.gcMaxPauseMillis=16
# Start-up, in milliseconds from the navigation (the gate: the warm start to the title screen).
# The development desktop (Ryzen 5 9600X): 2.2 s warm and 3.2 s cold measured on 2026-10-01.
desktop.max.load.warmTitleMillis=3000
desktop.max.load.coldTitleMillis=4500
# The floor device, a 4 GB Chromebook (docs/benchmark.md): targets, not measurements, until the
# device is measured. Its CPU (Celeron N4500 class) is estimated at about a fifth of the desktop's
# single-thread speed, which puts the desktop's 2.2 s warm start near 10 s there.
chromebook-4gb.max.load.warmTitleMillis=10000
chromebook-4gb.max.load.coldTitleMillis=20000
@@ -0,0 +1,56 @@
# The client's modules in play, in the page's own world:
# ./gradlew :app-web:benchmark -Pbenchmark.singleplayer -Pbenchmark.script=features.txt
# -Pbenchmark.history=<a file of its own> -Pteavm.release -Pteavm.fast
# -Pbenchmark.query=modules=<ids>
# Run it twice, with no modules (modules=) and with the HUD and play modules on, to see what they
# cost:
# modules=armorpotionview,blockoutline,clearchat,cooldownindicator,coordinates,cps,crosshair,
# customscoreboard,fpsdisplay,freelook,fullbright,glintcolor,hitcolor,hiteffects,keystrokes,
# lowfire,lowshield,minimap,nohurtcam,oldanimations,reachdisplay,shieldtotem,shortswords,
# shulkertooltips,togglesprint,waypoints,weatherchanger
# (no commas' spaces; Old Textures is left out: its pack reloads every resource at start).
# The player is in creative, in armor, with a shield, totems and three effects, so every HUD
# module has something to show. Scenarios: standing at spawn, then flying east at 11 blocks a
# second, a command block teleporting the player each tick, so the minimap draws new chunks.
setup
rcon:gamerule advance_time false
rcon:gamerule advance_weather false
rcon:gamerule spawn_mobs false
rcon:gamerule spawn_patrols false
rcon:gamerule spawn_phantoms false
rcon:gamerule spawn_wandering_traders false
rcon:gamerule command_block_output false
rcon:gamerule send_command_feedback false
rcon:time set 6000
rcon:weather clear
rcon:gamemode creative @s
rcon:item replace entity @s armor.head with minecraft:diamond_helmet
rcon:item replace entity @s armor.chest with minecraft:diamond_chestplate
rcon:item replace entity @s armor.legs with minecraft:diamond_leggings
rcon:item replace entity @s armor.feet with minecraft:diamond_boots
rcon:item replace entity @s weapon.mainhand with minecraft:diamond_sword
rcon:item replace entity @s weapon.offhand with minecraft:shield
rcon:give @s minecraft:totem_of_undying 3
rcon:effect give @s minecraft:speed infinite 1
rcon:effect give @s minecraft:strength infinite 0
rcon:effect give @s minecraft:fire_resistance infinite 0
rcon:forceload add 0 0
sleep:10000
scenario still Standing at spawn with the HUD
shot:features-still
measure:20
scenario travel Flying east at 11 blocks a second over terrain the page's server generates, the minimap drawing new chunks
rcon:tp @s 0.5 120 0.5 -90 20
rcon:gamerule send_command_feedback true
rconwait:execute if loaded 0 64 0 => passed
rconwait:execute if loaded 96 64 0 => passed
rcon:gamerule send_command_feedback false
sleep:5000
rcon:setblock 0 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @a at @s run tp @s ~0.55 120 ~"}
sleep:2000
shot:features-travel
measure:40
rcon:setblock 0 318 0 minecraft:air
@@ -0,0 +1,92 @@
# The HUD editor's cost (ADR 0049), in the page's own world:
# ./gradlew :app-web:benchmark -Pbenchmark.singleplayer -Pbenchmark.script=hudeditor.txt
# -Pbenchmark.history=<a file of its own>
# The player stands at the world's spawn with Toggle Sprint on (its line is what the editor shows).
# Scenarios: the HUD alone; the pause menu (Potato: no blur); the HUD editor in Potato, its blurred
# backdrop drawn ten times a second and kept (BackdropCache); the editor in Normal, blurred every
# frame, which is what Potato would pay without the cache. The menus are reached with the keyboard
# (Tab order in the module menu: All, Movement, GUI, Profile, Done, Edit HUD, the search, the cards),
# and each scenario takes a screenshot in build/benchmark to show it got there.
setup
rcon:gamerule advance_time false
rcon:gamerule advance_weather false
rcon:gamerule spawn_mobs false
rcon:gamerule send_command_feedback false
rcon:time set 6000
rcon:weather clear
sleep:10000
# Toggle Sprint on: its card is the eighth stop.
key:ShiftRight
sleep:1500
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Enter
sleep:500
shot:hudeditor-setup
key:Escape
sleep:3000
scenario hud The world at spawn with the HUD, no screen open
measure:20
scenario pause The pause menu over the world (Potato: no blur)
key:Escape
sleep:2000
shot:hudeditor-pause
measure:20
key:Escape
sleep:2000
scenario editor_potato The HUD editor in Potato: the blurred world drawn ten times a second and kept
key:ShiftRight
sleep:1500
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Enter
sleep:2000
shot:hudeditor-potato
measure:20
key:Escape
sleep:1000
key:Escape
sleep:2000
scenario editor_normal The HUD editor in Normal: the world drawn and blurred every frame
# The module menu's GUI entry (the third stop) switches to Normal.
key:ShiftRight
sleep:1500
key:Tab
key:Tab
key:Tab
key:Enter
sleep:1000
# Opened again, so the Tabs start from the top.
key:Escape
sleep:1500
key:ShiftRight
sleep:1500
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Enter
sleep:2000
shot:hudeditor-normal
measure:20
key:Escape
sleep:1000
key:Escape
sleep:2000
@@ -0,0 +1,92 @@
# The client's menus and screens (the look's first performance pass), in the page's own world:
# ./gradlew :app-web:benchmark -Pbenchmark.singleplayer -Pbenchmark.script=menus.txt
# -Pbenchmark.history=<a file of its own> -Pteavm.release -Pteavm.fast
# The player stands at the world's spawn in survival with a few items. Scenarios: the HUD alone (the
# world's own cost, for comparison), then the module menu, the pause menu and the inventory, in
# Potato and again in Normal (glows, eased hovers, the menus' blur). The pointer rests over the
# module menu's first card, so its hover is drawn. The menus are reached with the keyboard (Tab
# order in the module menu: All, the five categories, GUI, Profile, Done, Edit HUD, the search, the
# cards), and each scenario takes a screenshot in build/benchmark to show it got there.
setup
rcon:gamerule advance_time false
rcon:gamerule advance_weather false
rcon:gamerule spawn_mobs false
rcon:gamerule send_command_feedback false
rcon:time set 6000
rcon:weather clear
rcon:gamemode survival @s
rcon:give @s minecraft:diamond_sword
rcon:give @s minecraft:bow
rcon:give @s minecraft:arrow 64
rcon:give @s minecraft:oak_planks 64
rcon:give @s minecraft:cooked_beef 32
rcon:give @s minecraft:iron_chestplate
sleep:10000
scenario hud The world at spawn with the HUD, no screen open
measure:20
scenario menu_potato The module menu in Potato, the pointer over its first card
key:ShiftRight
sleep:1500
move:0.36,0.3
sleep:1000
shot:menus-menu-potato
measure:20
key:Escape
sleep:2000
scenario pause_potato The pause menu in Potato
key:Escape
sleep:2000
shot:menus-pause-potato
measure:20
key:Escape
sleep:2000
scenario inventory_potato The inventory in Potato: the glass panel with a well under each slot
key:KeyE
sleep:2000
shot:menus-inventory-potato
measure:20
key:Escape
sleep:2000
scenario menu_normal The module menu in Normal, the pointer over its first card
# The module menu's GUI entry (the seventh stop) switches to Normal.
key:ShiftRight
sleep:1500
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Tab
key:Enter
sleep:1000
move:0.5,0.5
sleep:300
move:0.36,0.3
sleep:1000
shot:menus-menu-normal
measure:20
key:Escape
sleep:2000
scenario pause_normal The pause menu in Normal, blurred
key:Escape
sleep:2000
shot:menus-pause-normal
measure:20
key:Escape
sleep:2000
scenario inventory_normal The inventory in Normal
key:KeyE
sleep:2000
shot:menus-inventory-normal
measure:20
key:Escape
sleep:2000
@@ -0,0 +1,45 @@
version:5023
onboardAccessibility:false
pauseOnLostFocus:false
joinedFirstServer:true
skipMultiplayerWarning:true
tutorialStep:none
realmsNotifications:false
graphicsPreset:"custom"
fov:0.0
fovEffectScale:0.0
guiScale:2
renderDistance:8
simulationDistance:6
biomeBlendRadius:2
ao:true
renderClouds:"true"
cloudRange:64
particles:0
mipmapLevels:4
textureFiltering:1
maxAnisotropyBit:1
entityShadows:true
entityDistanceScaling:1.0
improvedTransparency:false
cutoutLeaves:true
weatherRadius:10
chunkSectionFadeInTime:0.0
menuBackgroundBlurriness:5
prioritizeChunkUpdates:0
bobView:false
gamma:0.5
vignette:true
screenEffectScale:1.0
darknessEffectScale:1.0
damageTiltStrength:0.0
hideLightningFlashes:true
enableVsync:false
maxFps:260
inactivityFpsLimit:"minimized"
fullscreen:false
chatVisibility:2
showSubtitles:false
narrator:0
soundCategory_master:0.0
lang:en_us
@@ -0,0 +1,20 @@
# The benchmark's game server (see benchmark.txt). The runner adds the address, ports and a
# random RCON password, and starts every run with a fresh world from this seed. Command blocks
# move the fly-through's camera, a step each tick.
level-seed=20260928
level-type=minecraft\:normal
generate-structures=true
online-mode=false
white-list=false
difficulty=easy
spawn-monsters=false
view-distance=8
simulation-distance=6
spawn-protection=0
enable-command-block=true
pause-when-empty-seconds=0
max-tick-time=-1
broadcast-console-to-ops=false
broadcast-rcon-to-ops=false
sync-chunk-writes=false
enable-status=true
@@ -0,0 +1,266 @@
# The singleplayer benchmark's baseline (ADR 0039; ./gradlew :app-web:benchmark -Pbenchmark.singleplayer,
# singleplayer.txt): as baseline.properties, for the scenarios a world the page runs itself plays.
# Kept apart from the server benchmark's: recording one machine's figures replaces all of them.
#
# rule.<figure>=<higher|lower is better> <percent> <absolute>
# Frame rate and frame time.
rule.fpsMedian=higher 5 1
rule.fpsLow1=higher 15 3
rule.frameP99Millis=lower 15 2
# Where the frame's time goes (milliseconds a frame).
rule.tickMillis=lower 20 0.5
rule.extractMillis=lower 20 0.5
rule.renderMillis=lower 20 0.5
rule.gpuMillis=lower 20 0.5
# Memory, in megabytes, and garbage collection pauses: the page's, then the server worker's.
rule.heapMaxMB=lower 10 16
rule.nativeMaxMB=lower 10 16
rule.gcMaxPauseMillis=lower 30 4
rule.workerHeapLiveMB=lower 10 16
# The server worker's ticks: 20 a second when it keeps up.
rule.serverTicksPerSecond=higher 5 1
rule.serverTickMillis=lower 20 2
rule.serverTickP95Millis=lower 20 5
# Loading, in milliseconds: the world created from the title screen, Save and Quit until it's
# stored, and opening it again from a reload (from the navigation).
rule.coldTitleMillis=lower 20 500
rule.createMillis=lower 20 1000
rule.saveQuitMillis=lower 20 500
rule.openMillis=lower 20 1000
rule.gzipBytes=lower 2 10000
desktop.combat.drawCalls=14.19
desktop.combat.extractMillis=0.25
desktop.combat.fpsLow1=54.31
desktop.combat.fpsMean=60.00
desktop.combat.fpsMedian=60.04
desktop.combat.frameP99Millis=18.34
desktop.combat.frames=1813
desktop.combat.gcCount=9
desktop.combat.gcMaxPauseMillis=0.73
desktop.combat.gcTotalMillis=5.68
desktop.combat.gpuMillis=0.39
desktop.combat.heapLiveMB=411.81
desktop.combat.heapMaxMB=441.17
desktop.combat.meshQueueMax=0
desktop.combat.meshQueueMean=0
desktop.combat.nativeLiveMB=77.32
desktop.combat.nativeMaxMB=100.56
desktop.combat.poolMillis=0
desktop.combat.renderMillis=0.55
desktop.combat.serverChunks=2578
desktop.combat.serverPausedTicks=0
desktop.combat.serverTickMaxMillis=3.73
desktop.combat.serverTickMillis=3.13
desktop.combat.serverTickP95Millis=3.42
desktop.combat.serverTicksPerSecond=19.97
desktop.combat.slow1.extractMillis=0.27
desktop.combat.slow1.frameMillis=2.42
desktop.combat.slow1.intervalMillis=18.41
desktop.combat.slow1.poolLateMillis=0
desktop.combat.slow1.poolMillis=0
desktop.combat.slow1.renderMillis=0.54
desktop.combat.slow1.tickMillis=1.55
desktop.combat.terrainDrawCalls=3
desktop.combat.terrainSections=1021
desktop.combat.tickMillis=0.45
desktop.combat.workerHeapLiveMB=371.04
desktop.download.gzipBytes=20397515
desktop.flythrough.drawCalls=18.94
desktop.flythrough.extractMillis=0.26
desktop.flythrough.fpsLow1=43.63
desktop.flythrough.fpsMean=59.98
desktop.flythrough.fpsMedian=60.15
desktop.flythrough.frameP99Millis=18.75
desktop.flythrough.frames=3335
desktop.flythrough.gcCount=58
desktop.flythrough.gcMaxPauseMillis=45.37
desktop.flythrough.gcTotalMillis=160.67
desktop.flythrough.gpuMillis=0.38
desktop.flythrough.heapLiveMB=383.78
desktop.flythrough.heapMaxMB=607.93
desktop.flythrough.meshQueueMax=56
desktop.flythrough.meshQueueMean=2.96
desktop.flythrough.nativeLiveMB=69.30
desktop.flythrough.nativeMaxMB=100.56
desktop.flythrough.poolMillis=0.69
desktop.flythrough.renderMillis=0.60
desktop.flythrough.serverChunks=2578
desktop.flythrough.serverPausedTicks=0
desktop.flythrough.serverTickMaxMillis=10.55
desktop.flythrough.serverTickMillis=2.50
desktop.flythrough.serverTickP95Millis=4.51
desktop.flythrough.serverTicksPerSecond=20.01
desktop.flythrough.slow1.extractMillis=0.78
desktop.flythrough.slow1.frameMillis=3.26
desktop.flythrough.slow1.intervalMillis=22.92
desktop.flythrough.slow1.poolLateMillis=0
desktop.flythrough.slow1.poolMillis=1.33
desktop.flythrough.slow1.renderMillis=0.86
desktop.flythrough.slow1.tickMillis=1.55
desktop.flythrough.terrainDrawCalls=4.75
desktop.flythrough.terrainSections=868.08
desktop.flythrough.tickMillis=0.38
desktop.flythrough.workerHeapLiveMB=298.95
desktop.load.coldTitleMillis=3210.55
desktop.load.createMillis=6011.25
desktop.load.leftHeapLiveMB=375.48
desktop.load.leftNativeLiveMB=70.16
desktop.load.openMillis=5312.63
desktop.load.saveQuitMillis=1034.09
desktop.spawn.drawCalls=18.79
desktop.spawn.extractMillis=0.22
desktop.spawn.fpsLow1=51.82
desktop.spawn.fpsMean=60.00
desktop.spawn.fpsMedian=60.11
desktop.spawn.frameP99Millis=18.67
desktop.spawn.frames=1806
desktop.spawn.gcCount=8
desktop.spawn.gcMaxPauseMillis=0.77
desktop.spawn.gcTotalMillis=5.59
desktop.spawn.gpuMillis=0.32
desktop.spawn.heapLiveMB=384.43
desktop.spawn.heapMaxMB=414.11
desktop.spawn.meshQueueMax=2
desktop.spawn.meshQueueMean=0.00
desktop.spawn.nativeLiveMB=69.95
desktop.spawn.nativeMaxMB=90.44
desktop.spawn.poolMillis=0.00
desktop.spawn.renderMillis=0.39
desktop.spawn.serverChunks=1849
desktop.spawn.serverPausedTicks=0
desktop.spawn.serverTickMaxMillis=7.44
desktop.spawn.serverTickMillis=4.98
desktop.spawn.serverTickP95Millis=5.73
desktop.spawn.serverTicksPerSecond=19.97
desktop.spawn.slow1.extractMillis=0.25
desktop.spawn.slow1.frameMillis=3.23
desktop.spawn.slow1.intervalMillis=19.30
desktop.spawn.slow1.poolLateMillis=0
desktop.spawn.slow1.poolMillis=0
desktop.spawn.slow1.renderMillis=0.82
desktop.spawn.slow1.tickMillis=2.09
desktop.spawn.terrainDrawCalls=4
desktop.spawn.terrainSections=531
desktop.spawn.tickMillis=0.58
desktop.spawn.workerHeapLiveMB=227.31
laptop-floor.combat.drawCalls=14.86
laptop-floor.combat.extractMillis=0.91
laptop-floor.combat.fpsLow1=33.84
laptop-floor.combat.fpsMean=59.77
laptop-floor.combat.fpsMedian=58.86
laptop-floor.combat.frameP99Millis=23.03
laptop-floor.combat.frames=1829
laptop-floor.combat.gcCount=17
laptop-floor.combat.gcMaxPauseMillis=2.30
laptop-floor.combat.gcTotalMillis=20.50
laptop-floor.combat.gpuMillis=5.01
laptop-floor.combat.heapLiveMB=341.80
laptop-floor.combat.heapMaxMB=382.74
laptop-floor.combat.meshQueueMax=2
laptop-floor.combat.meshQueueMean=0.00
laptop-floor.combat.nativeLiveMB=69.24
laptop-floor.combat.nativeMaxMB=88.56
laptop-floor.combat.poolMillis=0.00
laptop-floor.combat.renderMillis=1.92
laptop-floor.combat.serverChunks=2578
laptop-floor.combat.serverPausedTicks=0
laptop-floor.combat.serverTickMaxMillis=64.22
laptop-floor.combat.serverTickMillis=7.34
laptop-floor.combat.serverTickP95Millis=10.54
laptop-floor.combat.serverTicksPerSecond=20.04
laptop-floor.combat.slow1.extractMillis=2.02
laptop-floor.combat.slow1.frameMillis=16.56
laptop-floor.combat.slow1.intervalMillis=29.55
laptop-floor.combat.slow1.poolLateMillis=0
laptop-floor.combat.slow1.poolMillis=0
laptop-floor.combat.slow1.renderMillis=5.18
laptop-floor.combat.slow1.tickMillis=8.92
laptop-floor.combat.terrainDrawCalls=3
laptop-floor.combat.terrainSections=1043
laptop-floor.combat.tickMillis=1.40
laptop-floor.combat.workerHeapLiveMB=366.58
laptop-floor.download.gzipBytes=20397515
laptop-floor.flythrough.drawCalls=13.65
laptop-floor.flythrough.extractMillis=0.82
laptop-floor.flythrough.fpsLow1=14.91
laptop-floor.flythrough.fpsMean=58.34
laptop-floor.flythrough.fpsMedian=59.92
laptop-floor.flythrough.frameP99Millis=31
laptop-floor.flythrough.frames=3307
laptop-floor.flythrough.gcCount=26
laptop-floor.flythrough.gcMaxPauseMillis=18.29
laptop-floor.flythrough.gcTotalMillis=225.14
laptop-floor.flythrough.gpuMillis=2.45
laptop-floor.flythrough.heapLiveMB=304.75
laptop-floor.flythrough.heapMaxMB=444.96
laptop-floor.flythrough.meshQueueMax=34
laptop-floor.flythrough.meshQueueMean=1.34
laptop-floor.flythrough.nativeLiveMB=61.21
laptop-floor.flythrough.nativeMaxMB=88.56
laptop-floor.flythrough.poolMillis=0.93
laptop-floor.flythrough.renderMillis=1.65
laptop-floor.flythrough.serverChunks=2039
laptop-floor.flythrough.serverPausedTicks=0
laptop-floor.flythrough.serverTickMaxMillis=53.18
laptop-floor.flythrough.serverTickMillis=5.05
laptop-floor.flythrough.serverTickP95Millis=13.72
laptop-floor.flythrough.serverTicksPerSecond=19.97
laptop-floor.flythrough.slow1.extractMillis=4.02
laptop-floor.flythrough.slow1.frameMillis=54.03
laptop-floor.flythrough.slow1.intervalMillis=67.05
laptop-floor.flythrough.slow1.poolLateMillis=4.04
laptop-floor.flythrough.slow1.poolMillis=2.26
laptop-floor.flythrough.slow1.renderMillis=6.51
laptop-floor.flythrough.slow1.tickMillis=42.54
laptop-floor.flythrough.terrainDrawCalls=2.99
laptop-floor.flythrough.terrainSections=97.49
laptop-floor.flythrough.tickMillis=1.85
laptop-floor.flythrough.workerHeapLiveMB=317.97
laptop-floor.load.coldTitleMillis=11817.60
laptop-floor.load.createMillis=26397.91
laptop-floor.load.leftHeapLiveMB=295.76
laptop-floor.load.leftNativeLiveMB=68.10
laptop-floor.load.openMillis=19986.34
laptop-floor.load.saveQuitMillis=3757.05
laptop-floor.spawn.drawCalls=21.33
laptop-floor.spawn.extractMillis=1.07
laptop-floor.spawn.fpsLow1=25.02
laptop-floor.spawn.fpsMean=59.54
laptop-floor.spawn.fpsMedian=60.37
laptop-floor.spawn.frameP99Millis=27.12
laptop-floor.spawn.frames=1837
laptop-floor.spawn.gcCount=9
laptop-floor.spawn.gcMaxPauseMillis=29.12
laptop-floor.spawn.gcTotalMillis=68.98
laptop-floor.spawn.gpuMillis=5.94
laptop-floor.spawn.heapLiveMB=319.04
laptop-floor.spawn.heapMaxMB=473.25
laptop-floor.spawn.meshQueueMax=6
laptop-floor.spawn.meshQueueMean=0.05
laptop-floor.spawn.nativeLiveMB=68.09
laptop-floor.spawn.nativeMaxMB=88.56
laptop-floor.spawn.poolMillis=0.06
laptop-floor.spawn.renderMillis=2.26
laptop-floor.spawn.serverChunks=1849
laptop-floor.spawn.serverPausedTicks=0
laptop-floor.spawn.serverTickMaxMillis=93.41
laptop-floor.spawn.serverTickMillis=14.30
laptop-floor.spawn.serverTickP95Millis=19.97
laptop-floor.spawn.serverTicksPerSecond=20.02
laptop-floor.spawn.slow1.extractMillis=2.29
laptop-floor.spawn.slow1.frameMillis=21.32
laptop-floor.spawn.slow1.intervalMillis=39.97
laptop-floor.spawn.slow1.poolLateMillis=0
laptop-floor.spawn.slow1.poolMillis=0
laptop-floor.spawn.slow1.renderMillis=7.81
laptop-floor.spawn.slow1.tickMillis=10.84
laptop-floor.spawn.terrainDrawCalls=4.53
laptop-floor.spawn.terrainSections=542.32
laptop-floor.spawn.tickMillis=1.97
laptop-floor.spawn.workerHeapLiveMB=270.99
@@ -0,0 +1,80 @@
# The singleplayer benchmark (ADR 0039's server in a worker): ./gradlew :app-web:benchmark
# -Pbenchmark.singleplayer plays these scenarios in a world the page creates itself, from
# server.properties' seed (the server benchmark's terrain), with options.txt's options but commands
# shown in chat. Same format as benchmark.txt, but there's no server section: nothing runs before
# the world exists, and each rcon step is typed into the game's chat as the player (who may run
# commands: the world allows them). rconwait reads the answer from the page's console.
#
# Unlike the server benchmark, nothing is generated in advance: the page's own server generates
# terrain as the camera reaches it, on the same machine as the page, which is what a player's
# singleplayer world does. Each scenario's figures add the server worker's ticks: ticks a second
# (20 when it keeps up), their length, the chunks it holds, and its heap.
setup
rcon:gamerule advance_time false
rcon:gamerule advance_weather false
rcon:gamerule spawn_mobs false
rcon:gamerule spawn_patrols false
rcon:gamerule spawn_phantoms false
rcon:gamerule spawn_wandering_traders false
rcon:gamerule command_block_output false
rcon:gamerule send_command_feedback false
rcon:gamerule mob_drops false
rcon:time set 6000
rcon:weather clear
rcon:gamemode spectator @s
# The fly-through's engine, as in benchmark.txt: each tick, the camera moves 0.55 blocks east.
rcon:forceload add 0 0
rcon:setblock 0 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @e[tag=incari_camera] at @s run tp @s ~0.55 ~ ~"}
sleep:10000
# Where the world put the player: its spawn area, generated when the world was created.
scenario spawn At the world's spawn, where the player stands when the world opens: the server ticking the area around them, nothing new to generate
measure:30
scenario flythrough A straight flight east at 11 blocks a second, over terrain the page's own server generates as the camera reaches it
rcon:tp @s 0.5 140 0.5 -90 25
# The flight starts over generated terrain: the server makes the start area first.
rcon:gamerule send_command_feedback true
rconwait:execute if loaded 0 64 0 => passed
rconwait:execute if loaded 96 64 0 => passed
rcon:gamerule send_command_feedback false
sleep:5000
rcon:kill @e[tag=incari_camera]
rcon:summon minecraft:armor_stand 0.5 140 0.5 {Tags:["incari_camera"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[-90f,25f]}
rcon:spectate @e[tag=incari_camera,limit=1] @s
sleep:3000
measure:55
# A teleport ends the spectating.
rcon:tp @s 0.5 212 -2026 0 35
rcon:kill @e[tag=incari_camera]
scenario combat Iron golems against waves of vindicators, pillagers and husks in an arena, the server running their AI beside the page
rcon:tp @s 0.5 212 -2026 0 35
# The arena's chunks are generated once the teleport reaches them: building before then fails.
# Feedback on for the waits' answers, off again for the building.
rcon:gamerule send_command_feedback true
rconwait:execute if loaded -17 199 -2017 => passed
rconwait:execute if loaded 17 204 -1983 => passed
rcon:gamerule send_command_feedback false
rcon:fill -17 199 -2017 17 204 -1983 minecraft:barrier outline
rcon:fill -16 199 -2016 16 199 -1984 minecraft:smooth_stone
rcon:summon minecraft:armor_stand 0.5 212 -2026 {Tags:["incari_watch"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[0f,35f]}
rcon:spectate @e[tag=incari_watch,limit=1] @s
rcon*10:summon minecraft:iron_golem 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon:spreadplayers 0 -2000 2 14 under 203 false @e[tag=incari_fighter]
sleep:5000
measure:10
rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
measure:10
rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b}
measure:10
rcon:kill @e[tag=incari_fighter]
rcon:kill @e[tag=incari_watch]
@@ -0,0 +1,164 @@
# Browser check scripts
Step scripts for `./gradlew :app-web:browserCheck`, one step per line (`#` comments). They play the
game in headless Chromium over the DevTools protocol and fail on the first `assert:` or `waitfor:`
that doesn't hold. Positions are fractions of the 1280×720 window. Screenshots go to
`build/browser-checks/`. `BrowserCheck.runStep` lists every step.
```sh
./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/input.steps
```
The page opens as `?name=Player` (straight to the title screen) unless the query names someone;
`-Pbrowser.query=name=` opens Edit Profile first.
## Scripts
| Script | Checks | Needs |
| --- | --- | --- |
| `input.steps` | Text fields, copy/paste, input methods, key names on a French layout, F11, resize, dropped files, Pointer Lock | — |
| `loader.steps` | Loading screen, manifest, service worker caching, reload from cache | — |
| `storage.steps` | An option, a server and an imported pack survive a reload; F2 stores a PNG | — |
| `assets.steps` | Japanese from the asset index: the Unicode font and the language file | assets |
| `audio.steps` | The sound unlock prompt, menu music after the first click, click sounds | assets |
| `audio-positional.steps` | Panning, rear attenuation and distance fade within 1% of the desktop's OpenAL | assets, server |
| `server-join.steps` | Join over `ws://`, chat, the Nether and back, a transfer, a kick and rejoin | server |
| `version-join.steps` | Join a 1.8.9, 1.12.2 or 1.20.4 server through Via; idle 20 s; kick and rejoin | old server |
| `screenshot.steps` | F2 in a world, then the chat link downloads the PNG | server |
| `community-pack.steps` | A real community resource pack loads | a pack |
| `soak.steps` | 30 minutes over fresh terrain; fails if the render thread ever waits 50 ms | server, GPU |
| `voice-talker.steps`, `voice-listener.steps` | Eagler voice chat between two browsers | EaglerXServer |
| `relay-join.steps` | Join a world shared through an Eagler relay | relay |
| `share-host.steps`, `share-guest.steps` | Host a singleplayer world on a relay; a second page joins it | relay |
| `singleplayer.steps` | Create, play, save and reopen a world; World Options; zip download and import; delete | — |
| `singleplayer-lan.steps` | Open to LAN with the server on the page fails cleanly | — |
| `modules.steps` | Module menu, Toggle Sprint, its settings, the profile saved | — |
| `hudeditor.steps` | HUD editor: drag an element, blurred backdrop, saved anchor | — |
| `waypoints.steps` | Minimap, a new waypoint, its tag and beam, the list, the world map, saved data | — |
| `newmodules.steps` | Each module from ADRs 0052–0054 turned on and seen working | — |
| `incari-settings.steps` | Block-break sounds, Incari Settings, the screen recorder (F8) | — |
| `look.steps`, `menus-look.steps` | The Frost look in Potato and Normal; menus checked for overlapping text | — |
| `old-textures.steps` | Built-in packs listed; Old Textures switches Programmer Art on and off | — |
| `sound-retry.steps` | Sounds still play when their first downloads fail | assets |
| `legacy-sounds.steps` | Block sounds on a 1.8.9 server through Via | old server |
| `html-sounds.steps` | The single HTML file plays sounds from disk (`-Pbrowser.html=<file>`) | an HTML build |
Not covered: typing in chat and most F3 keys (check by hand). `input.steps` stops on the Resource
Packs screen because leaving it reloads resources. Ctrl+W and Ctrl+T aren't sent: Chromium acts on
them outside fullscreen.
## Setting up what checks need
**Assets:** `./incari assets` once. The dev server serves them from `work/cache/assets`.
**Server** (`server-join`, `screenshot`, `soak`, `audio-positional`): a vanilla 26.3 server behind
`tools/wsbridge`, with RCON, played as `IncariWeb`. The jar is Mojang's: keep it in `run/` (ignored),
never commit it or its world.
```sh
mkdir -p run/server && cd run/server && echo eula=true > eula.txt
cat > server.properties <<'EOF'
server-ip=127.0.0.1
server-port=25582
online-mode=false
accepts-transfers=true
white-list=false
enable-rcon=true
rcon.port=25592
rcon.password=<a password>
EOF
java -jar server.jar nogui # jar from work/cache/versions/26.3/26.3.json, downloads.server
./gradlew :tools:wsbridge:run --args="--listen 8817 --target 127.0.0.1:25582" # another terminal
INCARI_RCON_PASSWORD=<the password> ./gradlew :app-web:browserCheck \
"-Pbrowser.query=server=ws://127.0.0.1:8817&name=IncariWeb" \
-Pbrowser.rcon=127.0.0.1:25592 -Pbrowser.seconds=300 \
-Pbrowser.steps=@browser-checks/server-join.steps
```
- `rcon:<command>` runs a command; `rconwait:<command> => <regex>` repeats until the reply matches.
- RCON runs as the console, so `~` is the world spawn, not the player. Turn a player with
`execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~`.
- `soak.steps` also wants `-Pbrowser.gpu=gl -Pbrowser.seconds=2100`.
**Old servers** (`version-join`): vanilla 1.8.9, 1.12.2 or 1.20.4 (1.8.9 and 1.12.2 need Java 8;
use `difficulty=0`), each behind its own bridge. The suggested ports: 1.8.9 on 25601 (RCON 25611,
bridge 8801), 1.12.2 on 25602/25612/8802, 1.20.4 on 25603/25613/8803. Add `&via=auto` to
`browser.query`: Via is off unless the join asks for it (ADR 0071).
**EaglerXServer** (`version-join`, voice): BungeeCord with the EaglerXServer plugin (downloaded,
never committed) in front of the 1.8.9 server: `online_mode: false`, lobby `127.0.0.1:25601`,
`inject_address` equal to Bungee's listener host. Join `ws://127.0.0.1:25577`. For voice, set
`voice_service.enable_voice_service: true`, then run both scripts at once (Chromium gets a fake
microphone):
```sh
INCARI_RCON_PASSWORD=<pw> ./gradlew :app-web:browserCheck "-Pbrowser.query=server=ws://127.0.0.1:25577&via=auto&name=VoiceA" \
-Pbrowser.rcon=127.0.0.1:25611 -Pbrowser.seconds=200 -Pbrowser.steps=@browser-checks/voice-talker.steps &
sleep 8
INCARI_RCON_PASSWORD=<pw> ./gradlew :app-web:browserCheck "-Pbrowser.query=server=ws://127.0.0.1:25577&via=auto&name=VoiceB" \
-Pbrowser.rcon=127.0.0.1:25611 -Pbrowser.seconds=200 -Pbrowser.steps=@browser-checks/voice-listener.steps
```
The desktop checks voice signalling alone: `smokeVoiceA` and `smokeVoiceB` together.
**Relay** (`relay-join`, `share-*`): EaglerSPRelay on port 6699 (its jar ships in the EaglercraftX
workspace's `relay_download.zip`; keep it in `run/`).
```sh
# relay-join: relay-host.html is a stand-in host that prints a join code
java -jar run/relay/EaglerSPRelay.jar &
chrome --headless=new --enable-logging=stderr --user-data-dir=$(mktemp -d) \
"file://$PWD/app-web/browser-checks/relay-host.html?relay=ws://127.0.0.1:6699/" 2> host.log &
sleep 5; CODE=$(grep -ao 'incari-relay-code: [a-z0-9]*' host.log | tail -1 | cut -d' ' -f2)
sed "s/CODE/$CODE/" app-web/browser-checks/relay-join.steps > build/relay.steps
./gradlew :app-web:browserCheck -Pbrowser.seconds=150 -Pbrowser.steps=@build/relay.steps
# share-host + share-guest: the guest runs BrowserCheck directly (Gradle runs one build at a time;
# the class path is printed by the first run with --info)
./gradlew :app-web:browserCheck -Pbrowser.seconds=300 \
"-Pbrowser.query=name=Host&world=Shared&seed=2&share=ws://127.0.0.1:6699/" \
-Pbrowser.steps=@browser-checks/share-host.steps | tee host.log &
java -cp <class path> incari.tools.webbuild.BrowserCheck app-web/build/teavm <same --file/--dir args> \
--query "name=Guest&shared=ws://127.0.0.1:6699/|<code from host.log>" --seconds 240 \
--steps-file app-web/browser-checks/share-guest.steps
```
**Community pack:** download one into the ignored `build/`, never the repo. Tested with Faithful 32x:
```sh
mkdir -p app-web/build/community-packs
curl -L -o app-web/build/community-packs/pack.zip \
"https://cdn.modrinth.com/data/w0TnApzs/versions/lDYpMiqk/Faithful%2032x%20-%2026.3.zip"
```
**Audio notes:** Chromium runs muted with `--autoplay-policy=document-user-activation-required`, so
audio starts locked as for a player; the scripts measure the page's master bus. DevTools
evaluations count as a click, so steps before the first click use `holds:` and `until:`. Desktop
reference numbers come from `./gradlew :platform-desktop:openAlReference`.
`window.incariStorage.read(path)` in the page reads a stored file back (handy in the console too).
## By hand, in a real browser
Headless Chromium can't do everything. With `./gradlew :app-web:serve` and a world, check in Chrome
(and Firefox where noted):
- [ ] **Pointer Lock:** clicking into a world hides the cursor; turning is smooth, with no acceleration on Windows.
- [ ] **Escape:** opens the pause menu; Back to Game locks again (perhaps after one more click).
- [ ] **Focus:** Alt+Tab or a tab switch pauses the game; no key stays held on return.
- [ ] **Fullscreen:** F11 and the video setting both toggle it. Inside, Escape pauses, and Ctrl+W and Ctrl+1–9 don't reach the browser.
- [ ] **Ctrl+W while playing:** asks "Leave site?". Nothing asks on the title screen.
- [ ] **F3 and chat:** F3+B/G/H/T work without browser side effects; chat typing, editing, history and Tab completion work.
- [ ] **Clipboard:** paste into chat from another program; copy out of a game text field; F3+C copies the location.
- [ ] **Key names:** on AZERTY, Key Binds shows Z/Q/S/D; names follow a layout switch (Chrome) or are learned as you type (Firefox).
- [ ] **Input methods and dead keys:** Japanese/Chinese composition shows in the field; ´ then e types é.
- [ ] **Resize and density:** window resize, browser zoom and a move to another display redraw sharply; clicks land right.
- [ ] **Dropped files:** a pack .zip or folder dropped on Resource Packs is offered and survives a reload.
- [ ] **Sound by ear:** the unlock note, then music; positional sounds turn with you and fade with distance; each volume slider only moves its category; jukeboxes pause and loop; no gaps between tracks. Also in Firefox.
- [ ] **Chromebook tablet mode:** tapping a text field opens the on-screen keyboard (note if it takes a second tap).
- [ ] **Storage after closing the browser:** an option, a server and a pack are all still there. Over plain http from another machine the console says `indexeddb` and it still works.
- [ ] **A second tab:** warns that the other tab keeps the files.
- [ ] **Downloads:** F2, then the chat link saves the PNG (Chrome, Safari, Firefox).
- [ ] **Closing right after a change:** the change is kept (the same-frame window is accepted, ADR 0011).
@@ -0,0 +1,31 @@
# ADR 0037: the Unicode font and the languages from the asset index (the panorama is no longer
# fetched: menus show Incari's photo). The language list draws 日本語 with the
# Unicode font; picking Japanese fetches its file before the reload, and the title screen is in
# Japanese. Positions are for the 1280x577 viewport headless Chromium gives a 1280x720 window.
#
# ./gradlew :app-web:browserCheck -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/assets.steps
sleep:4000
# The first-run accessibility screen: Continue.
click:0.5,0.945
sleep:3000
shot:build/browser-checks/assets-title.png
# Options, Language..., search for Japan's region name.
click:0.42,0.782
sleep:1500
click:0.376,0.515
sleep:1500
insert:日本
sleep:1000
shot:build/browser-checks/assets-language.png
click:0.5,0.17
sleep:500
# Done reloads the resources in Japanese.
click:0.62,0.945
wait:.*\[Incari\] Assets: fetched 1 files .*
sleep:8000
# Back to the title screen.
click:0.5,0.945
sleep:3000
shot:build/browser-checks/assets-title-ja.png
assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('lang:ja_jp'))
@@ -0,0 +1,82 @@
# Positional sound, measured. The page joins a vanilla 26.3 server over ws:// (as
# server-join.steps does), floats in the sky facing south, and the server plays a mono note
# (block.note_block.harp, heard up to 16 blocks) at known offsets. A meter on the master bus sums
# each channel's energy; the ratios must match what the desktop's OpenAL Soft gives for the same
# offsets (measured by :platform-desktop:openAlReference, ADR 0013):
# 4 blocks to the right left/right = 0.000 (0.0000 / 0.7497)
# 30° to the left (2 left, 3.5 ahead) right/left = 0.236 (0.2169 / 0.9192 before distance)
# 4 blocks ahead vs 4 behind behind/ahead = 0.679 (0.4041 / 0.5955 per ear)
# 12 blocks ahead vs 4 ahead far/near = 0.333 (linear: 1 - d/16)
# README.md ("Audio") has the setup: a server with RCON behind tools/wsbridge.
rcon:whitelist off
rcon:difficulty peaceful
rcon:time set day
rcon:weather clear
# The first-run accessibility screen: Continue, which also unlocks the sound. Quick play connects.
sleep:4000
click:0.5,0.945
waitfor:incariAudio.context.state === 'running'
rconwait:list => IncariWeb
sleep:3000
# In the sky, where nothing else makes a sound: spectator (no footsteps), at a known eye position.
# Facing south (yaw 0): forward is +z, right is -x. The eye is 1.62 above the feet.
rcon:gamemode spectator IncariWeb
rcon:tp IncariWeb 0.5 200 0.5 0 0
sleep:3000
rcon:stopsound IncariWeb
# Music is stereo and starts on its own schedule: mute every stream, now and later, so only the
# note is measured.
rcon:stopsound IncariWeb music
eval:(() => { const play = HTMLMediaElement.prototype.play; HTMLMediaElement.prototype.play = function () { this.muted = true; return play.call(this); }; incariAudio.streams.forEach(e => { e.muted = true; }); return 'music muted'; })()
# The meter: each channel of the master bus, summed over one burst of sound: from the first
# audible block after it's armed until the level falls 30 dB below the burst's peak (by then over
# 99.9% of the note's energy is in). The note rings for about half a second; the game plays quiet
# sounds of its own (ambience) just after, which the burst leaves out.
eval:(() => { const a = incariAudio, ctx = a.context; const p = ctx.createScriptProcessor(1024, 2, 2); const m = { l: 0, r: 0, now: 0, state: 'idle', runs: {} }; p.onaudioprocess = e => { const l = e.inputBuffer.getChannelData(0), r = e.inputBuffer.getChannelData(1); let sl = 0, sr = 0; for (let i = 0; i < l.length; i++) { sl += l[i] * l[i]; sr += r[i] * r[i]; } m.now = sl + sr; if (m.state === 'armed' && m.now > 1e-6) m.state = 'burst'; if (m.state === 'burst') { m.peak = Math.max(m.peak, m.now); if (m.now < m.peak * 1e-3) m.state = 'done'; else { m.l += sl; m.r += sr; } } }; const g = ctx.createGain(); g.gain.value = 0; a.master.connect(p); p.connect(g); g.connect(ctx.destination); m.arm = () => { m.l = 0; m.r = 0; m.peak = 0; m.state = 'armed'; }; m.keep = name => { m.runs[name] = { l: Math.sqrt(m.l), r: Math.sqrt(m.r) }; return name + ': left ' + m.runs[name].l.toFixed(4) + ', right ' + m.runs[name].r.toFixed(4); }; globalThis.incariMeter = m; return 'meter on'; })()
# Quiet first: whatever was playing dies away.
waitfor:incariMeter.now < 1e-7
# 4 blocks to the right.
waitfor:incariMeter.now < 1e-7
eval:incariMeter.arm()
rcon:playsound minecraft:block.note_block.harp master IncariWeb -3.5 201.625 0.5 1 1
waitfor:incariMeter.state === 'done'
eval:incariMeter.keep('right')
# About 30° to the left of straight ahead: +x is left, so 2 blocks that way and 3.5 ahead. Sound
# packets carry positions in eighths of a block, so every offset here is a multiple of one. Write
# every coordinate with a decimal point: commands centre a whole number on its block (4 is 4.5).
waitfor:incariMeter.now < 1e-7
eval:incariMeter.arm()
rcon:playsound minecraft:block.note_block.harp master IncariWeb 2.5 201.625 4.0 1 1
waitfor:incariMeter.state === 'done'
eval:incariMeter.keep('left30')
# 4 blocks ahead, 4 behind, 12 ahead.
waitfor:incariMeter.now < 1e-7
eval:incariMeter.arm()
rcon:playsound minecraft:block.note_block.harp master IncariWeb 0.5 201.625 4.5 1 1
waitfor:incariMeter.state === 'done'
eval:incariMeter.keep('ahead4')
waitfor:incariMeter.now < 1e-7
eval:incariMeter.arm()
rcon:playsound minecraft:block.note_block.harp master IncariWeb 0.5 201.625 -3.5 1 1
waitfor:incariMeter.state === 'done'
eval:incariMeter.keep('behind4')
waitfor:incariMeter.now < 1e-7
eval:incariMeter.arm()
rcon:playsound minecraft:block.note_block.harp master IncariWeb 0.5 201.625 12.5 1 1
waitfor:incariMeter.state === 'done'
eval:incariMeter.keep('ahead12')
# The ratios, against the desktop's.
eval:JSON.stringify(Object.fromEntries(Object.entries(incariMeter.runs).map(([k, v]) => [k, [+v.l.toFixed(4), +v.r.toFixed(4)]])))
eval:'right: left/right ' + (incariMeter.runs.right.l / incariMeter.runs.right.r).toFixed(4) + '; left30: right/left ' + (incariMeter.runs.left30.r / incariMeter.runs.left30.l).toFixed(4) + '; behind/ahead ' + (incariMeter.runs.behind4.l / incariMeter.runs.ahead4.l).toFixed(4) + '; far/near ' + (incariMeter.runs.ahead12.l / incariMeter.runs.ahead4.l).toFixed(4)
assert:incariMeter.runs.right.r > 0.01 && incariMeter.runs.right.l / incariMeter.runs.right.r < 0.005
assert:Math.abs(incariMeter.runs.left30.r / incariMeter.runs.left30.l - 0.2360) < 0.01
assert:Math.abs(incariMeter.runs.ahead4.l / incariMeter.runs.ahead4.r - 1) < 0.005
assert:Math.abs(incariMeter.runs.behind4.l / incariMeter.runs.ahead4.l - 0.6787) < 0.01
assert:Math.abs(incariMeter.runs.ahead12.l / incariMeter.runs.ahead4.l - 0.3333) < 0.01
shot:build/browser-checks/audio-positional.png
@@ -0,0 +1,44 @@
# Sound on the title screen. The page starts with its audio context suspended, as a player's
# browser does (BrowserCheck runs Chromium with --autoplay-policy=document-user-activation-required, muted on
# this machine's speakers), and shows the unlock prompt; the first click resumes it. Then the menu
# music streams through a media element, and a button's click plays. Needs the assets
# `./incari assets` downloaded (the dev server serves them). README.md ("Audio") has the command.
# --- Before any gesture: the context waits, and the prompt says so ---
# (The check starts once the game loop runs; by then the sound engine has started.)
# Until the click below, steps use holds:/until:, which don't count as a click themselves.
sleep:3000
until:globalThis.incariAudio !== undefined && incariAudio.context.state === 'suspended'
holds:document.getElementById('incari-audio-unlock') !== null
# The menu music has been asked for by now (100 ticks after the game starts) and waits for the context.
until:incariAudio.pending.length === 1 && incariAudio.streamsStarted === 0 && incariAudio.buffersStarted === 0
shot:build/browser-checks/audio-prompt.png
# --- The first-run accessibility screen's Continue: that click unlocks the sound ---
click:0.5,0.945
waitfor:incariAudio.context.state === 'running' && document.getElementById('incari-audio-unlock') === null
# The waiting music starts, and its element streams: it plays long before the whole file could have
# been decoded, and its position moves.
waitfor:incariAudio.streamsStarted >= 1 && incariAudio.streams.some(e => !e.paused && e.currentTime > 0.5)
eval:incariAudio.streams.map(e => e.src.slice(0, 5) + ' ' + e.currentTime.toFixed(2) + 's of ' + e.duration.toFixed(1) + 's').join(', ')
sleep:2000
assert:incariAudio.streams.some(e => !e.paused && e.currentTime > 2)
# --- A meter on the master bus: each channel's energy, from every sample the page plays ---
eval:(() => { const a = incariAudio, ctx = a.context; const p = ctx.createScriptProcessor(4096, 2, 2); const m = { l: 0, r: 0, n: 0 }; p.onaudioprocess = e => { const l = e.inputBuffer.getChannelData(0), r = e.inputBuffer.getChannelData(1); for (let i = 0; i < l.length; i++) { m.l += l[i] * l[i]; m.r += r[i] * r[i]; } m.n += l.length; }; const g = ctx.createGain(); g.gain.value = 0; a.master.connect(p); p.connect(g); g.connect(ctx.destination); globalThis.incariMeter = m; return 'meter on'; })()
sleep:1000
# The music reaches the output: stereo, so both channels.
assert:incariMeter.n > 40000 && incariMeter.l > 0 && incariMeter.r > 0
# --- A UI sound: a button's click (a stereo sound, not positioned) ---
eval:globalThis.clicksBefore = incariAudio.buffersStarted
# Options... (its click), Escape back to the title screen, Options... again.
click:0.42,0.78
sleep:1500
shot:build/browser-checks/audio-options.png
key:Escape
sleep:1000
click:0.42,0.78
sleep:500
waitfor:incariAudio.buffersStarted >= clicksBefore + 2
eval:'buffers started: ' + incariAudio.buffersStarted + ', voices: ' + incariAudio.voices
@@ -0,0 +1,41 @@
# A real community resource pack loads. It's the one at build/community-packs/pack.zip,
# downloaded when the check runs, never committed (the browser-checks README says how; the check
# was run with Faithful 32x for 26.3). It's dropped on the Resource Packs screen, copied in,
# selected, and the game reloads its resources with it; then the page is reloaded and the game
# starts with it from storage. Positions are for the 1280x577 viewport.
#
# ./gradlew :app-web:browserCheck -Pbrowser.seconds=500 -Pbrowser.steps=@browser-checks/community-pack.steps
sleep:4000
# The first-run accessibility screen: Continue.
click:0.5,0.945
sleep:3000
# Options, Resource Packs, then the pack dropped on the screen and "Yes" to copy it.
click:0.42,0.782
sleep:1500
click:0.376,0.598
sleep:2000
drop:0.5,0.5,build/community-packs/pack.zip
sleep:4000
click:0.38,0.585
sleep:3000
waitfor:window.incariStorage.list('/incari/game/resourcepacks').then(p => p.includes('/incari/game/resourcepacks/pack.zip'))
move:0.19,0.277
sleep:300
click:0.19,0.277
sleep:1000
shot:build/browser-checks/community-pack-selected.png
# Done: the game reloads its resources with the pack, which must finish without errors.
click:0.623,0.945
wait:.*Reloading ResourceManager.*file/pack\.zip.*
wait:\[Incari\] Main loop running.*
sleep:3000
shot:build/browser-checks/community-pack-title.png
waitfor:window.incariStorage.pending() === 0
# After a reload the game starts with it.
reload
wait:\[Incari\] Client jar: .* from storage.*
wait:.*Reloading ResourceManager.*file/pack\.zip.*
wait:\[Incari\] Main loop running.*
sleep:4000
shot:build/browser-checks/community-pack-after-reload.png
@@ -0,0 +1,41 @@
# The single HTML file's sounds (ADR 0062: all but music, smaller): opened from the disk, a quick world's block
# breaks play their sounds from the file. Build it first (./incari build --html --only fast), then:
#
# ./gradlew :app-web:browserCheck -Pteavm.fast -Pbrowser.html=$PWD/dist/incari.html -Pbrowser.gpu=gl \
# -Pbrowser.seconds=300 "-Pbrowser.query=name=Player&world=Html&seed=1" \
# -Pbrowser.steps=@browser-checks/html-sounds.steps
sleep:6000
# The first-run accessibility screen: Continue (also the gesture the audio waits for).
click:0.5,0.945
wait:.*logged in with entity id.*
sleep:6000
eval:globalThis.before = incariAudio.buffersStarted
key:KeyT
sleep:800
type:/fill ~-4 ~ ~-4 ~4 ~4 ~4 minecraft:air
key:Enter
sleep:800
key:KeyT
sleep:800
type:/fill ~-4 ~-3 ~-4 ~4 ~-1 ~4 minecraft:stone
key:Enter
sleep:800
key:KeyT
sleep:800
type:/gamemode creative
key:Enter
sleep:800
key:KeyT
sleep:800
type:/tp @s ~ ~ ~ 0 90
key:Enter
sleep:1500
click:0.5,0.5
sleep:1500
click:0.5,0.5
sleep:1500
click:0.5,0.5
sleep:3000
eval:'buffers started: ' + (incariAudio.buffersStarted - before)
@@ -0,0 +1,42 @@
# The HUD editor in the page, in the Potato GUI preset (the default), where its blurred
# backdrop is drawn a few times a second and kept in between (BackdropCache). Creates a world, turns
# Toggle Sprint on from the module menu, opens Edit HUD beside the search, drags the status line
# from the top left to the right edge halfway down, and checks the profile stored in OPFS has it
# anchored on the right. No server needed. Positions are for the 1280x577 viewport (GUI scale 2,
# 640x288).
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/hudeditor.steps
sleep:4000
# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults.
click:0.5,0.945
sleep:3000
click:0.2,0.43
sleep:4000
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:8000
# --- The module menu: Toggle Sprint on, then Edit HUD ---
key:ShiftRight
sleep:1500
click:0.545,0.215
sleep:500
click:0.798,0.104
sleep:2000
move:0.5,0.7
sleep:500
shot:build/browser-checks/hudeditor-potato.png
# --- The status line dragged to the right edge, halfway down: it snaps there ---
drag:0.019,0.021,0.953,0.5
sleep:800
shot:build/browser-checks/hudeditor-placed.png
# --- Back to the module menu and the game; the placement is stored ---
key:Escape
sleep:800
key:Escape
sleep:2500
until:window.incariStorage.pending() === 0
assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "modules", "profiles"]) d = await d.getDirectoryHandle(p); const text = await (await (await d.getFileHandle("Default.json")).getFile()).text(); console.log("[check] profile: " + text.replace(/\s+/g, " ")); const status = JSON.parse(text).modules.togglesprint.hud.status; return status.anchor === "right" && status.x === 2; })()
@@ -0,0 +1,75 @@
# ADR 0062: in a quick world (-Pbrowser.query=name=Player&world=Batch&seed=1): the pause menu's one
# Incari Settings button and its screen, the screen recorder downloading a video (F8 twice), and
# block-breaking sounds: each break's sound fetched, decoded and started. No server needed.
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 \
# "-Pbrowser.query=name=Player&world=Batch&seed=1" -Pbrowser.steps=@browser-checks/incari-settings.steps
downloads:build/browser-checks/downloads
sleep:4000
# The first-run accessibility screen: Continue (also the gesture the audio waits for).
click:0.5,0.945
wait:.*logged in with entity id.*
sleep:6000
# Every sound file fetched from now on, with its status and time.
eval:(() => { const of = window.fetch; globalThis.fetchLog = []; window.fetch = (u, ...a) => { const t = performance.now(); return of(u, ...a).then(r => { if (String(u).includes('objects')) fetchLog.push(r.status + ' ' + Math.round(performance.now() - t) + 'ms'); return r; }, e => { fetchLog.push('ERR ' + u); throw e; }); }; return 'logging'; })()
eval:'buffers started before: ' + incariAudio.buffersStarted
# --- On a dirt floor, looking straight down: creative breaks a block a click ---
key:KeyT
sleep:800
type:/fill ~-4 ~ ~-4 ~4 ~4 ~4 minecraft:air
key:Enter
sleep:800
key:KeyT
sleep:800
type:/fill ~-4 ~-3 ~-4 ~4 ~-1 ~4 minecraft:dirt
key:Enter
sleep:800
key:KeyT
sleep:800
type:/gamemode creative
key:Enter
sleep:800
key:KeyT
sleep:800
type:/tp @s ~ ~ ~ 0 90
key:Enter
sleep:1500
click:0.5,0.5
sleep:800
click:0.5,0.5
sleep:800
click:0.5,0.5
sleep:2000
eval:'buffers started after breaking: ' + incariAudio.buffersStarted + ', fetches: ' + JSON.stringify(fetchLog)
shot:build/browser-checks/batch-broken.png
# --- Survival: held, the dirt's hit sounds every 4 ticks and its break ---
key:KeyT
sleep:800
type:/gamemode survival
key:Enter
sleep:1000
eval:globalThis.beforeHold = incariAudio.buffersStarted
hold:0.5,0.5,4000
sleep:1500
eval:'buffers started while holding: ' + (incariAudio.buffersStarted - beforeHold) + ', fetches: ' + JSON.stringify(fetchLog)
shot:build/browser-checks/batch-mined.png
# --- The pause menu and Incari Settings ---
key:Escape
sleep:1500
shot:build/browser-checks/batch-pause.png
# --- The recorder: F8 starts, F8 stops, and the video downloads ---
key:Escape
sleep:1000
key:F8
waitfor:globalThis.incariRecorder && incariRecorder.state === 'recording'
sleep:4000
shot:build/browser-checks/batch-recording.png
key:F8
waitfor:incariRecorder.state === 'idle'
eval:'recorder error: ' + incariRecorder.error
download:incari-.*\.(webm|mp4)
@@ -0,0 +1,170 @@
# Keyboard, mouse, text, clipboard, key names, fullscreen, resize and drops, on the title
# screen and its menus. Positions are for the 1280x577
# viewport headless Chromium gives a 1280x720 window.
#
# ./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/input.steps
# A French (AZERTY) layout, as Chrome's Keyboard Map API would report it, for every load from now on.
init:(function() { var fr = {KeyQ: 'a', KeyW: 'z', KeyA: 'q', KeyZ: 'w', KeyM: ',', Semicolon: 'm', Digit1: '&', Digit2: 'é', Minus: ')', BracketLeft: '^'}; var kb = navigator.keyboard; if (kb) kb.getLayoutMap = function() { return Promise.resolve(new Map(Object.entries(fr))); }; })();
# The reloaded page's start (the first page's heartbeats may still be queued before it).
wait:\[Incari\] Client jar.*
wait:\[Incari\] Main loop running.*
sleep:4000
# The first-run accessibility screen: Continue.
click:0.5,0.945
sleep:3000
shot:build/browser-checks/title.png
# --- Nothing on the title screen holds the mouse, so leaving asks nothing ---
assert:!document.getElementById('incari-canvas').__incariGuard
# --- Fullscreen in and out with F11 ---
key:F11
waitfor:document.fullscreenElement === document.getElementById('incari-canvas')
sleep:1000
assert:document.getElementById('incari-canvas').width === screen.width
shot:build/browser-checks/fullscreen.png
key:F11
waitfor:!document.fullscreenElement
sleep:1000
assert:document.getElementById('incari-canvas').width === innerWidth
# Leaving from the browser's side (Escape, the browser's own controls) turns the game's option off,
# so the next F11 enters again rather than doing nothing.
key:F11
waitfor:!!document.fullscreenElement
eval:document.exitFullscreen()
waitfor:!document.fullscreenElement
sleep:1000
key:F11
waitfor:!!document.fullscreenElement
eval:document.exitFullscreen()
waitfor:!document.fullscreenElement
sleep:1000
# --- Resize and density ---
resize:960,540
waitfor:document.getElementById('incari-canvas').width === 960 && document.getElementById('incari-canvas').height === 540
sleep:1000
shot:build/browser-checks/resized.png
# A denser display: the backing store follows the device-pixel size the browser reports. (Headless
# Chromium's emulated density reports the CSS size here, as its compositor does the scaling; a real
# 2x display reports twice it, which the unit tests cover.)
resize:640,360,2
waitfor:devicePixelRatio === 2 && document.getElementById('incari-canvas').clientWidth === 640
waitfor:new Promise(r => { const c = document.getElementById('incari-canvas'); const o = new ResizeObserver(es => { const d = es[0].devicePixelContentBoxSize[0]; o.disconnect(); r(c.width === d.inlineSize && c.height === d.blockSize); }); o.observe(c, {box: 'device-pixel-content-box'}); })
sleep:1000
shot:build/browser-checks/dense.png
resize:1280,577
waitfor:document.getElementById('incari-canvas').width === 1280 && document.getElementById('incari-canvas').height === 577
sleep:1500
# Clicks land where the game drew after all that: Multiplayer, then Proceed on the safety screen.
click:0.5,0.534
sleep:1500
shot:build/browser-checks/multiplayer-warning.png
click:0.376,0.688
sleep:1500
# Add Server.
click:0.662,0.854
sleep:1500
# --- Text: typing, selection, copy and paste, an input method ---
# The name field has the focus, so the page's text input element has it too.
assert:document.activeElement === document.getElementById('incari-canvas-text')
key:Control+KeyA
type:Hello Incari
clipboard:
key:Control+KeyA
key:Control+KeyC
waitfor:navigator.clipboard.readText().then(t => t === 'Hello Incari')
clipboard: & pasted
key:End
key:Control+KeyV
# Shift+Left twice selects the last two characters, and Backspace deletes them.
down:ShiftLeft
key:ArrowLeft
key:ArrowLeft
up:ShiftLeft
key:Backspace
# An input method: a composition shows in the field, then commits.
compose:にほ
sleep:500
shot:build/browser-checks/composing.png
insert:日本
type:!
key:Control+KeyA
key:Control+KeyX
waitfor:navigator.clipboard.readText().then(t => t === 'Hello Incari & past日本!')
sleep:500
shot:build/browser-checks/cut.png
# Tab moves to the address field; the browser mustn't move its own focus.
key:Tab
type:localhost
key:Control+KeyA
key:Control+KeyC
waitfor:navigator.clipboard.readText().then(t => t === 'localhost')
assert:document.activeElement === document.getElementById('incari-canvas-text')
# Escape leaves the screen, and text input with it.
key:Escape
sleep:800
key:Escape
sleep:800
waitfor:document.activeElement !== document.getElementById('incari-canvas-text')
# --- Key names in the player's layout, and binding a key ---
# Options, Controls, Key Binds.
click:0.42,0.782
sleep:1500
click:0.623,0.432
sleep:1500
click:0.623,0.161
sleep:1500
# With AZERTY, strafe left is Q and walking forward Z; the rest keep their US names.
shot:build/browser-checks/key-binds.png
# Bind "Walk Forward" to the key right of Tab: AZERTY's A.
click:0.617,0.64
sleep:500
key:KeyQ
sleep:800
shot:build/browser-checks/key-bound.png
# Back to W, which the Reset button next to it does.
click:0.722,0.64
sleep:800
key:Escape
sleep:800
key:Escape
sleep:800
# --- F3 and browser shortcuts: the game gets them, the browser does nothing ---
# (On the Options screen, where these keys change nothing in the game.)
# A mark on the page that a reload or navigation would wipe.
eval:window.__incariCheckMark = 1
# F3 shows the debug screen here too, memory lines and all; the game keeps running under it, and a
# second F3 hides it.
key:F3
sleep:1500
shot:build/browser-checks/debug-screen.png
wait:\[Incari\] Main loop running.*
key:F3
sleep:500
# Not Ctrl+W or Ctrl+T: Chromium keeps those outside fullscreen whatever the page does (sent here,
# Ctrl+W closes the tab). The leave-page prompt and Keyboard Lock are on the manual checklist.
key:F5
key:Alt+ArrowLeft
sleep:1000
assert:window.__incariCheckMark === 1
assert:document.activeElement === document.getElementById('incari-canvas')
shot:build/browser-checks/after-shortcuts.png
# --- A dropped file ---
# Resource Packs, then a file dropped on it: the game asks whether to copy it in.
click:0.376,0.598
sleep:2000
drop:0.5,0.5,browser-checks/README.md
sleep:2000
shot:build/browser-checks/dropped.png
# "No". Leaving the pack screen reloads resources, which restarts the sound engine, and that
# crashes the browser build today (the old sound thread ends with an IllegalMonitorStateException;
# audio has checks of its own): the script stops here.
click:0.62,0.585
sleep:1000
shot:build/browser-checks/packs.png
@@ -0,0 +1,27 @@
# F1 (2026-10-12): block sounds on a 1.8.9 server through Via. The server behind tools/wsbridge on
# 8801 with RCON on 25611 (run/servers, INCARI_RCON_PASSWORD=incari-dev):
# "-Pbrowser.query=server=ws://127.0.0.1:8801&name=IncariWeb" -Pbrowser.rcon=127.0.0.1:25611
sleep:4000
click:0.5,0.945
sleep:15000
eval:(() => { const of = window.fetch; globalThis.fetchLog = []; window.fetch = (u, ...a) => { const t = performance.now(); return of(u, ...a).then(r => { if (String(u).includes('objects')) fetchLog.push(r.status + ' ' + Math.round(performance.now() - t) + 'ms'); return r; }, e => { fetchLog.push('ERR ' + u); throw e; }); }; return 'logging'; })()
rcon:execute IncariWeb ~ ~ ~ fill ~-3 ~ ~-3 ~3 ~3 ~3 air
rcon:execute IncariWeb ~ ~ ~ fill ~-3 ~-3 ~-3 ~3 ~-1 ~3 dirt
rcon:execute IncariWeb ~ ~ ~ tp IncariWeb ~ ~ ~ 0 90
rcon:gamemode 1 IncariWeb
sleep:2000
eval:globalThis.before = incariAudio.buffersStarted
click:0.5,0.5
sleep:800
click:0.5,0.5
sleep:800
click:0.5,0.5
sleep:2000
eval:'creative breaks started ' + (incariAudio.buffersStarted - before) + ', fetches ' + JSON.stringify(fetchLog)
rcon:gamemode 0 IncariWeb
sleep:1500
eval:globalThis.before = incariAudio.buffersStarted
hold:0.5,0.5,4000
sleep:1500
eval:'survival mining started ' + (incariAudio.buffersStarted - before) + ', fetches ' + JSON.stringify(fetchLog)
shot:build/browser-checks/legacy-mined.png
@@ -0,0 +1,26 @@
# The loader page. The loading screen reads the build manifest, shows the steps, and goes at
# the game's first frame; the service worker takes the page on its first visit and keeps the build,
# so a reload loads the module through it. No server needed.
#
# ./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/loader.steps
# (The check waits for the game's loop before the first step, so the loader's own lines are past.)
until:window.incariBuild !== undefined && /^[0-9a-f]{64}$/.test(window.incariBuild.id) && window.incariBuild.pack !== null
# The first frame is drawn: the screen has gone.
until:document.getElementById('incari-loader').hidden === true
# The service worker controls the page, and the module went through it.
until:navigator.serviceWorker.controller !== null
holds:performance.getEntriesByType('resource').some(e => e.name.includes('incari.wasm?v=') && e.workerStart > 0)
# It's cached under its version (stored while the page compiled it; 157 MB can take a moment).
sleep:5000
until:caches.open('incari-build-v1').then(c => c.keys()).then(k => k.some(r => r.url.includes('incari.wasm?v=')))
until:caches.open('incari-build-v1').then(c => c.keys()).then(k => k.some(r => r.url.includes('incari.pack?v=')))
# A returning player: the module comes from the service worker's cache.
reload
wait:\[Incari\] Loader: build [0-9a-f]+ .*
wait:\[Incari\] Asset pack: 2 files, from storage.*
wait:\[Incari\] Main loop running.*
holds:performance.getEntriesByType('resource').some(e => e.name.includes('incari.wasm?v=') && e.workerStart > 0)
until:document.getElementById('incari-loader').hidden === true
shot:build/browser-checks/loader.png
@@ -0,0 +1,52 @@
# ADR 0048: the client's look in the page. The title screen in Potato, the options, the module
# menu, then Normal switched on from the module menu's sidebar: the title again (snow, blur), then a
# new world's pause menu, inventory and HUD. Red Hat Display is drawn by the browser's canvas
# (PlatformFonts). No server needed. Positions are for the 1280x577 viewport (GUI scale 2, 640x288).
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/look.steps
sleep:4000
# The first-run accessibility screen: Continue.
click:0.5,0.945
sleep:3000
shot:build/browser-checks/look-potato-title.png
# Options (the left half of the column's last row), and back.
click:0.133,0.691
sleep:1500
shot:build/browser-checks/look-potato-options.png
key:Escape
sleep:1000
# Modules, then the sidebar's GUI entry: Normal.
click:0.2,0.604
sleep:1500
shot:build/browser-checks/look-potato-modules.png
click:0.2,0.771
sleep:1000
shot:build/browser-checks/look-normal-modules.png
key:Escape
sleep:2000
shot:build/browser-checks/look-normal-title.png
# Singleplayer, Create New World with the defaults.
click:0.2,0.43
sleep:3000
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:8000
shot:build/browser-checks/look-normal-hud.png
key:Escape
sleep:1500
shot:build/browser-checks/look-normal-pause.png
key:Escape
sleep:800
key:KeyE
sleep:1500
shot:build/browser-checks/look-normal-inventory.png
key:Escape
sleep:800
down:Tab
sleep:800
shot:build/browser-checks/look-normal-tab.png
up:Tab
@@ -0,0 +1,27 @@
# F2 (2026-10-12): the menus as the browser draws their text, to look for text drawn over text.
# Title, Multiplayer (the featured server), Options, the module menu, Incari Settings. No server.
sleep:4000
click:0.5,0.945
sleep:3000
shot:build/browser-checks/menus-title.png
click:0.2,0.49
sleep:1500
# The first visit's warning: Proceed.
click:0.375,0.688
sleep:3000
shot:build/browser-checks/menus-servers.png
key:Escape
sleep:1500
click:0.13,0.74
sleep:2000
shot:build/browser-checks/menus-options.png
key:Escape
sleep:1500
click:0.2,0.573
sleep:2000
shot:build/browser-checks/menus-modules.png
key:Escape
sleep:1500
click:0.3,0.657
sleep:2000
shot:build/browser-checks/menus-incari-settings.png
@@ -0,0 +1,45 @@
# ADR 0046: the module framework in the page. Creates a world, opens the module menu with
# Right Shift, turns Toggle Sprint on with its switch, opens its generated settings, then latches
# sprint with a tap of Left Control and walks: the HUD says "[Sprinting (Toggled)]". The profile is
# stored in OPFS with the module on. No server needed. Positions are for the 1280x577 viewport.
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/modules.steps
sleep:4000
# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults.
click:0.5,0.945
sleep:3000
click:0.2,0.43
sleep:4000
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:8000
# --- The module menu: Right Shift, then Toggle Sprint's switch and its settings ---
key:ShiftRight
sleep:1500
shot:build/browser-checks/modules-menu.png
click:0.545,0.215
sleep:500
shot:build/browser-checks/modules-menu-on.png
click:0.553,0.292
sleep:1500
shot:build/browser-checks/modules-settings.png
key:Escape
sleep:800
key:Escape
sleep:1500
# --- A tap of Left Control latches sprinting; W alone then sprints and the HUD says so ---
key:ControlLeft
sleep:300
down:KeyW
sleep:1500
shot:build/browser-checks/modules-hud.png
up:KeyW
sleep:500
# --- The profile is stored with Toggle Sprint on ---
sleep:2000
until:window.incariStorage.pending() === 0
assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "modules", "profiles"]) d = await d.getDirectoryHandle(p); const text = await (await (await d.getFileHandle("Default.json")).getFile()).text(); console.log("[check] profile: " + text.replace(/\s+/g, " ")); return JSON.parse(text).modules.togglesprint.enabled === true; })()
@@ -0,0 +1,229 @@
# ADRs 0052-0054: the fifteen new modules in the page. Creates a world, turns each on from the
# module menu (its search narrows the grid to the one card, whose switch is the first card's), then
# shows the HUD, the crosshair and cooldown after a swing, Freelook with Left Alt held, F2 and the
# pause menu's Screenshots button, and the gallery. No server needed. Positions are for the
# 1280x577 viewport (GUI scale 2, 640x288).
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/newmodules.steps
sleep:4000
# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults.
click:0.5,0.945
sleep:3000
click:0.2,0.43
sleep:4000
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:8000
# --- Keystrokes ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Keystrokes
sleep:400
shot:build/browser-checks/newmodules-search.png
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- CPS ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:CPS
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- FPS Display ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:FPS Display
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Reach Display ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Reach Display
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Coordinates ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Coordinates
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Shield & Totem ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Shield & Totem
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Cooldown Indicator ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Cooldown Indicator
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- 1.7 Animations ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:1.7 Animations
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Freelook ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Freelook
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Crosshair Editor ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Crosshair Editor
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Low Shield ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Low Shield
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Weather Changer ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Weather Changer
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Theme Editor ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Theme Editor
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Screenshot Manager ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Screenshot Manager
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
# --- Shulker Tooltips ---
key:ShiftRight
sleep:1200
click:0.40,0.125
sleep:600
type:Shulker Tooltips
sleep:400
click:0.545,0.215
sleep:300
key:Escape
sleep:800
key:ShiftRight
sleep:1500
shot:build/browser-checks/newmodules-menu.png
key:Escape
sleep:2000
# --- The HUD, the crosshair, a swing's cooldown ---
down:KeyW
sleep:300
click:0.5,0.5
sleep:150
shot:build/browser-checks/newmodules-hud.png
up:KeyW
sleep:1500
# --- Freelook: Left Alt held ---
down:AltLeft
sleep:600
shot:build/browser-checks/newmodules-freelook.png
up:AltLeft
sleep:800
# --- F2, then the pause menu with its Screenshots button ---
key:F2
sleep:2500
key:Escape
sleep:1500
shot:build/browser-checks/newmodules-pause.png
until:window.incariStorage.pending() === 0
assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "screenshots"]) d = await d.getDirectoryHandle(p); let count = 0; for await (const [name] of d.entries()) { if (name.endsWith(".png")) count++; } console.log("[check] screenshots: " + count); return count > 0; })()
@@ -0,0 +1,63 @@
# ADR 0055: the built-in packs and Old Textures in the page. Programmer Art and High Contrast are
# fetched at start and listed in the Resource Packs screen. Selecting Programmer Art there reloads
# the resources with its zip and turns Old Textures on; turning the module off and on in the module
# menu takes the pack out and puts it back. Then a new world in the old textures. No server
# needed. Positions are for the 1280x577 viewport (GUI scale 2, 640x288).
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/old-textures.steps
# The packs' fetch is logged before the steps start ("Assets: fetched 2 files (705 KB)"); the
# reload with programmer_art below shows its zip was there.
sleep:4000
# The first-run accessibility screen: Continue.
click:0.5,0.945
sleep:3000
# Options (the left half of the column's last row), Resource Packs.
click:0.133,0.691
sleep:1500
click:0.376,0.598
sleep:2500
shot:build/browser-checks/old-textures-packs.png
# Programmer Art's icon (the second available pack) moves it to Selected; Done reloads with it.
move:0.195,0.41
sleep:300
click:0.195,0.41
sleep:1000
shot:build/browser-checks/old-textures-selected.png
click:0.623,0.945
wait:.*Reloading ResourceManager.*programmer_art.*
sleep:8000
assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('"programmer_art"'))
waitfor:window.incariStorage.read('/incari/game/incari/modules/profiles/Default.json').then(t => t !== null && JSON.parse(t).modules.oldtextures.enabled === true)
# Back to the title screen.
key:Escape
sleep:2000
shot:build/browser-checks/old-textures-title.png
# The module menu: Old Textures off takes the pack out.
click:0.2,0.604
sleep:1500
click:0.40,0.125
sleep:600
type:Old Textures
sleep:400
shot:build/browser-checks/old-textures-module.png
click:0.545,0.215
wait:.*Reloading ResourceManager.*
sleep:8000
assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && !t.includes('"programmer_art"'))
# And on again puts it back.
click:0.545,0.215
wait:.*Reloading ResourceManager.*programmer_art.*
sleep:8000
assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('"programmer_art"'))
key:Escape
sleep:1500
# Singleplayer, Create New World with the defaults, in the old textures.
click:0.2,0.43
sleep:4000
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:10000
shot:build/browser-checks/old-textures-world.png
@@ -0,0 +1,133 @@
<!doctype html>
<!--
A stand-in for an Eagler player sharing a world through a relay (ADR 0019), for
relay-join.steps: opened in headless Chromium beside the game's page, it shares a "world" on the
relay given as ?relay=ws://..., prints its join code to the console ("incari-relay-code: ..."),
accepts one client over WebRTC, answers its login as a shared world's host does (1.8, with
Eagler's login changes), sends the join and a chat message, and keeps the connection alive.
Nothing of a game runs here: just enough packets for the client to reach the world and show chat.
-->
<meta charset="utf-8">
<title>Incari relay host (test)</title>
<script>
'use strict';
const params = new URLSearchParams(location.search);
const relayUrl = params.get('relay') || 'ws://127.0.0.1:6699/';
const log = (...a) => console.log('incari-relay-host:', ...a);
// --- Relay messages ------------------------------------------------------------------------
const ascii8 = (s) => [s.length, ...Array.from(s, (c) => c.charCodeAt(0))];
const bytes16 = (s) => [s.length >> 8, s.length & 255, ...Array.from(s, (c) => c.charCodeAt(0))];
function readRelay(buf) {
const b = new Uint8Array(buf); let i = 1;
const a8 = () => { const n = b[i++]; const s = String.fromCharCode(...b.slice(i, i + n)); i += n; return s; };
const a16 = () => { const n = (b[i] << 8) | b[i + 1]; i += 2; const s = String.fromCharCode(...b.slice(i, i + n)); i += n; return s; };
switch (b[0]) {
case 0x00: { const type = b[i++]; const version = b[i++]; return { id: 0, type, version, code: a8() }; }
case 0x01: { const n = (b[1] << 8) | b[2]; i = 3; const servers = [];
for (let k = 0; k < n; k++) { const t = String.fromCharCode(b[i++]); const url = a16(); const u = a8(); const p = a8();
servers.push(t === 'T' ? { urls: url, username: u, credential: p } : { urls: url }); }
return { id: 1, servers }; }
case 0x02: return { id: 2, client: a8() };
case 0x03: return { id: 3, peer: a8(), text: a16() };
case 0x04: return { id: 4, peer: a8(), text: a16() };
case 0x05: return { id: 5, client: a8() };
case 0x06: return { id: 6, client: a8() };
case 0xff: return { id: 255, code: b[1], text: (i = 2, a16()) };
default: return { id: b[0] };
}
}
// --- 1.8 packets, as the host's integrated server writes them --------------------------------
function varint(v) { const out = []; do { let t = v & 0x7f; v >>>= 7; if (v) t |= 0x80; out.push(t); } while (v); return out; }
function str(s) { const u = new TextEncoder().encode(s); return [...varint(u.length), ...u]; }
function i32(v) { return [(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]; }
function f64(v) { const d = new DataView(new ArrayBuffer(8)); d.setFloat64(0, v); return [...new Uint8Array(d.buffer)]; }
function f32(v) { const d = new DataView(new ArrayBuffer(4)); d.setFloat32(0, v); return [...new Uint8Array(d.buffer)]; }
// A whole packet on the data channel: the "whole" kind byte, then the packet.
function packet(id, body) { return new Uint8Array([0, ...varint(id), ...body]); }
function readVarint(b, at) { let v = 0, s = 0, x; do { x = b[at.i++]; v |= (x & 0x7f) << s; s += 7; } while (x & 0x80); return v; }
let channel = null;
function onPacket(b) {
const at = { i: 0 };
const id = readVarint(b, at);
if (!onPacket.loggedIn) {
if (id !== 0) { log('expected Login Start, got', id); return; }
const n = readVarint(b, at);
const name = new TextDecoder().decode(b.slice(at.i, at.i + n)); at.i += n;
const skin = readVarint(b, at); at.i += skin;
const cape = readVarint(b, at); at.i += cape;
const protocols = readVarint(b, at); at.i += protocols;
const brandBytes = b.length - at.i;
log('login from', name, 'skin', skin, 'bytes, cape', cape, 'bytes, protocols', protocols, 'bytes, brand', brandBytes, 'bytes');
onPacket.loggedIn = true;
const uuid = '00000000-0000-3000-8000-' + Array.from(name).map((c) => c.charCodeAt(0).toString(16)).join('').padEnd(12, '0').slice(0, 12);
// Login Success, ending with the Eagler protocol chosen (4), as the host sends it.
channel.send(packet(0x02, [...str(uuid), ...str(name), 0, 4]));
// Join Game: entity 1, creative, overworld, peaceful, 8 players, flat, no reduced debug.
channel.send(packet(0x01, [...i32(1), 1, 0, 0, 8, ...str('flat'), 0]));
channel.send(packet(0x05, [0, 0, 0, 1, 0, 0, 0, 0])); // spawn position 0,64,0: y sits at bit 26
channel.send(packet(0x08, [...f64(0.5), ...f64(64), ...f64(0.5), ...f32(0), ...f32(0), 0]));
setTimeout(() => {
channel.send(packet(0x02, [...str('{"text":"incari-relay-check"}'), 0]));
log('sent chat');
}, 3000);
setInterval(() => channel.send(packet(0x00, varint(Date.now() & 0xffff))), 5000);
}
}
// --- Sharing -------------------------------------------------------------------------------
let iceServers = [];
const peers = new Map();
const ws = new WebSocket(relayUrl);
ws.binaryType = 'arraybuffer';
ws.onopen = () => ws.send(new Uint8Array([0x00, 0x01, 0x01, ...ascii8('Incari check;0')]));
ws.onclose = (e) => log('relay closed', e.code);
ws.onmessage = (e) => {
const m = readRelay(e.data);
if (m.id === 0) { log('incari-relay-code:', m.code); console.log('incari-relay-code: ' + m.code); }
else if (m.id === 1) { iceServers = []; log('ICE servers', m.servers.length); }
else if (m.id === 2) { newClient(m.client); }
else if (m.id === 4) { const p = peers.get(m.peer); if (p) p.description(m.text); }
else if (m.id === 3) { const p = peers.get(m.peer); if (p) p.candidates(m.text); }
else if (m.id === 5) { log('client', m.client, 'succeeded'); }
else if (m.id === 255) { log('relay error', m.code, m.text); }
};
function newClient(id) {
log('new client', id);
const pc = new RTCPeerConnection({ iceServers });
const mine = [];
let sent = false;
const sendCandidates = () => {
if (sent) return; sent = true;
const json = JSON.stringify(mine);
ws.send(new Uint8Array([0x03, ...ascii8(id), ...bytes16(json)]));
};
pc.onicecandidate = (e) => {
if (e.candidate) mine.push({ sdpMLineIndex: String(e.candidate.sdpMLineIndex), candidate: e.candidate.candidate });
else if (peers.get(id).gotTheirs) sendCandidates();
};
pc.ondatachannel = (e) => {
channel = e.channel; channel.binaryType = 'arraybuffer';
channel.onopen = () => log('data channel open');
channel.onmessage = (ev) => { const b = new Uint8Array(ev.data); if (b[0] === 0) onPacket(b.slice(1)); };
channel.onclose = () => log('data channel closed');
};
peers.set(id, {
gotTheirs: false,
description: async (json) => {
await pc.setRemoteDescription(JSON.parse(json));
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
ws.send(new Uint8Array([0x04, ...ascii8(id), ...bytes16(JSON.stringify(pc.localDescription))]));
},
candidates: async (json) => {
for (const c of JSON.parse(json)) await pc.addIceCandidate({ candidate: c.candidate, sdpMLineIndex: Number(c.sdpMLineIndex) });
peers.get(id).gotTheirs = true;
if (pc.iceGatheringState === 'complete') sendCandidates(); else setTimeout(sendCandidates, 2000);
},
});
}
</script>
@@ -0,0 +1,29 @@
# Joining a world shared through an Eagler relay. Needs the relay (EaglerSPRelay, local) and
# relay-host.html open in another headless Chromium, which prints the world's code; the command
# that runs this script puts the code in place of CODE (README.md, "Shared worlds").
# The first-run accessibility screen: Continue.
sleep:4000
click:0.5,0.945
sleep:2000
# Title screen: Multiplayer; the first visit's warning: Proceed.
click:0.5,0.5
sleep:1500
click:0.375,0.688
sleep:1500
shot:build/browser-checks/relay-multiplayer.png
# The multiplayer screen's "Shared..." button, bottom row, fourth.
click:0.621,0.938
sleep:1500
shot:build/browser-checks/relay-screen.png
# The relay field: select what's there, type the local relay.
click:0.5,0.277
key:Control+KeyA
type:ws://127.0.0.1:6699/
click:0.5,0.416
type:CODE
shot:build/browser-checks/relay-filled.png
# Join.
click:0.42,0.553
wait:.*\[CHAT\] incari-relay-check.*
shot:build/browser-checks/relay-joined.png
@@ -0,0 +1,26 @@
# A screenshot taken in a world (F2) downloads as a PNG when the player clicks its name in
# the chat message, as it opens in the file manager on a desktop. Needs a world: a vanilla server
# behind tools/wsbridge, as server-join.steps (the browser-checks README has the setup), joined
# straight away with ?server=. Positions are for the 1280x577 viewport.
#
# INCARI_RCON_PASSWORD=<password> ./gradlew :app-web:browserCheck \
# "-Pbrowser.query=server=ws://127.0.0.1:8817&name=IncariWeb" -Pbrowser.rcon=127.0.0.1:25592 \
# -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/screenshot.steps
downloads:build/browser-checks/downloads
rcon:whitelist off
rcon:time set day
# The first-run accessibility screen: Continue. Quick play connects after it.
sleep:4000
click:0.5,0.945
rconwait:list => IncariWeb
sleep:6000
key:F2
wait:.*\[CHAT\] Saved screenshot as .*\.png.*
sleep:1000
# Open chat, and click the file name in the message ("Saved screenshot as <name>").
key:KeyT
sleep:1000
shot:build/browser-checks/screenshot-chat.png
click:0.28,0.848
download:.*\.png
@@ -0,0 +1,71 @@
# The browser build joins a vanilla 26.3 server over ws://, through the dev bridge
# (tools/wsbridge on 127.0.0.1:8817), plays, changes dimension there and back, is transferred to
# the same server (disconnecting and reconnecting by itself), is kicked, and joins again through
# the multiplayer screen. Each check reads the page's console, the clipboard (F3+C copies the
# client's own position and dimension), or the server's answer over RCON. The page runs with
# ?server=ws://127.0.0.1:8817&name=IncariWeb; README.md ("Server join") has the setup and command.
# A fresh 26.3 server has its whitelist on; and on a server that has run a while, night falls and
# mobs can kill the player mid-check.
rcon:whitelist off
rcon:difficulty peaceful
rcon:time set day
# The first-run accessibility screen: Continue. Quick play connects after it.
sleep:4000
click:0.5,0.945
wait:.*Connecting to 127\.0\.0\.1, 8817.*
# --- Joined: the server lists the player, and a system message reaches the client's chat ---
rconwait:list => IncariWeb
# The teleports below land in rock, lava or the air: in creative nothing there can kill the player,
# which would otherwise be saved dead and fail the next run's teleports.
rcon:gamemode creative IncariWeb
sleep:3000
rcon:tellraw IncariWeb "incari-check-chat"
wait:.*\[CHAT\] incari-check-chat.*
shot:build/browser-checks/server-joined.png
# --- To the Nether and back, as the client itself sees it ---
clipboard:-
rcon:execute in minecraft:the_nether run tp IncariWeb 0 100 0
rconwait:data get entity IncariWeb Dimension => the_nether
sleep:4000
key:F3+KeyC
waitfor:navigator.clipboard.readText().then(text => text.startsWith('/execute in minecraft:the_nether '))
shot:build/browser-checks/server-nether.png
rcon:execute in minecraft:overworld run tp IncariWeb 0 -60 0
rconwait:data get entity IncariWeb Dimension => overworld
sleep:4000
key:F3+KeyC
waitfor:navigator.clipboard.readText().then(text => text.startsWith('/execute in minecraft:overworld '))
# --- Transfer: the server names a ws:// address; the client disconnects and reconnects itself ---
rcon:transfer "ws://127.0.0.1:8817" 25565 IncariWeb
wait:.*Client disconnected with reason: Transferred to another server.*
wait:.*Connecting to 127\.0\.0\.1, 8817.*
rconwait:list => IncariWeb
sleep:3000
rcon:tellraw IncariWeb "incari-check-transferred"
wait:.*\[CHAT\] incari-check-transferred.*
# --- Disconnect and reconnect: kicked, back to the server list, Direct Connection ---
rcon:kick IncariWeb incari-check-kick
wait:.*Client disconnected with reason: incari-check-kick.*
rconwait:list => There are 0
sleep:1000
shot:build/browser-checks/server-kicked.png
# "Back to Server List", then "Direct Connection" (the list itself is empty: the check's browser
# starts with a new profile, so there's no stored servers.dat).
click:0.5,0.598
sleep:2000
click:0.5,0.854
sleep:1500
type:ws://127.0.0.1:8817
key:Enter
wait:.*Connecting to 127\.0\.0\.1, 8817.*
rconwait:list => IncariWeb
sleep:3000
rcon:tellraw IncariWeb "incari-check-rejoined"
wait:.*\[CHAT\] incari-check-rejoined.*
shot:build/browser-checks/server-rejoined.png
@@ -0,0 +1,14 @@
# ADR 0062: a guest joining an Incari player's shared world (?shared=<relay>|<code>, the code from
# share-host.steps' console): joined as it is, no Via; the world arrives and the guest plays in it.
sleep:4000
click:0.5,0.945
wait:.*Loaded \d+ advancements.*
sleep:20000
shot:build/browser-checks/share-guest-joined.png
key:KeyT
sleep:800
type:hello from the guest
key:Enter
wait:.*\[CHAT\] <Guest> hello from the guest.*
sleep:2000
shot:build/browser-checks/share-guest-chat.png
@@ -0,0 +1,10 @@
# ADR 0062: the host of a shared world. Run beside share-guest.steps and the local relay
# (README.md, "Shared worlds, hosted"): the quick world is shared on the relay as soon as it's open
# (?share=), the code goes to the console, and a guest joins.
sleep:4000
click:0.5,0.945
wait:.*The world is shared on .* with the code .*
shot:build/browser-checks/share-host-shared.png
wait:.*\[CHAT\] Guest joined the game.*
sleep:90000
shot:build/browser-checks/share-host-guest.png
@@ -0,0 +1,24 @@
# ADR 0038: Open to LAN with singleplayer's server on the page. A page can't listen for
# connections, so the game says it couldn't host instead of failing. (With the server in a worker,
# the pause menu has no World Options yet: ADR 0039.) Positions are for the 1280x577 viewport.
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 "-Pbrowser.query=name=Player&singleplayer=page" \
# -Pbrowser.steps=@browser-checks/singleplayer-lan.steps
sleep:4000
click:0.5,0.945
sleep:3000
click:0.5,0.449
sleep:4000
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:8000
# World Options, LAN on, Apply: back to the pause menu, and the game says it couldn't host.
key:Escape
sleep:1500
click:0.583,0.561
sleep:2000
click:0.375,0.723
sleep:500
click:0.375,0.945
wait:.*\[CHAT\] Unable to host local game.*
@@ -0,0 +1,90 @@
# ADR 0038, ADR 0039: singleplayer, its server in a worker (or on the page with
# -Pbrowser.query=name=Player&singleplayer=page). Creates a world with the defaults, plays in it,
# turns Allow Commands on in World Options and runs a command, saves and quits; checks that every saved chunk inflates with the browser's own DecompressionStream; plays the world again;
# downloads it through Edit World's folder button, drops the download on the world list (a second
# copy is imported), and opens Delete. No server needed. Positions are for the 1280x577 viewport.
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=400 -Pbrowser.steps=@browser-checks/singleplayer.steps
downloads:build/browser-checks/downloads
sleep:4000
# The first-run accessibility screen: Continue. Then Singleplayer; with no worlds yet it opens
# Create New World, and Create takes the defaults.
click:0.5,0.945
sleep:3000
click:0.5,0.449
sleep:4000
shot:build/browser-checks/singleplayer-create.png
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:8000
shot:build/browser-checks/singleplayer-world.png
# --- World Options: Allow Commands on, Apply; then a command works ---
key:Escape
sleep:1500
click:0.583,0.561
sleep:2000
shot:build/browser-checks/singleplayer-world-options.png
click:0.376,0.414
sleep:500
click:0.375,0.945
sleep:2000
key:Escape
sleep:1000
key:KeyT
sleep:800
type:/time set day
key:Enter
wait:.*\[CHAT\] Set minecraft:overworld to time marker minecraft:day.*
sleep:1000
key:Escape
sleep:1500
# --- Save and Quit to Title, then every saved chunk reads back whole ---
click:0.5,0.643
wait:.*Saving chunks for level 'ServerLevel\[New World\]'/minecraft:the_nether.*
sleep:4000
until:window.incariStorage.pending() === 0
assert:(async () => { const root = await navigator.storage.getDirectory(); let d = root; for (const p of ["incari", "game", "saves", "New World", "dimensions", "minecraft", "overworld"]) d = await d.getDirectoryHandle(p); let ok = 0, bad = 0; for (const sub of ["region", "entities"]) { const s = await d.getDirectoryHandle(sub); for await (const [, h] of s.entries()) { const buf = await (await h.getFile()).arrayBuffer(); const v = new DataView(buf); for (let i = 0; i < 1024; i++) { const off = v.getUint32(i * 4); if (!off) continue; const pos = (off >>> 8) * 4096; const len = v.getUint32(pos); try { await new Response(new Blob([new Uint8Array(buf, pos + 5, len - 1)]).stream().pipeThrough(new DecompressionStream("deflate"))).arrayBuffer(); ok++; } catch (e) { bad++; } } } } console.log("[check] saved chunks: " + ok + " whole, " + bad + " broken"); return ok > 0 && bad === 0; })()
# --- Play it again from the world list ---
click:0.5,0.449
sleep:3000
shot:build/browser-checks/singleplayer-list.png
click:0.5,0.235
sleep:500
click:0.375,0.854
wait:.*logged in with entity id.*
sleep:5000
key:Escape
sleep:1500
click:0.5,0.643
wait:.*Saving chunks for level 'ServerLevel\[New World\]'/minecraft:the_nether.*
sleep:4000
# --- Edit World, Open World Folder: the page downloads the world as a zip ---
click:0.5,0.449
sleep:3000
click:0.5,0.235
sleep:500
click:0.313,0.937
sleep:2000
click:0.5,0.436
download:New World\.zip
sleep:1000
key:Escape
sleep:2000
# --- The zip dropped on the world list comes in as a second world ---
drop:0.5,0.5,build/browser-checks/downloads/New World.zip
waitfor:window.incariStorage.list('/incari/game/saves/New World (1)').then(l => l.includes('/incari/game/saves/New World (1)/level.dat'))
sleep:1000
shot:build/browser-checks/singleplayer-imported.png
# --- Delete asks first ---
click:0.5,0.235
sleep:500
click:0.437,0.937
sleep:2000
shot:build/browser-checks/singleplayer-delete.png
@@ -0,0 +1,900 @@
# A 30-minute session on a vanilla server that keeps the client loading terrain, and the
# threading audit's gate: no frame in which the render thread spent 50 ms or more waiting (blocking
# calls on it; the page's frame monitor, platform-web's Dom.installFrameMonitor, adds up each frame's
# waits). Frames over 50 ms from work (meshing, packets), with or without a short wait in them, are
# reported, not failed: that's the benchmark's job.
# Every minute the player is sent to fresh terrain and turns full circle, and the mouse moves with
# each turn so the game never counts the player as idle (it throttles to 30 and then 10 fps); the
# page's counts are printed as it goes. Setup as for server-join.steps (README.md, "Server join"); run with
#
# INCARI_RCON_PASSWORD=<password> ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl \
# "-Pbrowser.query=server=ws://127.0.0.1:8817&name=IncariWeb" -Pbrowser.rcon=127.0.0.1:25592 \
# -Pbrowser.seconds=2100 -Pbrowser.steps=@browser-checks/soak.steps
rcon:whitelist off
rcon:difficulty peaceful
rcon:time set day
rcon:gamerule doDaylightCycle false
rcon:gamerule doWeatherCycle false
# The first-run accessibility screen: Continue. Quick play connects after it.
sleep:4000
click:0.5,0.945
wait:.*Connecting to 127\.0\.0\.1, 8817.*
rconwait:list => IncariWeb
sleep:5000
# Counted from here: the join itself is loading, not play.
eval:(function() { var f = window.__incariFrames; f.frames = 0; f.waiting = 0; f.waitStalls = 0; f.worstWait = 0; f.slow = 0; f.slowWaiting = 0; f.worst = 0; f.worstWaiting = 0; return 'counting'; })()
# Minute 1
rcon:spreadplayers 2000 2000 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 2
rcon:spreadplayers 2700 2000 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 3
rcon:spreadplayers 3400 2000 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 4
rcon:spreadplayers 4100 2000 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 5
rcon:spreadplayers 4800 2000 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 6
rcon:spreadplayers 5500 2000 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 7
rcon:spreadplayers 2000 2700 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 8
rcon:spreadplayers 2700 2700 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 9
rcon:spreadplayers 3400 2700 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 10
rcon:spreadplayers 4100 2700 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 11
rcon:spreadplayers 4800 2700 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 12
rcon:spreadplayers 5500 2700 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 13
rcon:spreadplayers 2000 3400 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 14
rcon:spreadplayers 2700 3400 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 15
rcon:spreadplayers 3400 3400 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 16
rcon:spreadplayers 4100 3400 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 17
rcon:spreadplayers 4800 3400 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 18
rcon:spreadplayers 5500 3400 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 19
rcon:spreadplayers 2000 4100 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 20
rcon:spreadplayers 2700 4100 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 21
rcon:spreadplayers 3400 4100 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 22
rcon:spreadplayers 4100 4100 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 23
rcon:spreadplayers 4800 4100 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 24
rcon:spreadplayers 5500 4100 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 25
rcon:spreadplayers 2000 4800 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 26
rcon:spreadplayers 2700 4800 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 27
rcon:spreadplayers 3400 4800 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 28
rcon:spreadplayers 4100 4800 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 29
rcon:spreadplayers 4800 4800 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
# Minute 30
rcon:spreadplayers 5500 4800 0 1 false IncariWeb
sleep:20000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.4,0.5
sleep:4000
rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~
move:0.6,0.5
sleep:4000
sleep:8000
eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting'])
shot:build/browser-checks/soak.png
# The gate: no frame in which the render thread waited 50 ms or more.
assert:window.__incariFrames.waitStalls === 0
@@ -0,0 +1,42 @@
# F1 of the 2026-10-12 batch: sounds whose download fails at first still play. Every sound's first
# two fetches fail as a dropped connection would; the loader's retries get the third. In a quick
# world (-Pbrowser.query=name=Player&world=Retry&seed=1); no server needed.
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=240 \
# "-Pbrowser.query=name=Player&world=Retry&seed=1" -Pbrowser.steps=@browser-checks/sound-retry.steps
sleep:4000
eval:(() => { const of = window.fetch; const tries = new Map(); globalThis.fetchLog = []; window.fetch = (u, ...a) => { const url = String(u); if (!url.includes('objects')) return of(u, ...a); const n = (tries.get(url) || 0) + 1; tries.set(url, n); if (n <= 2) { fetchLog.push('fail ' + n); return Promise.reject(new TypeError('Failed to fetch')); } return of(u, ...a).then(r => { fetchLog.push(r.status + ' on try ' + n); return r; }); }; return 'failing each sound twice'; })()
# The first-run accessibility screen: Continue (also the gesture the audio waits for).
click:0.5,0.945
wait:.*logged in with entity id.*
sleep:6000
eval:globalThis.before = incariAudio.buffersStarted
key:KeyT
sleep:800
type:/fill ~-4 ~ ~-4 ~4 ~4 ~4 minecraft:air
key:Enter
sleep:800
key:KeyT
sleep:800
type:/fill ~-4 ~-3 ~-4 ~4 ~-1 ~4 minecraft:stone
key:Enter
sleep:800
key:KeyT
sleep:800
type:/gamemode creative
key:Enter
sleep:800
key:KeyT
sleep:800
type:/tp @s ~ ~ ~ 0 90
key:Enter
sleep:1500
click:0.5,0.5
sleep:1500
click:0.5,0.5
sleep:1500
click:0.5,0.5
sleep:3000
eval:'buffers started: ' + (incariAudio.buffersStarted - before) + ', fetches: ' + JSON.stringify(fetchLog)
@@ -0,0 +1,106 @@
# Settings, servers and resource packs survive a reload. Changes an option (FOV), adds a
# server and imports a resource pack (made by the check from scratch) through "Open Pack Folder"'s
# file picker, reloads the page, and checks that the page loaded all three from storage and the
# game uses them. Also: F2's screenshot is stored as a PNG. Positions are for the 1280x577
# viewport headless Chromium gives a 1280x720 window.
#
# ./gradlew :app-web:browserCheck -Pbrowser.seconds=400 -Pbrowser.steps=@browser-checks/storage.steps
# A new profile: nothing stored yet, and the jar comes from the network.
sleep:4000
assert:window.incariStorage.read('/incari/game/servers.dat').then(t => t === null)
# The first-run accessibility screen: Continue.
click:0.5,0.945
sleep:3000
shot:build/browser-checks/storage-title-before.png
# --- An option: FOV, on the Options screen, dragged right of Normal ---
click:0.42,0.782
sleep:1500
click:0.48,0.133
sleep:500
shot:build/browser-checks/storage-fov.png
# Done saves options.txt.
click:0.5,0.945
sleep:1500
waitfor:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && /\nfov:0\.[0-9]*[1-9]/.test(t))
# --- A resource pack: Options, Resource Packs, Open Pack Folder, pick the pack, Yes to copy it ---
pack:build/browser-checks/incari-check-pack.zip
click:0.42,0.782
sleep:1500
click:0.376,0.598
sleep:2000
choose:0.376,0.945,build/browser-checks/incari-check-pack.zip
sleep:2000
shot:build/browser-checks/storage-pack-confirm.png
click:0.38,0.585
sleep:2000
shot:build/browser-checks/storage-pack-available.png
waitfor:window.incariStorage.read('/incari/game/resourcepacks/incari-check-pack.zip').then(t => t !== null && t.startsWith('PK'))
# Select it: its icon's arrow, at the top of the Available list.
move:0.19,0.277
sleep:300
click:0.19,0.277
sleep:1000
shot:build/browser-checks/storage-pack-selected.png
# Done reloads resources with the pack, and saves it in options.txt.
click:0.623,0.945
wait:.*Reloading ResourceManager.*incari-check-pack.*
sleep:4000
waitfor:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('file/incari-check-pack.zip'))
key:Escape
sleep:1500
# --- A server: Multiplayer, Proceed on the safety screen, Add Server ---
click:0.5,0.534
sleep:1500
click:0.376,0.688
sleep:1500
click:0.662,0.854
sleep:1500
click:0.5,0.262
key:Control+KeyA
type:Incari Check Server
click:0.5,0.4
type:ws://127.0.0.1:18199
sleep:300
click:0.5,0.678
sleep:2000
shot:build/browser-checks/storage-servers-before.png
waitfor:window.incariStorage.read('/incari/game/servers.dat').then(t => t !== null && t.includes('Incari Check Server') && t.includes('ws://127.0.0.1:18199'))
key:Escape
sleep:1500
# --- A screenshot (F2), stored as a PNG under screenshots/ ---
key:F2
sleep:2000
waitfor:window.incariStorage.list('/incari/game/screenshots').then(p => p.length === 1 && p[0].endsWith('.png'))
assert:window.incariStorage.list('/incari/game/screenshots').then(p => window.incariStorage.read(p[0])).then(t => t.startsWith('\ufffdPNG'))
# --- Everything is stored before the reload ---
waitfor:window.incariStorage.pending() === 0
reload
wait:\[Incari\] Storage: opfs, [1-9][0-9]* files.*
wait:\[Incari\] Client jar: .* from storage.*
# The game started with the pack (resource reloads name the packs in use).
wait:.*Reloading ResourceManager.*incari-check-pack.*
wait:\[Incari\] Main loop running.*
sleep:4000
# No accessibility screen this time: options.txt said it was done. The title screen shows the
# pack's name for the Singleplayer button.
shot:build/browser-checks/storage-title-after.png
assert:window.incariStorage.read('/incari/game/options.txt').then(t => /\nfov:0\.[0-9]*[1-9]/.test(t) && t.includes('file/incari-check-pack.zip'))
# Options shows the FOV that was set.
click:0.42,0.782
sleep:1500
shot:build/browser-checks/storage-fov-after.png
key:Escape
sleep:1500
# The server list has the server.
click:0.5,0.534
sleep:1500
click:0.376,0.688
sleep:2500
shot:build/browser-checks/storage-servers-after.png
assert:window.incariStorage.read('/incari/game/servers.dat').then(t => t !== null && t.includes('Incari Check Server'))
@@ -0,0 +1,43 @@
# The browser build joins a server of another version through Via, over ws://: a vanilla
# 1.8.9, 1.12.2 or 1.20.4 server behind the dev bridge (tools/wsbridge, which speaks Eagler), or a
# real EaglerXServer in front of one. It pings nothing first: quick play's version check asks the
# server's MOTD. Checks read the page's console and the server's answers over RCON (the backend's).
# The page needs &via=auto: Via is off unless the join asks for it (ADR 0071). README.md ("Old
# servers") has the setup and commands.
# On a server that has run a while, night falls and mobs can kill the player mid-check. (1.8 and
# 1.12 take a number; later versions a name. The other form fails harmlessly.)
rcon:difficulty 0
rcon:difficulty peaceful
rcon:time set 1000
# The first-run accessibility screen: Continue. Quick play connects after it, through Via.
sleep:4000
click:0.5,0.945
wait:.*Joining ws://[^ ]+ as .* through Via.*
# --- Joined: the server lists the player, and a system message reaches the client's chat ---
rconwait:list => IncariWeb
sleep:3000
rcon:tellraw IncariWeb "incari-check-chat"
wait:.*\[CHAT\] incari-check-chat.*
shot:build/browser-checks/version-joined.png
# --- Idle for 20 s: a 1.8 server wants a movement packet every tick, which Via sends ---
sleep:20000
rconwait:list => IncariWeb
rcon:tellraw IncariWeb "incari-check-still-here"
wait:.*\[CHAT\] incari-check-still-here.*
# --- Kicked, then back through a reload of the page (quick play again) ---
rcon:kick IncariWeb incari-check-kick
wait:.*Client disconnected with reason: incari-check-kick.*
sleep:1000
reload:
# The accessibility screen was answered and saved: quick play connects straight away.
wait:.*Joining ws://[^ ]+ as .* through Via.*
rconwait:list => IncariWeb
sleep:3000
rcon:tellraw IncariWeb "incari-check-rejoined"
wait:.*\[CHAT\] incari-check-rejoined.*
shot:build/browser-checks/version-rejoined.png
@@ -0,0 +1,33 @@
# Eagler voice chat between two browsers, the listener (this file with voice-talker.steps). Run both at once against EaglerXServer with its
# voice service on, as VoiceA (-Pbrowser.query=...&name=VoiceA) and VoiceB; README.md ("Voice
# chat") has the commands. Chromium's fake microphone plays a steady tone and grants the
# permission, so each page turns global voice on, VoiceA holds push to talk, and VoiceB hears it.
rcon:difficulty 0
rcon:time set 1000
# The first-run accessibility screen: Continue. Quick play joins the server.
sleep:4000
click:0.5,0.945
wait:.*Joining ws://[^ ]+ as .* through Via.*
wait:.*The server has voice chat.*
sleep:3000
# Pause menu: "Voice Chat...", then the channel button until it reads Global.
key:Escape
sleep:1000
shot:build/browser-checks/voice-pause-b.png
click:0.5,0.539
sleep:1000
shot:build/browser-checks/voice-screen-b.png
click:0.375,0.173
sleep:500
shot:build/browser-checks/voice-global-b.png
key:Escape
sleep:500
key:Escape
sleep:500
# Connected by now or soon (the log line may come before a wait could see it); then VoiceA talks.
wait:.*Voice: VoiceA is talking.*
shot:build/browser-checks/voice-hearing-b.png
@@ -0,0 +1,39 @@
# Eagler voice chat between two browsers, the talker (this file with voice-listener.steps, or
# the other way round). Run both at once against EaglerXServer with its
# voice service on, as VoiceA (-Pbrowser.query=...&name=VoiceA) and VoiceB; README.md ("Voice
# chat") has the commands. Chromium's fake microphone plays a steady tone and grants the
# permission, so each page turns global voice on, VoiceA holds push to talk, and VoiceB hears it.
rcon:difficulty 0
rcon:time set 1000
# The first-run accessibility screen: Continue. Quick play joins the server.
sleep:4000
click:0.5,0.945
wait:.*Joining ws://[^ ]+ as .* through Via.*
wait:.*The server has voice chat.*
sleep:3000
# Pause menu: "Voice Chat...", then the channel button until it reads Global.
key:Escape
sleep:1000
shot:build/browser-checks/voice-pause-a.png
click:0.5,0.539
sleep:1000
shot:build/browser-checks/voice-screen-a.png
click:0.375,0.173
sleep:500
shot:build/browser-checks/voice-global-a.png
key:Escape
sleep:500
key:Escape
sleep:500
# The two connect within seconds of the listener turning voice on (the log line may come before a
# wait could see it): give it that, then hold push to talk (B) for twenty seconds.
sleep:10000
down:KeyB
sleep:20000
shot:build/browser-checks/voice-talking-a.png
up:KeyB
sleep:20000
@@ -0,0 +1,66 @@
# ADR 0051: the minimap and waypoints in the page. Creates a world, turns Minimap and Waypoints on
# from the module menu, marks where the player stands with N and names it
# Base, walks back from it so its label, distance and beam show ahead, opens the list with U and
# the world map with M, and checks the world's waypoints and the explored map are stored in OPFS. No server needed. Positions are for the
# 1280x577 viewport (GUI scale 2, 640x288).
#
# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/waypoints.steps
sleep:4000
# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults.
click:0.5,0.945
sleep:3000
click:0.2,0.43
sleep:4000
click:0.38,0.945
wait:.*logged in with entity id.*
sleep:8000
# --- The module menu: Minimap's and Waypoints' switches (the right column's second and fourth cards) ---
key:ShiftRight
sleep:1500
click:0.833,0.395
sleep:300
click:0.833,0.756
sleep:300
shot:build/browser-checks/waypoints-menu.png
key:Escape
sleep:4000
shot:build/browser-checks/waypoints-minimap.png
# --- N: a new waypoint where the player stands, named Base and added with Enter ---
key:KeyN
sleep:1500
shot:build/browser-checks/waypoints-new.png
type:Base
key:Enter
sleep:800
# --- Back from it: its label, distance and beam ahead ---
down:KeyS
sleep:2500
up:KeyS
sleep:1500
shot:build/browser-checks/waypoints-ahead.png
# --- U: the list ---
key:KeyU
sleep:1500
shot:build/browser-checks/waypoints-list.png
key:Escape
sleep:2500
# --- M: the world map, Base on it; M again closes it ---
key:KeyM
sleep:2000
shot:build/browser-checks/waypoints-worldmap.png
key:KeyM
sleep:1000
# --- The world's waypoints are stored ---
until:window.incariStorage.pending() === 0
assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "modules", "waypoints"]) d = await d.getDirectoryHandle(p); let found = ""; for await (const [name, handle] of d.entries()) { const text = await (await handle.getFile()).text(); console.log("[check] " + name + ": " + text); found += text; } return found.includes("\"name\":\"Base\""); })()
# --- And the explored map, after the map's half-minute save ---
sleep:31000
until:window.incariStorage.pending() === 0
assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "map"]) d = await d.getDirectoryHandle(p); let count = 0; const walk = async (dir) => { for await (const [name, handle] of dir.entries()) { if (handle.kind === "directory") await walk(handle); else if (name.endsWith(".map")) count++; } }; await walk(d); console.log("[check] map regions: " + count); return count > 0; })()
@@ -0,0 +1,794 @@
import java.util.Properties
plugins {
java
}
// The browser build: the game compiled by TeaVM (WebAssembly GC) through platform-web.
// `./gradlew :app-web:teavm` writes build/teavm/, which is never committed or published.
dependencies {
implementation(project(":client"))
implementation(project(":platform-web"))
// The WebGL2 graphics backend.
implementation(project(":render-webgl2"))
// Compiled into the browser build in place of the JDK parts TeaVM lacks. ClientJar also
// names the directory its class-path resources live in.
implementation(project(":web-classlib"))
// java.time, which TeaVM maps onto ThreeTen Backport.
runtimeOnly(libs.threetenbp)
compileOnly(libs.teavm.jso)
compileOnly(libs.teavm.jso.apis)
compileOnly(libs.teavm.interop)
// MemoryParityTest: the game's memory users over LWJGL and over web-classlib, on a JVM.
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testImplementation(libs.asm)
testImplementation(libs.asm.commons)
testRuntimeOnly(libs.junit.launcher)
}
// The parity test runs the vanilla side on real LWJGL, so it needs this machine's natives.
val testNativeJars = run {
val root = rootProject.layout.projectDirectory.asFile
val version = Properties().apply {
rootProject.layout.projectDirectory.file("incari.properties").asFile.reader().use { load(it) }
}.getProperty("minecraft.version")
providers.fileContents(rootProject.layout.projectDirectory.file("work/cache/versions/$version/natives.txt"))
.asText.map { text -> text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) } }
.orElse(emptyList())
}
tasks.test {
classpath += files(testNativeJars)
maxHeapSize = "2g"
// Game classes write logs/ into the working directory; keep that in build/.
val runDir = layout.buildDirectory.dir("test-run").get().asFile
workingDir = runDir
doFirst { runDir.mkdirs() }
jvmArgs(
"--enable-native-access=ALL-UNNAMED",
"-Dorg.lwjgl.system.SharedLibraryExtractPath=" +
rootProject.layout.projectDirectory.dir("work/natives/lwjgl").asFile.path,
)
testLogging { showStandardStreams = true }
}
val webbuildTool: Configuration = configurations.create("webbuildTool")
val shaderTool: Configuration = configurations.create("shaderTool")
val spriteTool: Configuration = configurations.create("spriteTool")
dependencies {
webbuildTool(project(":tools:webbuild"))
shaderTool(project(":tools:shaders"))
spriteTool(project(":tools:sprites"))
}
val repoRoot = rootProject.layout.projectDirectory
// The client jar `./incari setup` downloaded. The dev server hands it to the page, which unpacks the
// game's resources from it (the build compiles classes only); it is never copied into the build.
val minecraftVersion = providers.fileContents(repoRoot.file("incari.properties")).asText.map { text ->
Properties().apply { load(text.reader()) }.getProperty("minecraft.version")
}
val clientJar = minecraftVersion.map { repoRoot.file("work/cache/versions/$it/client.jar").asFile.path }
// The asset index `./incari assets` downloaded, and its objects (ADR 0013): the page lists the
// sounds from the index and fetches each one the first time it plays. Mojang's files, served from
// work/ by the dev server, never copied into the build. Without them the page runs silent.
val assetServerArgs: Provider<List<String>> = minecraftVersion.map { version ->
val versionJson = repoRoot.file("work/cache/versions/$version/$version.json").asFile
if (!versionJson.isFile) {
emptyList()
} else {
@Suppress("UNCHECKED_CAST")
val index = (groovy.json.JsonSlurper().parse(versionJson) as Map<String, Any?>)["assetIndex"] as Map<String, Any?>
listOf(
"--file", "asset-index.json=" + repoRoot.file("work/cache/assets/indexes/${index["id"]}.json").asFile.path,
"--dir", "assets/objects=" + repoRoot.dir("work/cache/assets/objects").asFile.path,
)
}
}
// The game's shaders translated to GLSL ES 3.00 for the WebGL2 backend (tools/shaders). Translated
// Mojang files: build output beside the page, never inside build/teavm/ (so they don't invalidate the
// ten-minute compile) and never committed or published. The dev server serves them at /shaders.json.
val shaderManifest = layout.buildDirectory.file("web-shaders/shaders.json")
tasks.register<JavaExec>("shaders") {
group = "build"
description = "Translates the game's shaders for WebGL2 into build/web-shaders/shaders.json."
classpath = shaderTool
mainClass = "incari.tools.shaders.Main"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val jar = clientJar.get()
val version = minecraftVersion.get()
// CI installs glslang and must check with it; locally it's used when it's installed.
val requireGlslang = providers.environmentVariable("CI").isPresent ||
providers.gradleProperty("shaders.requireGlslang").isPresent
// A local: a lambda capturing the script can't be stored in the configuration cache.
val manifest = shaderManifest
inputs.file(jar)
inputs.files(shaderTool)
outputs.dir(manifest.map { it.asFile.parentFile })
jvmArgs(
"--enable-native-access=ALL-UNNAMED",
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
)
argumentProviders.add(CommandLineArgumentProvider {
listOf("--client-jar", jar, "--minecraft", version, "--out", manifest.get().asFile.path) +
(if (requireGlslang) listOf("--require-glslang") else emptyList())
})
}
// The vanilla sprites decoded, with their mip levels, by the game's own code (tools/sprites,
// ADR 0026): the asset pack carries them, and the page makes a vanilla sprite from them instead of
// decoding its PNG. Decoded Mojang textures: build output, never committed or published.
val spriteFile = layout.buildDirectory.file("web-sprites/sprites.bin")
tasks.register<JavaExec>("sprites") {
group = "build"
description = "Decodes the vanilla sprites and their mip levels into build/web-sprites/sprites.bin."
classpath = spriteTool
mainClass = "incari.tools.sprites.Main"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val jar = clientJar.get()
val file = spriteFile
inputs.file(jar)
inputs.files(spriteTool)
outputs.file(file)
// The game's classes write logs/ into the working directory; keep that in build/.
val runDir = layout.buildDirectory.dir("web-sprites/run").get().asFile
workingDir = runDir
doFirst { runDir.mkdirs() }
jvmArgs(
"--enable-native-access=ALL-UNNAMED",
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
)
argumentProviders.add(CommandLineArgumentProvider { listOf("--out", file.get().asFile.path) })
}
// The game has two builds (ADR 0036), both WebAssembly GC: Fast (JSPI) in build/teavm-fast/ and
// Compatible (TeaVM's coroutines) in build/teavm/. `-Pteavm.fast` makes the teavm task compile Fast,
// and the checks and the benchmark run it; without it, Compatible. The page offers whichever are built.
val fastBuild = providers.gradleProperty("teavm.fast").isPresent
val gameBuildDir = if (fastBuild) "teavm-fast" else "teavm"
/** The build the checks and the benchmark ask the page for (PageQuery): fast or compatible. */
val gameBuild = if (fastBuild) "fast" else "compatible"
tasks.register<JavaExec>("teavm") {
group = "build"
description = "Compiles the Compatible build with TeaVM into build/teavm/ (-Pteavm.fast: Fast, into build/teavm-fast/)."
classpath = webbuildTool
mainClass = "incari.tools.webbuild.Main"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
maxHeapSize = "20g"
val libraries = repoRoot.dir("work/cache/libraries").asFile
// Incari's classes and the game as :client compiled it; the tool adds the Mojang libraries
// tools/survey/rules.txt keeps. Mojang's other jars (LWJGL, JNA...) stay out on purpose.
val appClasspath = sourceSets.main.get().runtimeClasspath.filter { !it.startsWith(libraries) }
// As an input, the classpath also makes Gradle build the jars on it first.
inputs.files(appClasspath)
// For experiments: `-Pteavm.main=<class> -Pteavm.classpath=<dir>` compiles a small program
// against the same class library in seconds, instead of the game in minutes.
val mainClass = providers.gradleProperty("teavm.main").orElse("incari.app.web.WebMain")
val extraClasspath = providers.gradleProperty("teavm.classpath").orElse("")
// `-Pteavm.release`: TeaVM's ADVANCED optimizations, obfuscated, no debug information.
// `-Pteavm.names` (with release): Java names kept in the module, for readable CPU profiles.
// Binaryen's wasm-opt over the module (ADR 0034, 0043): on by default for the Fast release build
// (under a minute; `-Pteavm.noWasmOpt` leaves it out), and for the Compatible one only with
// `-Pteavm.wasmOpt` (a quarter of an hour and 10 GB more, not measured with ADR 0043's flags).
val release = providers.gradleProperty("teavm.release").isPresent
val names = providers.gradleProperty("teavm.names").isPresent
val wasmOpt = release && !providers.gradleProperty("teavm.noWasmOpt").isPresent &&
(fastBuild || providers.gradleProperty("teavm.wasmOpt").isPresent)
inputs.property("wasmOpt", wasmOpt)
// `-Pteavm.fast`: the Fast build, which suspends through JSPI instead of coroutines
// (tools/webbuild's JspiTransformer, ADR 0036), into build/teavm-fast/.
val jspi = fastBuild
inputs.property("jspi", jspi)
inputs.property("release", release)
inputs.property("names", names)
// Experiments build into their own directory, so they never replace the game's build.
val output = layout.buildDirectory.dir(
providers.gradleProperty("teavm.main").map { "teavm-experiment" }
.orElse(gameBuildDir))
// A development page that loads the module; `./gradlew :app-web:serve` serves the directory.
val page = layout.projectDirectory.file("src/main/web/index.html")
inputs.file(page)
inputs.property("mainClass", mainClass)
inputs.property("extraClasspath", extraClasspath)
// The experiment's classes themselves, so editing a probe recompiles it.
inputs.files(extraClasspath.map { path -> if (path.isEmpty()) emptyList() else listOf(File(path)) })
outputs.dir(output)
val verbose = providers.gradleProperty("teavm.verbose").map { true }.orElse(false)
argumentProviders.add(CommandLineArgumentProvider {
listOf(
"--main", mainClass.get(),
"--classpath", (appClasspath.files.map { it.path } + extraClasspath.get())
.filter { it.isNotEmpty() }.joinToString(File.pathSeparator),
"--out", output.get().asFile.path,
"--page", page.asFile.path,
) + (if (verbose.get()) listOf("--verbose") else emptyList()) +
(if (release) listOf("--release") else emptyList()) +
(if (names) listOf("--names") else emptyList()) +
(if (wasmOpt) listOf("--wasm-opt") else emptyList()) +
(if (jspi) listOf("--jspi") else emptyList())
})
systemProperty("incari.cwd", repoRoot.asFile.path)
// `-Pteavm.explainAsync=<method prefix>,...`: explain in async.txt why methods suspend.
systemProperty("incari.explainAsync", providers.gradleProperty("teavm.explainAsync").orElse("").get())
// `-Pteavm.throwCensus`: count every throw by site and thread, logged every 10 s (ADR 0033).
val throwCensus = providers.gradleProperty("teavm.throwCensus").isPresent
inputs.property("throwCensus", throwCensus)
systemProperty("incari.throwCensus", throwCensus.toString())
// `-Pteavm.noJsoIntrinsics`: ints to JavaScript through TeaVM's import again (tools/webbuild's
// JsoIntrinsics), to compare.
val jsoIntrinsics = !providers.gradleProperty("teavm.noJsoIntrinsics").isPresent
inputs.property("jsoIntrinsics", jsoIntrinsics)
systemProperty("incari.jsoIntrinsics", jsoIntrinsics.toString())
}
// ---- The mesher workers' program ------------------------------------------------------------
// Incari's terrain mesher on its own (incari.app.web.mesher.MesherWorker and the :mesher module, no
// game code), compiled by TeaVM into build/teavm-mesher/mesher.wasm with its loader beside it. The
// page's mesher workers load it (ADR 0023). Seconds to compile, not minutes.
val mesherOutput = layout.buildDirectory.dir("teavm-mesher")
val teavmMesher = tasks.register<JavaExec>("teavmMesher") {
group = "build"
description = "Compiles the mesher workers' program with TeaVM into build/teavm-mesher/."
classpath = webbuildTool
mainClass = "incari.tools.webbuild.Main"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
maxHeapSize = "4g"
val libraries = repoRoot.dir("work/cache/libraries").asFile
val appClasspath = sourceSets.main.get().runtimeClasspath.filter { !it.startsWith(libraries) }
inputs.files(appClasspath)
val release = providers.gradleProperty("teavm.release").isPresent
inputs.property("release", release)
val output = mesherOutput
outputs.dir(output)
argumentProviders.add(CommandLineArgumentProvider {
listOf(
"--main", "incari.app.web.mesher.MesherWorker",
"--classpath", appClasspath.files.joinToString(File.pathSeparator) { it.path },
"--out", output.get().asFile.path,
"--name", "mesher",
) + (if (release) listOf("--release") else emptyList())
})
systemProperty("incari.cwd", repoRoot.asFile.path)
}
// ---- The loader page, the asset pack and the build manifest ---------------------------------
// The page's TypeScript (src/main/ts) with the types stripped by Node, the asset pack (build-time data
// the page mounts read-only: the translated shaders, so it's Mojang content and never published), and
// build.json (every file's size and hash, which the loader and its service worker version files by).
// All land in build/page/; the dev server serves them beside build/teavm/. ADR 0014.
val pageDir = layout.buildDirectory.dir("page")
// Strips the types from each .ts file (Node's own stripping: the sources use only erasable syntax, as
// tsconfig.json enforces) and points relative imports at the .js files.
val stripTypesScript = """
import { stripTypeScriptTypes } from "node:module";
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
const [source, out] = process.argv.slice(-2);
rmSync(out, { recursive: true, force: true });
mkdirSync(out, { recursive: true });
for (const name of readdirSync(source).filter((n) => n.endsWith(".ts"))) {
const code = stripTypeScriptTypes(readFileSync(join(source, name), "utf8"), { mode: "strip" })
.replace(/(from\s+["']\.\/[^"']+)\.ts(["'])/g, "${'$'}1.js${'$'}2");
writeFileSync(join(out, name.replace(/\.ts${'$'}/, ".js")), code);
}
""".trimIndent()
val pageScripts = tasks.register<Exec>("pageScripts") {
group = "build"
description = "Strips the types from the page's TypeScript into build/page/scripts/."
val sources = layout.projectDirectory.dir("src/main/ts")
val out = pageDir.get().dir("scripts").asFile
inputs.dir(sources)
inputs.property("script", stripTypesScript)
outputs.dir(out)
executable = "node"
args("--no-warnings", "--input-type=module", "-e", stripTypesScript, sources.asFile.path, out.path)
}
val packManifest = layout.buildDirectory.file("pack/pack.json")
val writePackManifest = tasks.register("packManifest") {
val version = minecraftVersion.get()
val file = packManifest
inputs.property("version", version)
outputs.file(file)
doLast { file.get().asFile.writeText("{\"format\": 1, \"game\": \"$version\"}\n") }
}
// Via's mapping data (ADR 0017), which it reads from the class path: the pack carries it
// under classpath/, which the page adds to the class path's roots.
val viaJars = configurations.runtimeClasspath.map { classpath ->
classpath.filter { it.name.startsWith("viaversion-common-") || it.name.startsWith("viabackwards-common-") }
}
tasks.register<Zip>("assetPack") {
group = "build"
description = "Packs the build-time data the page mounts (translated shaders, decoded sprites, Via's data, Incari's pack) into build/page/incari.pack."
dependsOn("shaders", "sprites", writePackManifest)
from(packManifest)
from(shaderManifest)
from(spriteFile)
from(viaJars.map { jars -> jars.map { zipTree(it) } }) {
include("assets/viaversion/data/**", "assets/viabackwards/data/**")
into("classpath")
}
// Incari's own resource pack (its font), which the client reads from the class path.
from(rootProject.file("client/src/main/resources")) {
include("incari-pack/**")
into("classpath")
}
archiveFileName = "incari.pack"
destinationDirectory = pageDir
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
}
// The game's builds by the names the page fetches them by (tools/webbuild BuildManifest.BUILDS):
// Compatible's module as incari.wasm, Fast's as incari-fast.wasm, with their debugging files, and
// TeaVM's loader (one for both) from the build being compiled. Whichever are built are offered.
val gameModuleFiles: List<String> = run {
val compatibleDir = layout.buildDirectory.dir("teavm").get().asFile
val fastDir = layout.buildDirectory.dir("teavm-fast").get().asFile
val suffixes = listOf("", "-deobfuscator.wasm", ".teadbg")
listOf("incari.wasm-runtime.js=${layout.buildDirectory.dir(gameBuildDir).get().asFile.resolve("incari.wasm-runtime.js")}") +
suffixes.map { "incari.wasm$it=${compatibleDir.resolve("incari.wasm$it")}" } +
suffixes.map { "incari-fast.wasm$it=${fastDir.resolve("incari.wasm$it")}" }
}
// What the page loads, by the name it loads it by: the builds' files, the mesher, and the asset pack.
val buildFiles: List<String> = run {
val mesherDir = layout.buildDirectory.dir("teavm-mesher").get().asFile
gameModuleFiles +
listOf("mesher.wasm", "mesher.wasm-runtime.js").map { "$it=${mesherDir.resolve(it)}" } +
"incari.pack=${pageDir.get().file("incari.pack").asFile}"
}
// The experimental Rust build (ADR 0068): Horizon's browser port, its own page and files, which
// `./incari build` writes here (tools/build Horizon). Offered when it's there.
val rustDir = layout.buildDirectory.dir("rust").get().asFile
tasks.register<JavaExec>("buildManifest") {
group = "build"
description = "Writes build/page/build.json: the build's files with their sizes and hashes."
dependsOn("assetPack", teavmMesher)
// After a compile in the same run, not beside it: hashing a module TeaVM is still writing gave
// the page a manifest for the last build, and a cold start that never reached its first frame.
mustRunAfter("teavm")
classpath = webbuildTool
mainClass = "incari.tools.webbuild.BuildManifest"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val out = pageDir.get().file("build.json").asFile
val version = minecraftVersion.get()
val files = buildFiles
val rust = rustDir
// Always: it hashes whatever build is there, which Gradle doesn't track between the tasks.
outputs.upToDateWhen { false }
outputs.file(out)
argumentProviders.add(CommandLineArgumentProvider {
listOf("--out", out.path, "--game", version, "--rust", rust.path) + files.flatMap { listOf("--file", it) }
})
}
// The loader page and its scripts, served by name over whatever the build's directory holds (the page
// there is a copy from the last compile), with both builds' modules by name. An experiment's build
// gets the page but no manifest, pack or other build.
fun pageServerArgs(experiment: Boolean): List<String> {
val scripts = pageDir.get().dir("scripts").asFile
val page = layout.projectDirectory.file("src/main/web/index.html").asFile
val names = listOf("boot", "loader", "features", "jspi", "wakeups", "cache-policy", "sw", "game-worker")
return listOf("--file", "index.html=$page") +
names.flatMap { listOf("--file", "$it.js=${scripts.resolve("$it.js")}") } +
(if (experiment) emptyList() else listOf(
"--file", "mesher.wasm=${mesherOutput.get().file("mesher.wasm").asFile}",
"--file", "mesher.wasm-runtime.js=${mesherOutput.get().file("mesher.wasm-runtime.js").asFile}",
"--file", "build.json=${pageDir.get().file("build.json").asFile}",
"--file", "incari.pack=${pageDir.get().file("incari.pack").asFile}") +
gameModuleFiles.flatMap { listOf("--file", it) } +
listOf("--dir", "rust=${rustDir.path}"))
}
tasks.register<JavaExec>("serve") {
group = "application"
description = "Serves the game's builds on http://localhost:8080/ for development (never publish a build)."
dependsOn("shaders", pageScripts, "buildManifest")
classpath = webbuildTool
mainClass = "incari.tools.webbuild.Serve"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val output = layout.buildDirectory.dir(gameBuildDir)
val port = providers.gradleProperty("port").orElse("8080")
// Resolved now: clientJar's mapping captures the build script, which the configuration cache can't store.
val jar = clientJar.get()
val manifest = shaderManifest
val assets = assetServerArgs.get()
val page = pageServerArgs(false)
argumentProviders.add(CommandLineArgumentProvider {
listOf(output.get().asFile.path, "--port", port.get(),
"--file", "client.jar=$jar", "--file", "shaders.json=" + manifest.get().asFile.path) + assets + page
})
}
// ---- The web folder --------------------------------------------------------------------------
// `./gradlew :app-web:webFolder -Pteavm.release` writes what `serve` serves into one folder any static
// web server can serve (tools/webbuild WebFolder, ADR 0028), with its own build.json, an .htaccess and
// a README.txt that says it must not be shared. `./incari build` runs it. Options: `-Pweb.out=<dir>`
// (default build/web/), `-Pweb.builds=fast,compatible` (the builds to put in, both by default; ADR
// 0036: each must be compiled, Fast with -Pteavm.fast, and both release builds; `rust` adds
// build/rust/, ADR 0068), `-Pweb.noSounds`
// (leave the asset index out: ~460 MB of sounds, languages and the Unicode font), `-Pweb.skipBuild` (compile nothing first; otherwise the one
// build -Pteavm.fast picks is compiled). It holds Mojang's code and files: never published.
tasks.register<JavaExec>("webFolder") {
group = "distribution"
description = "Writes the browser builds as one folder for a static web server (never publish it)."
if (!providers.gradleProperty("web.skipBuild").isPresent) {
dependsOn("teavm")
}
dependsOn("assetPack", teavmMesher, pageScripts)
classpath = webbuildTool
mainClass = "incari.tools.webbuild.WebFolder"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val out = providers.gradleProperty("web.out").map { File(it).absolutePath }
.orElse(layout.buildDirectory.dir("web").get().asFile.path)
val builds = providers.gradleProperty("web.builds").orElse("fast,compatible").get()
.split(",").map { it.trim() }.filter { it.isNotEmpty() }
builds.forEach {
require(it == "fast" || it == "compatible" || it == "rust") {
"-Pweb.builds takes fast, compatible and rust, not '$it'"
}
}
val sounds = !providers.gradleProperty("web.noSounds").isPresent
val soundFiles = when {
providers.gradleProperty("web.noSoundFiles").isPresent -> "no"
providers.gradleProperty("web.smallSounds").isPresent -> "small"
providers.gradleProperty("web.coreSounds").isPresent -> "core"
else -> "yes"
}
val version = minecraftVersion.get()
val jar = clientJar.get()
// The index and objects directory assetServerArgs serves, as WebFolder's two options.
val assets = assetServerArgs.get().filterIndexed { i, _ -> i % 2 == 1 }
.map { it.substringAfter('=') }
val compatible = layout.buildDirectory.dir("teavm").get().asFile
val fast = layout.buildDirectory.dir("teavm-fast").get().asFile
val mesher = mesherOutput.get().asFile
val rust = rustDir
val page = layout.projectDirectory.file("src/main/web/index.html").asFile
val scripts = pageDir.get().dir("scripts").asFile
val pack = pageDir.get().file("incari.pack").asFile
// Always: it copies whatever build is there, which Gradle doesn't track between the tasks.
outputs.upToDateWhen { false }
argumentProviders.add(CommandLineArgumentProvider {
listOf(
"--out", out.get(),
"--game", version,
"--mesher", mesher.path,
"--page", page.path,
"--scripts", scripts.path,
"--pack", pack.path,
"--client-jar", jar,
) + (if ("fast" in builds) listOf("--fast", fast.path) else emptyList()) +
(if ("compatible" in builds) listOf("--compatible", compatible.path) else emptyList()) +
(if ("rust" in builds) listOf("--rust", rust.path) else emptyList()) +
(if (sounds && assets.size == 2) listOf("--asset-index", assets[0], "--asset-objects", assets[1])
else emptyList()) +
listOf("--sound-files", soundFiles)
})
}
// `./gradlew :app-web:webFolder :app-web:singleFile -Pteavm.release -Pweb.smallSounds -Pweb.html=<file>`
// packs the folder webFolder wrote (-Pweb.out) into one HTML file that plays from the disk (tools/webbuild
// SingleFile, ADR 0057); `./incari build --html` runs it. -Pweb.smallSounds keeps the languages, the
// Unicode font and every sound but the music, encoded smaller with ffmpeg (~38 MB of 377;
// tools/webbuild SmallSounds); -Pweb.coreSounds ~10 MB of common sounds as they are (CoreSounds);
// -Pweb.noSoundFiles none of the sounds. Like the folder, never published.
tasks.register<JavaExec>("singleFile") {
group = "distribution"
description = "Packs the web folder into one HTML file that plays from the disk (never publish it)."
dependsOn(pageScripts)
mustRunAfter("webFolder")
classpath = webbuildTool
mainClass = "incari.tools.webbuild.SingleFile"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val folder = providers.gradleProperty("web.out").map { File(it).absolutePath }
.orElse(layout.buildDirectory.dir("web").get().asFile.path)
val html = providers.gradleProperty("web.html").map { File(it).absolutePath }
.orElse(layout.buildDirectory.file("incari.html").get().asFile.path)
val script = pageDir.get().dir("scripts").file("offline.js").asFile
outputs.upToDateWhen { false }
argumentProviders.add(CommandLineArgumentProvider {
listOf("--folder", folder.get(), "--out", html.get(), "--script", script.path)
})
}
tasks.register<JavaExec>("browserCheck") {
group = "verification"
description = "Runs build/teavm/ in headless Chromium until the game loop's heartbeat shows."
// `-Pbrowser.html=<file>`: a single-file build (singleFile, ADR 0057) instead, opened from the
// disk with nothing compiled or served; the other options work as for the build.
val html = providers.gradleProperty("browser.html").map { File(it).absolutePath }
if (!html.isPresent) {
dependsOn("teavm", "shaders", pageScripts)
}
val experiment = providers.gradleProperty("teavm.main").isPresent
if (!experiment && !html.isPresent) {
dependsOn("buildManifest")
}
classpath = webbuildTool
mainClass = "incari.tools.webbuild.BrowserCheck"
// The build the page runs (PageQuery); none for an experiment's, which has one module.
systemProperty("incari.build", if (providers.gradleProperty("teavm.main").isPresent) "" else gameBuild)
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val output = layout.buildDirectory.dir(
providers.gradleProperty("teavm.main").map { "teavm-experiment" }.orElse(gameBuildDir))
// `-Pbrowser.expect=<regex> -Pbrowser.count=<n>` for experiments (see the teavm task).
val expect = providers.gradleProperty("browser.expect")
val count = providers.gradleProperty("browser.count")
val seconds = providers.gradleProperty("browser.seconds")
// `-Pbrowser.query=renderer=headless` and the like: page options (see WebMain).
val query = providers.gradleProperty("browser.query")
// `-Pbrowser.steps="shot:build/title.png;click:0.5,0.45;sleep:2000;shot:build/next.png"`: what to do
// once the game runs, through the DevTools protocol (BrowserCheck.runStep lists the steps). A `;`
// starts a new step only before a step's name, so `eval:` JavaScript may contain them.
// `-Pbrowser.steps=@browser-checks/text-input.steps` reads them from a file, a step per line.
val steps = providers.gradleProperty("browser.steps")
val projectDir = layout.projectDirectory
val stepNames ="sleep|wait|shot|move|click|drag|hold|type|eval|init|key|down|up|assert|waitfor|holds|until|resize|clipboard|compose|insert|drop|rcon|rconwait|reload|choose|downloads|download|pack|profile"
// `-Pbrowser.rcon=127.0.0.1:25592`: the game server's remote console, for `rcon:` steps;
// the password comes from INCARI_RCON_PASSWORD.
val rcon = providers.gradleProperty("browser.rcon")
// `-Pbrowser.gpu=gl` (or vulkan): WebGL on this machine's GPU instead of SwiftShader, for
// timing frames; `webgpu`: Vulkan with WebGPU on the GPU too (probes/WebGpuCallProbe).
val gpu = providers.gradleProperty("browser.gpu")
val jar = clientJar.get()
val manifest = shaderManifest
val assets = assetServerArgs.get()
val page = pageServerArgs(experiment)
argumentProviders.add(CommandLineArgumentProvider {
(if (html.isPresent) listOf(html.get()) else listOf(output.get().asFile.path,
"--file", "client.jar=$jar", "--file", "shaders.json=" + manifest.get().asFile.path) + assets + page) +
(if (query.isPresent) listOf("--query", query.get()) else emptyList()) +
(if (!steps.isPresent) emptyList()
else if (steps.get().startsWith("@")) listOf("--steps-file", projectDir.file(steps.get().substring(1)).asFile.path)
else steps.get().split(Regex(";(?=($stepNames):)")).filter { it.isNotBlank() }.flatMap { listOf("--step", it) }) +
(if (seconds.isPresent) listOf("--seconds", seconds.get()) else emptyList()) +
(if (rcon.isPresent) listOf("--rcon", rcon.get()) else emptyList()) +
(if (gpu.isPresent) listOf("--gpu", gpu.get()) else emptyList()) +
(if (expect.isPresent) listOf("--expect", expect.get()) else emptyList()) +
(if (count.isPresent) listOf("--count", count.get()) else emptyList())
})
}
// ---- Screenshot diffs against the desktop ----------------------------------------------------
// `./gradlew :app-web:screenshotDiff` renders the scenes in screenshot-scenes/scenes.txt with the
// desktop game (Mojang's OpenGL backend) and with the browser build (WebGL2, in headless Chromium
// on this machine's GPU), both joined to a fresh vanilla server, and fails if a pair is less alike
// (SSIM) than the file's threshold, or if the page logs a WebGL error. The images are renders of
// Mojang's assets: they go to build/screenshots/ and are never committed. Needs a display and a GPU
// (the desktop game opens a window). Options: `-Pscreenshots.only=terrain,sky`,
// `-Pscreenshots.gpu=gl|vulkan|swiftshader` (default gl: ANGLE on the desktop's own driver),
// `-Pscreenshots.reuseDesktop` (keep the desktop images already rendered), `-Pscreenshots.skipBuild`
// (use build/teavm/ as it is instead of compiling first), `-Pscreenshots.port=18210` (six ports up
// from it: server, RCON, bridge, desktop agent, page, DevTools).
tasks.register<JavaExec>("screenshotDiff") {
group = "verification"
description = "Renders fixed scenes on the desktop (OpenGL) and in Chromium (WebGL2) and compares them."
if (!providers.gradleProperty("screenshots.skipBuild").isPresent) {
dependsOn("teavm")
}
dependsOn("shaders", ":app-desktop:sceneLaunch", pageScripts, "buildManifest")
classpath = webbuildTool
mainClass = "incari.tools.webbuild.ScreenshotDiff"
// The build the page runs (PageQuery, ADR 0036).
systemProperty("incari.build", gameBuild)
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val scenes = layout.projectDirectory.dir("screenshot-scenes")
val output = layout.buildDirectory.dir(gameBuildDir)
val out = layout.buildDirectory.dir("screenshots")
val launch = project(":app-desktop").layout.buildDirectory.file("scene-launch.txt")
val versionDir = minecraftVersion.map { repoRoot.dir("work/cache/versions/$it").asFile.path }.get()
val version = minecraftVersion.get()
val jar = clientJar.get()
val manifest = shaderManifest
val only = providers.gradleProperty("screenshots.only")
// `-Pscreenshots.query=sprites=off`: extra page options for the browser's run, to compare.
val screenshotQuery = providers.gradleProperty("screenshots.query")
val gpu = providers.gradleProperty("screenshots.gpu").orElse("gl")
val port = providers.gradleProperty("screenshots.port").orElse("18210")
val reuseDesktop = providers.gradleProperty("screenshots.reuseDesktop").isPresent
val page = pageServerArgs(false)
// Always runs: its inputs include a GPU, a server and two games.
outputs.upToDateWhen { false }
argumentProviders.add(CommandLineArgumentProvider {
listOf(
"--scenes", scenes.file("scenes.txt").asFile.path,
"--options", scenes.file("options.txt").asFile.path,
"--server-properties", scenes.file("server.properties").asFile.path,
"--out", out.get().asFile.path,
"--build", output.get().asFile.path,
"--file", "client.jar=$jar",
"--file", "shaders.json=" + manifest.get().asFile.path,
"--desktop-launch", launch.get().asFile.path,
"--version-json", "$versionDir/$version.json",
"--cache", versionDir,
"--gpu", gpu.get(),
"--port", port.get(),
) + page + (if (only.isPresent) listOf("--only", only.get()) else emptyList()) +
(if (screenshotQuery.isPresent) listOf("--query", screenshotQuery.get()) else emptyList()) +
(if (reuseDesktop) listOf("--reuse-desktop") else emptyList())
})
}
// ---- The benchmark ---------------------------------------------------------------------------
// `./gradlew :app-web:benchmark` plays benchmark/benchmark.txt's scenarios (a fly-through over fresh
// terrain, a fight in an arena) in the browser build against a fresh vanilla world, times the loads
// (cold and warm start to the title screen, the join), and reports what the page's profiler
// measured: frame rate and 1% low, tick, extract, render submit and GPU time, draw calls, the mesh
// queue, memory and GC pauses. The report goes to build/benchmark/ (report.md, report.json) and, in
// CI, to the job summary. It fails if a figure regressed past its rule against this machine's
// baseline (benchmark/baseline.properties). Needs a GPU for meaningful figures. Options:
// `-Pbenchmark.machine=<name>` (default: the host name), `-Pbenchmark.updateBaseline` (record this
// machine's figures instead of comparing), `-Pbenchmark.only=flythrough`, `-Pbenchmark.query=multidraw=off`
// (extra page options), `-Pbenchmark.gpu=gl|vulkan|swiftshader` (default gl), `-Pbenchmark.headed` (a
// Chromium window instead of headless), `-Pbenchmark.connect=<host>:<port> -Pbenchmark.pageHost=<address>`
// (a Chrome reachable over DevTools, a Chromebook's: docs/benchmark.md), `-Pbenchmark.skipBuild`
// (use build/teavm/ as it is), `-Pbenchmark.port=18310` (five ports up from it: server, RCON, bridge,
// page, DevTools), `-Pbenchmark.history=<file>` (default ~/.incari/benchmark-history.jsonl: the runs the
// report's trend charts come from, kept on this machine only), `-Pbenchmark.cpuThrottle=<rate>` (the
// page's CPU that many times slower: a Chromebook stand-in, under its own machine name),
// `-Pbenchmark.singleplayer` (benchmark/singleplayer.txt in a world the page creates and runs itself,
// ADR 0039: no server here; its own baseline, singleplayer-baseline.properties, and history). Run
// :app-web:checkDownloadSize first
// to have the download size in the report.
tasks.register<JavaExec>("benchmark") {
group = "verification"
description = "Plays the benchmark's scenarios in the browser build and holds the figures to the baseline."
if (!providers.gradleProperty("benchmark.skipBuild").isPresent) {
dependsOn("teavm")
}
dependsOn("shaders", pageScripts, "buildManifest")
classpath = webbuildTool
mainClass = "incari.tools.webbuild.Benchmark"
// The build the page runs (PageQuery, ADR 0036).
systemProperty("incari.build", gameBuild)
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val dir = layout.projectDirectory.dir("benchmark")
val output = layout.buildDirectory.dir(gameBuildDir)
val out = layout.buildDirectory.dir("benchmark")
val downloadReport = layout.buildDirectory.file("reports/download-size.json")
val versionDir = minecraftVersion.map { repoRoot.dir("work/cache/versions/$it").asFile.path }.get()
val version = minecraftVersion.get()
val jar = clientJar.get()
val manifest = shaderManifest
val assets = assetServerArgs.get()
val page = pageServerArgs(false)
val machine = providers.gradleProperty("benchmark.machine")
val update = providers.gradleProperty("benchmark.updateBaseline").isPresent
val only = providers.gradleProperty("benchmark.only")
val query = providers.gradleProperty("benchmark.query")
val gpu = providers.gradleProperty("benchmark.gpu").orElse("gl")
val headed = providers.gradleProperty("benchmark.headed").isPresent
// `-Pbenchmark.cpuThrottle=4`: Chrome runs the page's CPU four times slower, a stand-in for a
// Chromebook's CPU (ADR 0027); record it under a machine name of its own.
val cpuThrottle = providers.gradleProperty("benchmark.cpuThrottle")
// `-Pbenchmark.gcTrace`: each scenario's collector events, phases included, in time order
// (build/benchmark/<scenario>-<n>.gc.txt; ADR 0027).
val gcTrace = providers.gradleProperty("benchmark.gcTrace").isPresent
// `-Pbenchmark.profile`: a CPU profile of each measured stretch, build/benchmark/<scenario>-<n>.cpuprofile.
val profile = providers.gradleProperty("benchmark.profile").isPresent
// `-Pbenchmark.heapProfile`: the heap sampler's live objects at the title screen and after each
// scenario, build/benchmark/<name>.heapprofile.
val heapProfile = providers.gradleProperty("benchmark.heapProfile").isPresent
// `-Pbenchmark.heapSnapshot`: heap snapshots at the same points, with their sizes by type.
val heapSnapshot = providers.gradleProperty("benchmark.heapSnapshot").isPresent
// `-Pbenchmark.desktopJfr`: the desktop game plays the scenarios instead of the page, each
// measured stretch recorded by the Flight Recorder with its allocations by site.
val desktopJfr = providers.gradleProperty("benchmark.desktopJfr").isPresent
if (desktopJfr) {
dependsOn(":app-desktop:sceneLaunch")
}
val desktopLaunch = project(":app-desktop").layout.buildDirectory.file("scene-launch.txt")
val connect = providers.gradleProperty("benchmark.connect")
val pageHost = providers.gradleProperty("benchmark.pageHost")
val port = providers.gradleProperty("benchmark.port").orElse("18310")
// `-Pbenchmark.singleplayer`: singleplayer's scenarios, figures and baseline instead (ADR 0039).
val singleplayer = providers.gradleProperty("benchmark.singleplayer").isPresent
// `-Pbenchmark.script=hudeditor.txt`: another script in benchmark/ (with -Pbenchmark.singleplayer
// for one that plays in the page's own world), measured but kept out of the usual history.
val script = providers.gradleProperty("benchmark.script")
val history = providers.gradleProperty("benchmark.history")
.orElse(
System.getProperty("user.home") + "/.incari/benchmark-" +
(if (singleplayer) "singleplayer-" else "") + "history.jsonl",
)
// Always runs: its inputs include a GPU, a server and a browser.
outputs.upToDateWhen { false }
argumentProviders.add(CommandLineArgumentProvider {
listOf(
"--script",
dir.file(script.getOrElse(if (singleplayer) "singleplayer.txt" else "benchmark.txt")).asFile.path,
"--options", dir.file("options.txt").asFile.path,
"--server-properties", dir.file("server.properties").asFile.path,
"--baseline",
dir.file(if (singleplayer) "singleplayer-baseline.properties" else "baseline.properties").asFile.path,
"--budgets", dir.file("budgets.properties").asFile.path,
"--out", out.get().asFile.path,
"--build", output.get().asFile.path,
"--file", "client.jar=$jar",
"--file", "shaders.json=" + manifest.get().asFile.path,
"--version-json", "$versionDir/$version.json",
"--cache", versionDir,
"--download-report", downloadReport.get().asFile.path,
"--history", history.get(),
"--gpu", gpu.get(),
"--port", port.get(),
) + assets + page +
(if (machine.isPresent) listOf("--machine", machine.get()) else emptyList()) +
(if (update) listOf("--update-baseline") else emptyList()) +
(if (only.isPresent) listOf("--only", only.get()) else emptyList()) +
(if (query.isPresent) listOf("--query", query.get()) else emptyList()) +
(if (headed) listOf("--headed") else emptyList()) +
(if (profile) listOf("--profile") else emptyList()) +
(if (heapProfile) listOf("--heap-profile") else emptyList()) +
(if (heapSnapshot) listOf("--heap-snapshot") else emptyList()) +
(if (desktopJfr) listOf("--desktop-launch", desktopLaunch.get().asFile.path) else emptyList()) +
(if (connect.isPresent) listOf("--connect", connect.get()) else emptyList()) +
(if (pageHost.isPresent) listOf("--page-host", pageHost.get()) else emptyList()) +
(if (cpuThrottle.isPresent) listOf("--cpu-throttle", cpuThrottle.get()) else emptyList()) +
(if (gcTrace) listOf("--gc-trace") else emptyList()) +
(if (singleplayer) listOf("--singleplayer") else emptyList())
})
}
// ---- Download-size budget --------------------------------------------------------------------
// `./gradlew :app-web:checkDownloadSize` measures what a player downloads (the build output and
// the files the dev server serves beside it) against download-budget.properties, raw, gzip and
// brotli, and fails when a file is over budget or unclassified. It writes
// build/reports/download-size.json for charting. `-PdownloadSize.skipBuild` measures the build
// already in build/teavm/ instead of compiling first (the compile takes about ten minutes);
// `-PdownloadSize.noBrotli` skips brotli, whose highest quality takes a minute or two.
tasks.register<JavaExec>("checkDownloadSize") {
group = "verification"
description = "Checks the browser build's download size against download-budget.properties."
val skipBuild = providers.gradleProperty("downloadSize.skipBuild").isPresent
if (!skipBuild) {
dependsOn("teavm")
// The build-time shader manifest, once that task exists.
dependsOn(tasks.matching { it.name == "shaders" })
}
dependsOn(pageScripts, "buildManifest")
classpath = webbuildTool
mainClass = "incari.tools.webbuild.DownloadSize"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val budget = layout.projectDirectory.file("download-budget.properties")
val output = layout.buildDirectory.dir(gameBuildDir)
val shaders = layout.buildDirectory.file("web-shaders/shaders.json")
val report = layout.buildDirectory.file("reports/download-size.json")
val noBrotli = providers.gradleProperty("downloadSize.noBrotli").isPresent
// Resolved now: clientJar's mapping captures the build script, which the configuration cache
// can't store inside a task.
val vendorJar = clientJar.get()
// The loader page: its scripts, the build manifest and the asset pack.
val scripts = pageDir.get().dir("scripts").asFile
val pageFiles = listOf("boot", "loader", "features", "jspi", "wakeups", "cache-policy", "sw", "game-worker").map { "$it.js=${scripts.resolve("$it.js")}" } +
listOf("build.json=${pageDir.get().file("build.json").asFile}", "incari.pack=${pageDir.get().file("incari.pack").asFile}")
argumentProviders.add(CommandLineArgumentProvider {
listOf(
"--budget", budget.asFile.path,
"--dir", output.get().asFile.path,
// Files the page fetches from outside build/teavm/: <name as the page fetches it>=<path>.
"--file", "shaders.json=" + shaders.get().asFile.path,
"--file", "client.jar=" + vendorJar,
"--report", report.get().asFile.path,
) + pageFiles.flatMap { listOf("--file", it) } + (if (noBrotli) listOf("--no-brotli") else emptyList())
})
}
@@ -0,0 +1,82 @@
# What a player downloads to start the browser build, checked by `./gradlew :app-web:checkDownloadSize`
# (tools/webbuild DownloadSize). Raising a number is fine when the pull request says why; the point
# is that growth is noticed.
#
# Every file in app-web/build/teavm/, and each extra file the page fetches, must be classified here,
# or the check fails: nothing ships unmeasured.
# download the page fetches it at start: measured and budgeted
# debug only a development build has it; measured, not budgeted
# report a compile report; the page never fetches it
# vendor Mojang's file, fetched by the page but not shipped by Incari: measured, not budgeted
file.incari.wasm=download
file.incari.wasm-runtime.js=download
file.index.html=download
# The build-time shader manifest (built by :app-web:shaders; the dev server serves it next to the page).
# The page reads it from the asset pack; an experiment's build without a pack still
# fetches it, so it's measured, not counted twice.
file.shaders.json=debug
# The loader: its scripts (src/main/ts, types stripped), the build manifest, and the asset pack
# (build-time data: the translated shaders, in a zip).
file.boot.js=download
file.loader.js=download
file.features.js=download
file.jspi.js=download
file.wakeups.js=download
file.game-worker.js=download
file.cache-policy.js=download
file.sw.js=download
file.build.json=download
file.incari.pack=download
# TeaVM's stack deobfuscator and the debug information it reads. The development page fetches both
# at start (index.html enables `stackDeobfuscator`), but a release build (webbuild --release) makes
# neither, so they aren't part of what a player downloads.
file.incari.wasm-deobfuscator.wasm=debug
file.incari.wasm.teadbg=debug
file.*.txt=report
# The game's own jar, which the page unpacks for its resources (ClientJar). Mojang's file: reported
# so its weight is visible, never counted as Incari's.
file.client.jar=vendor
# Limits in bytes. The budget is in gzip (level 9, compressed once at deploy time): every browser
# and static host handles it. Brotli (quality 11) is smaller and reported next to it, but a host may
# not serve it. The module's raw size is limited too: the Chromebook holds and compiles it uncompressed.
#
# The limits are the development build's size (`:app-web:teavm`: TeaVM's SIMPLE optimization,
# unobfuscated, so the module carries a 70 MB `name` section) plus a little headroom. Accidental
# growth (a survey rule that pulls in a library, a class-library change that drags in a subsystem)
# tends to be bigger than that, so a limit is raised deliberately. Measured 2026-09-29, with Via and
# the Eagler stage: development build 193.86 MB raw, 38.65 MB gzip; release build (-Pteavm.release)
# 66.33 MB raw, 20.06 MB gzip, 12.56 MB brotli. Via's translation code is most of the growth.
max.gzip.total=40_300_000
max.gzip.incari.wasm=40_000_000
max.raw.incari.wasm=200_000_000
# TeaVM's loader; changes only with a TeaVM upgrade (8.8 kB gzip measured).
max.gzip.incari.wasm-runtime.js=10_000
# The page, with its loading screen's images inline (the backdrop, the mark and the icon, base64:
# about 26 kB that gzip can't shrink). Measured 21.8 kB gzip (2026-10-20).
max.gzip.index.html=25_000
# The translated shaders: 309 stages, 1107 kB raw, 43.5 kB gzip (2026-09-28, ADR 0012). They ship in
# the asset pack (below), whose limit carries this one.
# The loader's scripts are a few kilobytes each; the asset pack carries the shaders (deflated,
# so about what shaders.json gzips to) and a manifest.
max.gzip.boot.js=6_000
max.gzip.loader.js=4_000
max.gzip.features.js=2_000
# Measured 1.6, 1.1 and 2.6 kB gzip (2026-10-19).
max.gzip.jspi.js=3_000
max.gzip.wakeups.js=2_000
max.gzip.game-worker.js=4_000
max.gzip.cache-policy.js=2_000
max.gzip.sw.js=3_000
max.gzip.build.json=2_000
# Via's mapping data rides in the pack (classpath/): 1.25 MB of NBT and JSON, about 270 kB
# compressed. Measured 318.5 kB gzip with the shaders.
# The vanilla sprites decoded (ADR 0026) with their mip levels (sprites.bin, 3142 sprites, 7.4
# MB raw, about 1.06 MB deflated), so a start skips decoding their PNGs. Measured 1.39 MB with the rest.
# Incari's own pack rides in it too (classpath/incari-pack/): GUI textures and six fonts, 379 kB
# packed. Measured 1.73 MB in all (2026-10-20).
max.gzip.incari.pack=1_900_000
@@ -0,0 +1,61 @@
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Regression probe for tools/teavm-patches' TArrayDeque fix: removing elements through an
* {@code ArrayDeque}'s iterator, as the game's particle groups do every tick. TeaVM's iterator
* skipped the element after one it removed and then returned null past the end, so the first
* particle to expire in a world crashed the game. Checks every removal pattern of up to ten
* elements, with the deque's contents wrapped around its array at several offsets. Prints
* "probe passed" when every deque holds what's left in order.
*/
public final class ArrayDequeProbe {
private ArrayDequeProbe() {}
public static void main(String[] args) {
String failure = null;
for (int size = 1; size <= 10 && failure == null; size++) {
for (int removed = 0; removed < 1 << size && failure == null; removed++) {
for (int offset = 0; offset < 5 && failure == null; offset++) {
failure = check(size, removed, offset);
}
}
}
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
/** Null if removing the elements whose bits are set in {@code removed} works, else what went wrong. */
private static String check(int size, int removed, int offset) {
ArrayDeque<Integer> deque = new ArrayDeque<>(8);
for (int i = 0; i < offset; i++) {
deque.add(-1);
}
for (int i = 0; i < offset; i++) {
deque.poll();
}
List<Integer> expected = new ArrayList<>();
for (int i = 0; i < size; i++) {
deque.add(i);
if ((removed & 1 << i) == 0) {
expected.add(i);
}
}
List<Integer> seen = new ArrayList<>();
for (Iterator<Integer> iterator = deque.iterator(); iterator.hasNext(); ) {
Integer value = iterator.next();
seen.add(value);
if (value != null && (removed & 1 << value) != 0) {
iterator.remove();
}
}
List<Integer> left = new ArrayList<>(deque);
if (seen.size() != size || seen.contains(null) || !left.equals(expected)) {
return "size " + size + ", removing " + Integer.toBinaryString(removed) + ", offset " + offset
+ ": iterated " + seen + ", left " + left;
}
return null;
}
}
@@ -0,0 +1,33 @@
import com.viaversion.viaversion.api.minecraft.item.HashedStructuredItem;
import com.viaversion.viaversion.api.minecraft.item.Item;
import com.viaversion.viaversion.api.minecraft.item.StructuredItem;
/**
* Regression probe for Via's StructuredItemRewriter: it tells a data component's value
* apart with {@code value instanceof Item[]}. Prints "probe passed" when arrays of other element
* types (and an interface array of another interface) don't answer true, and real item arrays do.
*/
public final class ArrayInstanceOfProbe {
interface Other {}
private ArrayInstanceOfProbe() {}
public static void main(String[] args) {
Object items = new StructuredItem[] {StructuredItem.empty()};
Object itemIface = new Item[] {StructuredItem.empty()};
Object hashed = new HashedStructuredItem[] {HashedStructuredItem.empty()};
Object others = new Other[] {new Other() {}};
Object strings = new String[] {"a"};
Object objects = new Object[] {"a"};
Object nested = new StructuredItem[][] {{StructuredItem.empty()}};
Object ints = new int[1];
Object intsNested = new int[1][1];
String more = "" + (nested instanceof Item[][]) + (nested instanceof Item[]) + (nested instanceof Other[][])
+ (ints instanceof int[]) + (ints instanceof Object[]) + (intsNested instanceof int[][])
+ (intsNested instanceof Item[][]) + (strings instanceof Object[]) + (null instanceof Item[]);
String result = "" + (items instanceof Item[]) + (itemIface instanceof Item[]) + (hashed instanceof Item[])
+ (others instanceof Item[]) + (strings instanceof Item[]) + (objects instanceof Item[]);
System.out.println((result + more).equals("truetruefalsefalsefalsefalse" + "truefalsefalsetruefalsetruefalsetruefalse") ? "probe passed" : "probe failed: " + result + " " + more);
}
}
@@ -0,0 +1,99 @@
import java.nio.ByteBuffer;
import org.teavm.jso.JSBody;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Measures how bytes cross between Java arrays and JavaScript buffers in the WebAssembly GC build:
* TeaVM's {@code Int8Array.copyFromJavaArray} / {@code copyToJavaArray}, against a route through a
* direct buffer in linear memory, which JavaScript can view and slice. Every message between the
* page and singleplayer's server worker (packets, file changes) crosses this way. Prints the times
* and "probe passed" when both routes agree on the bytes.
*/
public final class ByteCopyProbe {
private ByteCopyProbe() {}
public static void main(String[] args) {
int size = 1 << 20;
byte[] source = new byte[size];
for (int i = 0; i < size; i++) {
source[i] = (byte) (i * 31 + (i >>> 8));
}
ByteBuffer direct = ByteBuffer.allocateDirect(size);
int rounds = 20;
// Warm up both routes.
for (int i = 0; i < 3; i++) {
Int8Array.copyFromJavaArray(source);
viaLinear(source, direct);
}
double start = now();
Int8Array teavm = null;
for (int i = 0; i < rounds; i++) {
teavm = Int8Array.copyFromJavaArray(source);
}
double teavmOut = (now() - start) / rounds;
start = now();
ArrayBuffer linear = null;
for (int i = 0; i < rounds; i++) {
linear = viaLinear(source, direct);
}
double linearOut = (now() - start) / rounds;
start = now();
byte[] back = null;
for (int i = 0; i < rounds; i++) {
back = teavm.copyToJavaArray();
}
double teavmIn = (now() - start) / rounds;
start = now();
byte[] backLinear = null;
for (int i = 0; i < rounds; i++) {
backLinear = fromLinear(linear, direct);
}
double linearIn = (now() - start) / rounds;
boolean same = java.util.Arrays.equals(back, source) && java.util.Arrays.equals(backLinear, source)
&& same(teavm.getBuffer(), linear);
System.out.println("ByteCopyProbe: 1 MiB to JavaScript: copyFromJavaArray " + teavmOut
+ " ms, through linear memory " + linearOut + " ms; back: copyToJavaArray " + teavmIn
+ " ms, through linear memory " + linearIn + " ms");
System.out.println(same ? "probe passed" : "probe failed: the bytes differ");
}
private static ArrayBuffer viaLinear(byte[] source, ByteBuffer direct) {
direct.clear();
direct.put(source, 0, source.length);
return sliceOf(Int8Array.fromJavaBuffer(direct), source.length);
}
private static byte[] fromLinear(ArrayBuffer buffer, ByteBuffer direct) {
int length = buffer.getByteLength();
setInto(Int8Array.fromJavaBuffer(direct), buffer);
byte[] out = new byte[length];
direct.get(0, out, 0, length);
return out;
}
@JSBody(
params = {"view", "length"},
script = "return view.buffer.slice(view.byteOffset, view.byteOffset + length);")
private static native ArrayBuffer sliceOf(Int8Array view, int length);
@JSBody(
params = {"view", "buffer"},
script = "view.set(new Int8Array(buffer));")
private static native void setInto(Int8Array view, ArrayBuffer buffer);
@JSBody(
params = {"a", "b"},
script = "var x = new Int8Array(a), y = new Int8Array(b); if (x.length !== y.length) return false;"
+ "for (var i = 0; i < x.length; i++) if (x[i] !== y[i]) return false; return true;")
private static native boolean same(ArrayBuffer a, ArrayBuffer b);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,35 @@
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.local.LocalChannel;
/**
* {@code Bootstrap.channel(Class)} in the browser build: it works for a channel class whose
* constructor tools/webbuild's ReflectionDeclarations declares, and throws for one it doesn't, as
* it did for PlatformSocketChannel in the server list's legacy ping (which crashed the game).
*/
public final class ChannelClassProbe {
private ChannelClassProbe() {}
/** Public, with a public no-arg constructor, like PlatformSocketChannel; not declared. */
public static final class Undeclared extends LocalChannel {
public Undeclared() {}
}
public static void main(String[] args) {
System.setProperty("io.netty.noUnsafe", "true");
try {
new Bootstrap().channel(LocalChannel.class);
System.out.println("channel(Class) accepted a declared class");
} catch (Throwable t) {
System.out.println("probe failed: channel(Class) threw for a declared class: " + t);
return;
}
try {
new Bootstrap().channel(Undeclared.class);
System.out.println("probe failed: channel(Class) accepted an undeclared class");
} catch (Throwable t) {
System.out.println("channel(Class) threw " + t);
System.out.println("probe passed");
}
}
}
@@ -0,0 +1,413 @@
/**
* Measures what TeaVM's coroutine transformation costs ordinary code in the browser build: the same
* workload compiled twice, once as plain functions and once as coroutines, timed in one module.
*
* <p>The workload looks like the game's hot paths: a loop over objects calling through interfaces
* with several implementations (as block, shape and entity code does), and a small open-addressing
* table whose lookups call the keys' {@code hashCode} and {@code equals} (as every {@code Map.get}
* does). In the game those virtual calls are suspension points because one implementation somewhere
* can block (ADR 0027), so the coroutine copy puts one blocking implementation into each call site's
* reach, never called. Everything else is the same code, duplicated by hand: shared code would merge
* the two copies in TeaVM's flow analysis. Prints nanoseconds per item for each copy, and "probe
* passed".
*
* <p>Each copy has one extra implementation at each call that the loops never call: blocking in
* the coroutine copy, harmless in the plain one, so both call sites are equally polymorphic.
*
* <p>What it found (2026-10-05, release build, Chrome on the desktop): with coroutines the
* coroutine copy takes 8.3 to 8.7 ns an item against 5.5 to 5.9 ns, about 1.5 times as long; in the
* Fast build ({@code -Pteavm.fast}, no coroutines) the two take the same, 5.3 to 5.7 ns. Only the
* callers ({@code coroutineWork}, {@code CTable.get}) are coroutines here; the shapes and keys stay
* plain.
* That's about 0.7 ns for each call through a suspension point, from the coroutine's prologue, the
* check after each call, and locals kept alive and nullable for the save path.
*/
public final class CoroutineCostProbe {
private static final int ITEMS = 200_000;
private static final int ROUNDS = 7;
/** Never true; lets the coroutine copy's blocking implementations suspend. */
static volatile boolean suspend;
static volatile long sink;
static void maybeSleep() {
if (suspend) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
// ----- Plain copy -----
interface PShape {
double value(int i, PVec v);
}
static final class PVec {
double x;
double y;
double z;
PVec(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static final class PBox implements PShape {
final double size;
PBox(double size) {
this.size = size;
}
@Override
public double value(int i, PVec v) {
return v.x * size + v.y - (i & 3);
}
}
static final class PSlab implements PShape {
@Override
public double value(int i, PVec v) {
return v.z * 0.5 + (i & 7);
}
}
static final class PStair implements PShape {
final PShape inner;
PStair(PShape inner) {
this.inner = inner;
}
@Override
public double value(int i, PVec v) {
return inner.value(i + 1, v) * 0.25 + v.y;
}
}
static class PKey {
final int a;
final int b;
PKey(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
return a * 31 + b;
}
@Override
public boolean equals(Object o) {
return o instanceof PKey k && k.a == a && k.b == b;
}
}
/** As CBlocking, without the blocking: the same number of implementations at each call. */
static final class PExtra implements PShape {
@Override
public double value(int i, PVec v) {
sink++;
return 0;
}
}
/** As CBlockingKey, without the blocking. */
static final class PExtraKey extends PKey {
PExtraKey() {
super(-1, -1);
}
@Override
public int hashCode() {
sink++;
return 7;
}
@Override
public boolean equals(Object o) {
sink++;
return false;
}
}
static final class PKey2 extends PKey {
PKey2(int a, int b) {
super(a, b);
}
@Override
public int hashCode() {
return a * 17 ^ b;
}
}
static final class PTable {
final Object[] keys = new Object[1024];
final int[] values = new int[1024];
void put(Object key, int value) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null && !keys[slot].equals(key)) {
slot = (slot + 1) & 1023;
}
keys[slot] = key;
values[slot] = value;
}
int get(Object key) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null) {
if (keys[slot].equals(key)) {
return values[slot];
}
slot = (slot + 1) & 1023;
}
return -1;
}
}
static double plainWork(PShape[] shapes, PVec[] vecs, PTable table, Object[] keys) {
double acc = 0;
for (int i = 0; i < ITEMS; i++) {
PVec v = vecs[i & 63];
acc += shapes[i & 7].value(i, v);
acc += table.get(keys[i & 255]);
}
return acc;
}
// ----- Coroutine copy: the same, with one blocking implementation in reach -----
interface CShape {
double value(int i, CVec v);
}
static final class CVec {
double x;
double y;
double z;
CVec(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static final class CBox implements CShape {
final double size;
CBox(double size) {
this.size = size;
}
@Override
public double value(int i, CVec v) {
return v.x * size + v.y - (i & 3);
}
}
static final class CSlab implements CShape {
@Override
public double value(int i, CVec v) {
return v.z * 0.5 + (i & 7);
}
}
static final class CStair implements CShape {
final CShape inner;
CStair(CShape inner) {
this.inner = inner;
}
@Override
public double value(int i, CVec v) {
return inner.value(i + 1, v) * 0.25 + v.y;
}
}
/** Never in the timed loop's array slots it reads; only makes the calls suspension points. */
static final class CBlocking implements CShape {
@Override
public double value(int i, CVec v) {
maybeSleep();
return 0;
}
}
static class CKey {
final int a;
final int b;
CKey(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
return a * 31 + b;
}
@Override
public boolean equals(Object o) {
return o instanceof CKey k && k.a == a && k.b == b;
}
}
static final class CKey2 extends CKey {
CKey2(int a, int b) {
super(a, b);
}
@Override
public int hashCode() {
return a * 17 ^ b;
}
}
/** As the game's one blocking toString makes every Object method a suspension point. */
static final class CBlockingKey extends CKey {
CBlockingKey() {
super(-1, -1);
}
@Override
public int hashCode() {
maybeSleep();
return 7;
}
@Override
public boolean equals(Object o) {
maybeSleep();
return false;
}
}
static final class CTable {
final Object[] keys = new Object[1024];
final int[] values = new int[1024];
void put(Object key, int value) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null && !keys[slot].equals(key)) {
slot = (slot + 1) & 1023;
}
keys[slot] = key;
values[slot] = value;
}
int get(Object key) {
int slot = key.hashCode() & 1023;
while (keys[slot] != null) {
if (keys[slot].equals(key)) {
return values[slot];
}
slot = (slot + 1) & 1023;
}
return -1;
}
}
static double coroutineWork(CShape[] shapes, CVec[] vecs, CTable table, Object[] keys) {
double acc = 0;
for (int i = 0; i < ITEMS; i++) {
CVec v = vecs[i & 63];
acc += shapes[i & 7].value(i, v);
acc += table.get(keys[i & 255]);
}
return acc;
}
public static void main(String[] args) throws InterruptedException {
// Threads must exist for TeaVM to compile anything as a coroutine.
Thread other = new Thread(() -> sink++);
other.start();
other.join();
PShape[] pShapes = new PShape[9];
CShape[] cShapes = new CShape[9];
for (int i = 0; i < 8; i++) {
pShapes[i] = switch (i % 3) {
case 0 -> new PBox(i);
case 1 -> new PSlab();
default -> new PStair(new PBox(i + 1));
};
cShapes[i] = switch (i % 3) {
case 0 -> new CBox(i);
case 1 -> new CSlab();
default -> new CStair(new CBox(i + 1));
};
}
cShapes[8] = new CBlocking();
pShapes[8] = new PExtra();
PVec[] pVecs = new PVec[64];
CVec[] cVecs = new CVec[64];
for (int i = 0; i < 64; i++) {
pVecs[i] = new PVec(i, i * 0.5, i * 0.25);
cVecs[i] = new CVec(i, i * 0.5, i * 0.25);
}
PTable pTable = new PTable();
CTable cTable = new CTable();
Object[] pKeys = new Object[257];
Object[] cKeys = new Object[257];
for (int i = 0; i < 256; i++) {
pKeys[i] = (i & 1) == 0 ? new PKey(i, i >> 2) : new PKey2(i, i >> 2);
cKeys[i] = (i & 1) == 0 ? new CKey(i, i >> 2) : new CKey2(i, i >> 2);
pTable.put(pKeys[i], i);
cTable.put(cKeys[i], i);
}
cKeys[256] = new CBlockingKey();
pKeys[256] = new PExtraKey();
// The blocking ones reach the same call sites, as in the game, but are never called in the
// timed loops (they index & 7 and & 255).
if (suspend) {
cTable.put(cKeys[256], 0);
sink += (long) cShapes[8].value(0, cVecs[0]);
pTable.put(pKeys[256], 0);
sink += (long) pShapes[8].value(0, pVecs[0]);
}
for (int round = 0; round < ROUNDS; round++) {
// Alternate which copy runs first, so neither gains from going second.
double a;
double b;
long plain;
long coroutine;
if ((round & 1) == 0) {
long t0 = System.nanoTime();
a = plainWork(pShapes, pVecs, pTable, pKeys);
long t1 = System.nanoTime();
b = coroutineWork(cShapes, cVecs, cTable, cKeys);
plain = t1 - t0;
coroutine = System.nanoTime() - t1;
} else {
long t0 = System.nanoTime();
b = coroutineWork(cShapes, cVecs, cTable, cKeys);
long t1 = System.nanoTime();
a = plainWork(pShapes, pVecs, pTable, pKeys);
coroutine = t1 - t0;
plain = System.nanoTime() - t1;
}
sink += (long) (a + b);
System.out.println("round " + round + ": plain " + String.format("%.2f", plain / (double) ITEMS)
+ " ns/item, coroutine " + String.format("%.2f", coroutine / (double) ITEMS)
+ " ns/item, ratio " + String.format("%.2f", coroutine / (double) plain)
+ (a == b ? "" : " (results differ!)"));
}
System.out.println("probe passed");
}
}
@@ -0,0 +1,100 @@
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.InflaterInputStream;
/**
* Round-trips data through the browser build's deflate and inflate streams, written the way the
* game writes chunks and NBT files (a DataOutputStream over a BufferedOutputStream over the
* compressor: single bytes, short and long runs). TeaVM's own DeflaterOutputStream failed partway
* through with zlib's "no progress" (-5), and singleplayer's saved chunks didn't read back. Half
* the trials read back the way a chunk scan does, skipping runs between reads: TeaVM's
* InflaterInputStream.skip overwrote its own compressed input.
*/
public class DeflateProbe {
private static final int TRIALS = 60;
public static void main(String[] args) throws Exception {
Random random = new Random(26);
int failures = 0;
for (int trial = 0; trial < TRIALS; trial++) {
int size = 1 + random.nextInt(trial % 10 == 0 ? 500_000 : 60_000);
byte[] data = new byte[size];
for (int i = 0; i < size; i++) {
data[i] = (byte) (random.nextInt(5) == 0 ? random.nextInt(256) : i % 37);
}
boolean gzip = trial % 3 == 0;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
OutputStream compressor = gzip ? new GZIPOutputStream(bytes) : new DeflaterOutputStream(bytes);
try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(compressor))) {
int position = 0;
while (position < size) {
int kind = random.nextInt(4);
if (kind == 0) {
out.writeByte(data[position++]);
} else {
int length = Math.min(size - position, 1 + random.nextInt(kind == 1 ? 16 : 20_000));
out.write(data, position, length);
position += length;
}
if (random.nextInt(50) == 0) {
out.flush();
}
}
}
byte[] back;
try (InputStream in = gzip
? new GZIPInputStream(new ByteArrayInputStream(bytes.toByteArray()))
: new InflaterInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
ByteArrayOutputStream collected = new ByteArrayOutputStream();
byte[] buffer = new byte[1 + random.nextInt(8192)];
boolean skipping = trial % 2 == 1;
int n;
while (true) {
if (skipping && random.nextBoolean()) {
// Skipped bytes are compared as zeros: the expected data gets the same.
int length = random.nextInt(3000);
long skipped = in.skip(length);
int start = collected.size();
for (long k = 0; k < skipped; k++) {
collected.write(0);
}
Arrays.fill(data, Math.min(start, data.length), Math.min(start + (int) skipped, data.length), (byte) 0);
if (skipped < length) {
break;
}
continue;
}
if ((n = in.read(buffer)) <= 0) {
break;
}
collected.write(buffer, 0, n);
}
back = collected.toByteArray();
} catch (Exception e) {
failures++;
System.out.println("trial " + trial + " (" + size + " bytes, gzip " + gzip + ") failed to read: " + e);
continue;
}
if (!Arrays.equals(back, data)) {
failures++;
System.out.println("trial " + trial + " (" + size + " bytes, gzip " + gzip + ") came back as " + back.length
+ " different bytes");
}
}
if (failures == 0) {
System.out.println(TRIALS + " deflate round trips came back whole");
System.out.println("probe passed");
} else {
System.out.println("probe failed: " + failures + " of " + TRIALS + " round trips");
}
}
}
@@ -0,0 +1,33 @@
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Regression probe for tools/teavm-patches' Heap fix: direct buffers of a whole number of
* 64 KiB pages, allocated once the heap's last record is in use. TeaVM grew the heap by exactly the
* request, which left the new free record a header too small, and threw OutOfMemoryError with the
* memory far from full: the game's 256x256 colour maps failed to load as soon as the heap's layout
* put an allocated record last. Keeps every buffer (half a gigabyte), so each one lands at the end
* of the heap. Prints "probe passed" when they all fit.
*/
public final class DirectAllocationProbe {
private DirectAllocationProbe() {}
public static void main(String[] args) {
List<ByteBuffer> kept = new ArrayList<>();
try {
// Each odd-sized buffer grows the heap by whole pages and leaves the rest of the last
// page free, a remainder 8 bytes different each time, so one of them fits exactly and
// leaves the last record allocated; the page-sized buffer after it then needs the fix.
for (int k = 0; k < 4096; k++) {
kept.add(ByteBuffer.allocateDirect(65536 - 8 * (k + 1)));
kept.add(ByteBuffer.allocateDirect(65536));
}
} catch (OutOfMemoryError e) {
System.out.println("probe failed: OutOfMemoryError after " + kept.size() + " buffers");
return;
}
System.out.println("probe passed");
}
}
@@ -0,0 +1,178 @@
import io.netty.channel.EventLoop;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.local.LocalIoHandler;
import java.util.Arrays;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
/**
* Measures how long a task the page's main thread hands to a Netty local event loop (as the
* browser's connections run on) waits before it runs, when the main thread then works for a while
* and waits for the next animation frame, as the game does each frame. Prints the wait's median,
* 95th percentile and max in ms, the frame interval for scale, and "probe passed".
*
* <p>What it found (2026-11-15, headless Chrome, Compatible build): the task ran as soon as the main
* thread stopped for the frame, 6.2 ms after it was handed over with 6 ms of work in between, every
* time. The hop to the loop costs no frame of its own.
*/
public final class EventLoopHopProbe {
private EventLoopHopProbe() {}
static volatile double ranAt;
public static void main(String[] args) throws Exception {
// As app-web's LibraryDefaults sets them.
System.setProperty("io.netty.allocator.type", "unpooled");
System.setProperty("io.netty.noUnsafe", "true");
System.setProperty("io.netty.leakDetection.level", "disabled");
System.setProperty("io.netty.machineId", "00:00:00:00:00:00:00:01");
System.setProperty("io.netty.processId", "1");
MultiThreadIoEventLoopGroup group = new MultiThreadIoEventLoopGroup(
1, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe IO"), LocalIoHandler.newFactory());
EventLoop loop = group.next();
loop.submit(() -> {}).sync();
// Other threads parked as the game's are (more event loops, timers), each in LockSupport.
MultiThreadIoEventLoopGroup others = new MultiThreadIoEventLoopGroup(
0, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe other"), LocalIoHandler.newFactory());
int parked = 0;
for (io.netty.util.concurrent.EventExecutor other : others) {
other.submit(() -> {}).sync();
parked++;
}
System.out.println("EventLoopHopProbe: " + parked + " other loops parked, "
+ Runtime.getRuntime().availableProcessors() + " processors");
int frames = 240;
for (int pass = 0; pass < 3; pass++) {
boolean slots = pass >= 1;
setSlotEnd(pass == 2 ? 1000 / 60.0 + 1 : 1000 / 60.0 - 2);
// Pass 1 adds the background pool's idle slot as the page has it: after each frame, a
// message that keeps the page busy until 2 ms before the next frame is due.
setIdleSlots(slots);
double[] waits = new double[frames];
double[] ran = new double[frames];
Arrays.fill(ran, -1);
for (int i = 0; i < frames; i++) {
nextFrame();
int index = i;
double handedAt = now();
waits[i] = handedAt;
loop.execute(() -> ran[index] = now());
// The frame's own work: a few ms on the main thread, no yielding.
busy(6);
}
for (int i = 0; i < 30; i++) {
nextFrame();
}
setIdleSlots(false);
for (int i = 0; i < frames; i++) {
waits[i] = ran[i] < 0 ? 1e9 : ran[i] - waits[i];
}
Arrays.sort(waits);
System.out.println("EventLoopHopProbe: " + (pass == 0 ? "no idle slots" : pass == 1 ? "idle slots ending 2 ms before the frame" : "idle slots running 1 ms past the frame")
+ ", hand-off to run, ms: median " + waits[frames / 2] + " p95 " + waits[frames * 95 / 100]
+ " max " + waits[frames - 1]);
}
// As the game since its network wake: the main thread waits for a frame or a message, a
// page callback (a stand-in for the socket's onmessage) wakes it, and it hands the message
// to the loop from there before waiting again.
setIdleSlots(true);
setSlotEnd(1000 / 60.0 - 2);
double[] woken = new double[frames];
double[] wokenRan = new double[frames];
Arrays.fill(wokenRan, -1);
int handed = 0;
startMessages();
while (handed < frames) {
if (!frameOrMessage()) {
int index = handed++;
woken[index] = now();
loop.execute(() -> wokenRan[index] = now());
} else {
busy(6);
}
}
stopMessages();
for (int i = 0; i < 30; i++) {
nextFrame();
}
setIdleSlots(false);
for (int i = 0; i < frames; i++) {
woken[i] = wokenRan[i] < 0 ? 1e9 : wokenRan[i] - woken[i];
}
Arrays.sort(woken);
System.out.println("EventLoopHopProbe: handed over from a wake by a page callback, ms: median "
+ woken[frames / 2] + " p95 " + woken[frames * 95 / 100] + " max " + woken[frames - 1]);
group.shutdownGracefully();
others.shutdownGracefully();
System.out.println("probe passed");
}
private static void busy(double millis) {
double end = now() + millis;
while (now() < end) {
// spin
}
}
@Async
private static native Boolean nextFrame();
private static void nextFrame(AsyncCallback<Boolean> callback) {
requestFrame(() -> callback.complete(true));
}
@Async
private static native Boolean frameOrMessage();
private static void frameOrMessage(AsyncCallback<Boolean> callback) {
waitFrameOrMessage(frame -> callback.complete(frame));
}
@JSFunctor
interface FrameOrMessage extends JSObject {
void run(boolean frame);
}
@JSBody(
params = "callback",
script = "var w = window.__hopWait || (window.__hopWait = { waiter: null, pending: false });"
+ "w.waiter = callback; if (!w.pending) { w.pending = true; requestAnimationFrame(function() {"
+ " w.pending = false; var c = w.waiter; w.waiter = null; if (c) c(true); }); }")
private static native void waitFrameOrMessage(FrameOrMessage callback);
@JSBody(
script = "window.__hopTimer = setInterval(function() { var w = window.__hopWait;"
+ " if (w && w.waiter) { var c = w.waiter; w.waiter = null; c(false); } }, 7);")
private static native void startMessages();
@JSBody(script = "clearInterval(window.__hopTimer);")
private static native void stopMessages();
@JSFunctor
interface Frame extends JSObject {
void run();
}
@JSBody(params = "frame", script = "requestAnimationFrame(function() { frame(); });")
private static native void requestFrame(Frame frame);
@JSBody(
params = "on",
script = "window.__hopSlots = on; if (!on || window.__hopSlotsStarted) return; window.__hopSlotsStarted = true;"
+ "var ch = new MessageChannel(); var last = 0;"
+ "ch.port1.onmessage = function() { var end = last + (window.__hopSlotEnd || 14);"
+ " while (performance.now() < end) {} };"
+ "function frame(t) { if (window.__hopSlots) { last = t; ch.port2.postMessage(0); } requestAnimationFrame(frame); }"
+ "requestAnimationFrame(frame);")
private static native void setIdleSlots(boolean on);
@JSBody(params = "millis", script = "window.__hopSlotEnd = millis;")
private static native void setSlotEnd(double millis);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,69 @@
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
/**
* Whether Netty's event loop knows its own thread in the browser build: {@code inEventLoop()} from
* a task on the loop, and a channel connected through a {@code ChannelInitializer}, as singleplayer's
* server end does. Netty asserts both ({@code DefaultChannelPipeline.invokeHandlerAddedIfNeeded}),
* so a false there fails every connection with an AssertionError.
*/
public final class EventLoopProbe {
private EventLoopProbe() {}
public static void main(String[] args) throws Exception {
// As app-web's LibraryDefaults sets them.
System.setProperty("io.netty.allocator.type", "unpooled");
System.setProperty("io.netty.noUnsafe", "true");
System.setProperty("io.netty.leakDetection.level", "disabled");
System.setProperty("io.netty.machineId", "00:00:00:00:00:00:00:01");
System.setProperty("io.netty.processId", "1");
boolean assertions = false;
assert assertions = true;
System.out.println("assertions enabled: " + assertions);
EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe IO"), LocalIoHandler.newFactory());
var loop = group.next();
System.out.println("inEventLoop from main: " + loop.inEventLoop());
boolean[] inside = new boolean[1];
loop.submit(() -> inside[0] = loop.inEventLoop()).sync();
System.out.println("inEventLoop from a task: " + inside[0]);
LocalAddress address = new LocalAddress("probe");
new ServerBootstrap()
.group(group)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {}
})
.bind(address)
.sync();
try {
Channel channel = new Bootstrap()
.group(group)
.channel(LocalChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
System.out.println("initChannel ran, inEventLoop " + channel.eventLoop().inEventLoop());
}
})
.connect(address)
.sync()
.channel();
System.out.println("connected: " + channel.isActive());
System.out.println("probe passed");
} catch (Throwable e) {
System.out.println("probe failed: " + e);
}
}
}
@@ -0,0 +1,71 @@
import java.io.IOException;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
/**
* A failed download, reported to a suspended coroutine from a promise's rejection handler: the
* caller catches it and carries on, and the page doesn't crash.
*
* <p>Reporting it through {@code AsyncCallback.error} crashes the page: TeaVM's WebAssembly GC
* runtime resumes the caller, which catches the exception, and then also rethrows it out of the
* JavaScript callback, where it's an unhandled rejection. The page crashed this way on a missing
* asset index (in the screenshot harness). So {@code incari.app.web.Fetch} and
* {@code WebAudioDecoder} complete with a value that says it failed and throw in Java, as this
* probe does; set {@link #USE_ERROR} to see TeaVM's behavior.
*/
public final class FetchFailureProbe {
/** True to report the failure through {@code AsyncCallback.error}, which crashes the page. */
private static final boolean USE_ERROR = false;
@JSFunctor
interface Failed extends JSObject {
void failed(String message);
}
@JSBody(
params = {"failed"},
script = "Promise.reject(new Error('HTTP 404')).then(null, function(e) { failed(String(e)); });")
private static native void start(Failed failed);
@Async
private static native String fetch() throws IOException;
private static void fetch(AsyncCallback<String> callback) {
start(message -> {
if (USE_ERROR) {
callback.error(new IOException("Couldn't fetch: " + message));
} else {
callback.complete("failed: " + message);
}
});
}
private static void fetchOrThrow() throws IOException {
String outcome = fetch();
if (outcome.startsWith("failed: ")) {
throw new IOException("Couldn't fetch: " + outcome.substring("failed: ".length()));
}
}
public static void main(String[] args) throws InterruptedException {
try {
fetchOrThrow();
System.out.println("probe failed: no exception");
return;
} catch (IOException e) {
System.out.println("caught " + e.getMessage());
}
try {
fetchOrThrow();
} catch (IOException e) {
System.out.println("caught again " + e.getMessage());
}
// A crash would come as the page's unhandled rejection, after the callback returns.
Thread.sleep(2000);
System.out.println("probe passed");
}
}
@@ -0,0 +1,44 @@
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Regression probe for web-classlib's FileInputStreamAdditions, and for RandomAccessFile's own
* read() since TeaVM 0.16.0: TeaVM's single-byte {@code read()} returned bytes signed, so a byte of
* 0x80 or more read as the end of the file, and the game's {@code NbtIo.read(Path)} (a
* DataInputStream straight over the file) lost {@code servers.dat}. Prints "probe passed" when every
* byte reads back unsigned.
*/
public final class FileReadProbe {
private FileReadProbe() {}
public static void main(String[] args) throws IOException {
File file = new File("/probe.dat");
try (FileOutputStream out = new FileOutputStream(file)) {
out.write(new byte[] {0x0A, (byte) 0xC8, (byte) 0xFF, 0x00, 0x01});
}
StringBuilder problems = new StringBuilder();
try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
int first = in.readUnsignedByte();
int second = in.readUnsignedShort();
short third = in.readShort();
if (first != 0x0A || second != 0xC8FF || third != 1) {
problems.append(" stream: ").append(first).append(',').append(second).append(',').append(third);
}
if (in.read() != -1) {
problems.append(" stream end");
}
}
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
raf.seek(1);
if (raf.read() != 0xC8 || raf.readUnsignedByte() != 0xFF) {
problems.append(" random access");
}
}
System.out.println(problems.isEmpty() ? "probe passed" : "probe failed:" + problems);
}
}
@@ -0,0 +1,108 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Regression probe for tools/teavm-patches' TTemplateCollections hashing (ADR 0034): the sets and
* maps {@code Set.of}, {@code Set.copyOf}, {@code Map.of} and {@code Map.ofEntries} make for more
* than two elements. Lookups now probe a table of indices; this checks they answer as a
* {@code HashSet} or {@code HashMap} would, for hits and misses, with colliding hashes, for every
* size up to 40, and that duplicates still throw (of) or are dropped (copyOf). Prints
* "probe passed" when every answer agrees.
*/
public final class ImmutableCollectionsProbe {
private ImmutableCollectionsProbe() {}
/** A key whose hash is chosen, so keys can collide. */
private record Key(int id, int hash) {
@Override
public boolean equals(Object o) {
return o instanceof Key k && k.id == id;
}
@Override
public int hashCode() {
return hash;
}
}
public static void main(String[] args) {
String failure = null;
for (int size = 0; size <= 40 && failure == null; size++) {
for (int spread = 1; spread <= 3 && failure == null; spread++) {
failure = check(size, spread);
}
}
if (failure == null) {
failure = duplicates();
}
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
/** Keys 0..size-1 whose hashes are id / spread (several share one when spread > 1). */
private static String check(int size, int spread) {
List<Key> keys = new ArrayList<>();
for (int i = 0; i < size; i++) {
keys.add(new Key(i, i / spread));
}
Set<Key> copied = Set.copyOf(keys);
Set<Key> of = Set.of(keys.toArray(new Key[0]));
@SuppressWarnings("unchecked")
Map.Entry<Key, Integer>[] entries = new Map.Entry[size];
for (int i = 0; i < size; i++) {
entries[i] = Map.entry(keys.get(i), i * 10);
}
Map<Key, Integer> map = Map.ofEntries(entries);
Map<Key, Integer> mapCopy = Map.copyOf(new HashMap<>(map));
Set<Key> reference = new HashSet<>(keys);
if (copied.size() != size || of.size() != size || map.size() != size || mapCopy.size() != size) {
return "size " + size + " spread " + spread + ": sizes " + copied.size() + ", " + of.size() + ", " + map.size();
}
if (!new HashSet<>(copied).equals(reference) || !new HashSet<>(of).equals(reference)
|| !new HashSet<>(map.keySet()).equals(reference)) {
return "size " + size + " spread " + spread + ": iteration";
}
// Hits, and misses: ids past the end, some with a hash a present key has.
for (int id = 0; id < size + 20; id++) {
Key probe = new Key(id, id / spread);
boolean present = id < size;
Integer value = present ? id * 10 : null;
if (copied.contains(probe) != present || of.contains(probe) != present
|| map.containsKey(probe) != present || mapCopy.containsKey(probe) != present
|| !java.util.Objects.equals(map.get(probe), value)
|| !java.util.Objects.equals(mapCopy.get(probe), value)
|| map.entrySet().contains(Map.entry(probe, id * 10)) != present
|| (present && map.entrySet().contains(Map.entry(probe, -1)))) {
return "size " + size + " spread " + spread + ": lookup of " + id;
}
}
if (copied.contains("not a key") || map.containsKey("not a key") || map.get("not a key") != null) {
return "size " + size + ": a key of another type";
}
return null;
}
private static String duplicates() {
try {
Set.of(new Key(1, 0), new Key(2, 0), new Key(1, 0));
return "Set.of accepted a duplicate";
} catch (IllegalArgumentException expected) {
// As the JDK's.
}
try {
Map.of(new Key(1, 0), 1, new Key(2, 0), 2, new Key(1, 0), 3);
return "Map.of accepted a duplicate key";
} catch (IllegalArgumentException expected) {
// As the JDK's.
}
Set<Key> copied = Set.copyOf(List.of(new Key(1, 0), new Key(2, 0), new Key(1, 0), new Key(3, 7)));
if (copied.size() != 3 || !copied.contains(new Key(3, 7)) || copied.contains(new Key(4, 7))) {
return "Set.copyOf kept " + copied.size() + " of a list with a duplicate";
}
return null;
}
}
@@ -0,0 +1,135 @@
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* Measures inflating packets the way the game's decoder does (one inflater, input and output as
* buffers, a reset after each) in the browser build, against the route before web-classlib's
* Inflater: a new zlib stream per packet (what TeaVM's reset did) and new input and output arrays
* per call (InflaterAdditions). A server's mix of sizes over the compression threshold. Prints
* microseconds per packet and "probe passed" when both routes read the packets back whole.
*
* <p>What it found (2026-11-15, headless Chrome, Compatible build, best of six alternated
* rounds): inflating, 14.2 us a packet with a new stream and arrays each, 11.2 us reset in place;
* deflating, 74.5 us and 60.4 us.
*/
public final class InflatePacketProbe {
private InflatePacketProbe() {}
public static void main(String[] args) throws DataFormatException {
Random random = new Random(26);
int packets = 2000;
byte[][] plain = new byte[packets][];
byte[][] compressed = new byte[packets][];
Deflater deflater = new Deflater();
byte[] buffer = new byte[8192];
for (int i = 0; i < packets; i++) {
// Mostly entity and block updates just over the threshold, some chunks.
int size = i % 25 == 0 ? 20_000 + random.nextInt(60_000) : 256 + random.nextInt(1500);
byte[] data = new byte[size];
for (int j = 0; j < size; j++) {
data[j] = (byte) ((j / 37) % 4 == 0 ? random.nextInt(256) : (j & 7));
}
plain[i] = data;
deflater.setInput(data);
deflater.finish();
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
while (!deflater.finished()) {
out.write(buffer, 0, deflater.deflate(buffer));
}
deflater.reset();
compressed[i] = out.toByteArray();
}
boolean same = true;
for (int round = 0; round < 2; round++) {
same &= asBefore(plain, compressed) && asNow(plain, compressed);
}
// Alternated, best of each, so neither route gains from running second.
double before = Double.MAX_VALUE;
double after = Double.MAX_VALUE;
double deflateNew = Double.MAX_VALUE;
double deflateReset = Double.MAX_VALUE;
for (int round = 0; round < 6; round++) {
double start = now();
same &= asBefore(plain, compressed);
before = Math.min(before, (now() - start) * 1000 / packets);
start = now();
same &= asNow(plain, compressed);
after = Math.min(after, (now() - start) * 1000 / packets);
start = now();
deflateEach(plain, true);
deflateNew = Math.min(deflateNew, (now() - start) * 1000 / packets);
start = now();
deflateEach(plain, false);
deflateReset = Math.min(deflateReset, (now() - start) * 1000 / packets);
}
System.out.println("InflatePacketProbe: inflate per packet: a new stream and arrays each " + before
+ " us, reset in place " + after + " us; deflate per packet: a new stream each " + deflateNew
+ " us, reset in place " + deflateReset + " us");
System.out.println(same ? "probe passed" : "probe failed: a packet didn't read back");
}
/** As before: a new stream per packet, input and output copied through new arrays. */
private static boolean asBefore(byte[][] plain, byte[][] compressed) throws DataFormatException {
boolean same = true;
for (int i = 0; i < plain.length; i++) {
Inflater inflater = new Inflater();
ByteBuffer input = ByteBuffer.wrap(compressed[i]);
byte[] in = new byte[input.remaining()];
input.get(in);
inflater.setInput(in);
ByteBuffer output = ByteBuffer.allocateDirect(plain[i].length);
byte[] out = new byte[output.remaining()];
int written = inflater.inflate(out);
output.put(out, 0, written);
inflater.end();
same &= written == plain[i].length && check(output, plain[i]);
}
return same;
}
/** As the game's decoder now runs: one inflater, the buffer forms, a reset after each. */
private static boolean asNow(byte[][] plain, byte[][] compressed) throws DataFormatException {
boolean same = true;
Inflater inflater = new Inflater();
for (int i = 0; i < plain.length; i++) {
inflater.setInput(ByteBuffer.wrap(compressed[i]));
ByteBuffer output = ByteBuffer.allocateDirect(plain[i].length);
int written = inflater.inflate(output);
inflater.reset();
same &= written == plain[i].length && check(output, plain[i]);
}
inflater.end();
return same;
}
/** As the game's encoder: input array, a kept output array, then a reset (or a new stream, as before). */
private static void deflateEach(byte[][] plain, boolean newEach) {
byte[] buffer = new byte[8192];
Deflater deflater = new Deflater();
for (byte[] data : plain) {
if (newEach) {
deflater.end();
deflater = new Deflater();
}
deflater.setInput(data, 0, data.length);
deflater.finish();
while (!deflater.finished()) {
deflater.deflate(buffer);
}
deflater.reset();
}
deflater.end();
}
private static boolean check(ByteBuffer output, byte[] expected) {
int n = expected.length;
return output.get(0) == expected[0] && output.get(n / 2) == expected[n / 2] && output.get(n - 1) == expected[n - 1];
}
@org.teavm.jso.JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,56 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Regression probe for tools/teavm-patches' ClassInitializerInsertionTransformer fix: a
* class's static initializer runs after its superclass's (JLS 12.4.2). TeaVM ran a subclass's first
* when the first use was {@code new Sub()}. The game numbers entity data by class this way
* ({@code SynchedEntityData.defineId} counts on from the superclass's last id), so creating the
* player on joining a server failed with "Duplicate id value for 0!". Prints "probe passed" when
* ids count up from the root class, as on the JVM.
*/
public final class InitOrderProbe {
static final List<String> ORDER = new ArrayList<>();
static final Map<Class<?>, Integer> LAST_IDS = new HashMap<>();
private InitOrderProbe() {}
/** The next id for {@code type}, after its own or its nearest superclass's last one. */
static int define(Class<?> type) {
Integer last = LAST_IDS.get(type);
Class<?> current = type;
while (last == null && (current = current.getSuperclass()) != Object.class) {
last = LAST_IDS.get(current);
}
int id = last == null ? 0 : last + 1;
LAST_IDS.put(type, id);
ORDER.add(type.getSimpleName() + "=" + id);
return id;
}
static class Root {
static final int FIRST = define(Root.class);
static final int SECOND = define(Root.class);
}
static class Middle extends Root {
static final int THIRD = define(Middle.class);
}
/** No initializer of its own between two classes that have one. */
static class Plain extends Middle {}
static final class Leaf extends Plain {
static final int FOURTH = define(Leaf.class);
}
public static void main(String[] args) {
new Leaf();
String expected = "[Root=0, Root=1, Middle=2, Leaf=3]";
String actual = ORDER.toString();
System.out.println(actual.equals(expected) ? "probe passed" : "probe failed: " + actual);
}
}
@@ -0,0 +1,52 @@
import java.util.concurrent.locks.LockSupport;
/**
* Regression probe for tools/teavm-patches' TObject fix: a thread interrupted in
* {@code wait()} holds the monitor again when the InterruptedException arrives, so it leaves its
* {@code synchronized} block normally. TeaVM threw without the monitor, and the block's exit threw
* IllegalMonitorStateException: the game's sound thread, parked through web-classlib's
* {@code LockSupport} and interrupted when the sound engine stops (joining a world), crashed the
* game this way. Prints "probe passed" when both a plain wait and a park end cleanly.
*/
public final class InterruptedWaitProbe {
private static final Object LOCK = new Object();
private static volatile String waitResult = "not run";
private static volatile String parkResult = "not run";
private InterruptedWaitProbe() {}
public static void main(String[] args) throws InterruptedException {
Thread waiter = new Thread(() -> {
try {
synchronized (LOCK) {
try {
LOCK.wait();
waitResult = "woke without an interrupt";
} catch (InterruptedException e) {
waitResult = Thread.holdsLock(LOCK) ? "ok" : "interrupted without the monitor";
}
}
} catch (IllegalMonitorStateException e) {
waitResult = "IllegalMonitorStateException leaving the block";
}
});
Thread parker = new Thread(() -> {
try {
LockSupport.park();
parkResult = Thread.currentThread().isInterrupted() ? "ok" : "returned without the interrupt";
} catch (IllegalMonitorStateException e) {
parkResult = "IllegalMonitorStateException in park";
}
});
waiter.start();
parker.start();
Thread.sleep(50);
waiter.interrupt();
parker.interrupt();
waiter.join();
parker.join();
boolean passed = waitResult.equals("ok") && parkResult.equals("ok");
System.out.println(passed ? "probe passed" : "probe failed: wait " + waitResult + ", park " + parkResult);
}
}
@@ -0,0 +1,124 @@
/**
* Checks that Java threads behave the same in the Fast build (fibers on JSPI, {@code -Pteavm.fast})
* as with TeaVM's coroutines in the Compatible build: sleeping, waiting and notifying, joining,
* exceptions thrown after a thread resumed and caught across the frames that waited, and
* {@code Thread.currentThread()} after each wait. Times a wait/notify ping-pong between two threads, the cost of a thread switch. Prints
* "probe passed" or "probe failed: ...". Run it in both builds.
*/
public final class JspiProbe {
private static final int PING_PONGS = 2000;
static final Object LOCK = new Object();
static int turn;
static volatile String failure;
static void check(boolean condition, String what) {
if (!condition && failure == null) {
failure = what;
}
}
static int sleepThenThrow(int depth) throws InterruptedException {
if (depth == 0) {
Thread.sleep(1);
throw new IllegalStateException("after the sleep");
}
return sleepThenThrow(depth - 1) + 1;
}
public static void main(String[] args) throws InterruptedException {
Thread main = Thread.currentThread();
long t0 = System.currentTimeMillis();
Thread.sleep(20);
long slept = System.currentTimeMillis() - t0;
check(slept >= 15, "slept only " + slept + " ms");
check(Thread.currentThread() == main, "the main thread changed over a sleep");
try {
sleepThenThrow(20);
check(false, "no exception after the sleep");
} catch (IllegalStateException e) {
check("after the sleep".equals(e.getMessage()), "wrong exception: " + e);
}
check(Thread.currentThread() == main, "the main thread changed over a throw");
// Three threads, each sleeping and counting, joined.
int[] counts = new int[3];
Thread[] workers = new Thread[3];
for (int i = 0; i < 3; i++) {
int index = i;
workers[i] = new Thread(() -> {
Thread self = Thread.currentThread();
for (int n = 0; n < 5; n++) {
try {
Thread.sleep(1 + index);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
check(Thread.currentThread() == self, "worker " + index + " resumed as another thread");
counts[index]++;
}
}, "worker-" + i);
workers[i].start();
}
for (Thread worker : workers) {
worker.join();
}
check(Thread.currentThread() == main, "the main thread changed over joins");
for (int i = 0; i < 3; i++) {
check(counts[i] == 5, "worker " + i + " counted " + counts[i]);
}
// Ping-pong: two threads hand a turn back and forth through wait/notify.
Thread pong = new Thread(() -> {
for (int n = 0; n < PING_PONGS; n++) {
synchronized (LOCK) {
while (turn != 1) {
try {
LOCK.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
turn = 0;
LOCK.notifyAll();
}
}
}, "pong");
pong.start();
long p0 = System.nanoTime();
for (int n = 0; n < PING_PONGS; n++) {
synchronized (LOCK) {
turn = 1;
LOCK.notifyAll();
while (turn != 0) {
LOCK.wait();
}
}
}
long p1 = System.nanoTime();
pong.join();
check(Thread.currentThread() == main, "the main thread changed over the ping-pong");
System.out.println("ping-pong: " + String.format("%.1f", (p1 - p0) / 1000.0 / PING_PONGS / 2)
+ " us a switch over " + PING_PONGS + " round trips");
// An uncaught exception in a thread goes to its handler, and the program goes on.
Throwable[] uncaught = new Throwable[1];
Thread thrower = new Thread(() -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
throw new IllegalArgumentException("uncaught");
});
thrower.setUncaughtExceptionHandler((t, e) -> uncaught[0] = e);
thrower.start();
thrower.join();
check(uncaught[0] instanceof IllegalArgumentException, "uncaught exception not handled: " + uncaught[0]);
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
}
@@ -0,0 +1,60 @@
/**
* Probe for tools/webbuild's {@code MathIntrinsics}: {@code Math.floor}, {@code ceil} and
* {@code sqrt} compiled to WebAssembly's own instructions give Java's answers, signed zeros,
* infinities and NaN included. Prints "probe passed" when every case matches its bits (any NaN
* matches any NaN).
*/
public final class MathProbe {
private MathProbe() {}
private static final double[] INPUTS = {
0.0, -0.0, 0.5, -0.5, 1.5, -1.5, 2.0, -2.0, 1e300, -1e300, 4503599627370495.5, -4503599627370495.5,
Double.MIN_VALUE, -Double.MIN_VALUE, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN, 2.0,
1e-300, 0.1
};
// Java's answers for INPUTS, in order: floor, ceil, sqrt.
private static final double[][] EXPECTED = {
{0.0, 0.0, 0.0},
{-0.0, -0.0, -0.0},
{0.0, 1.0, 0.7071067811865476},
{-1.0, -0.0, Double.NaN},
{1.0, 2.0, 1.224744871391589},
{-2.0, -1.0, Double.NaN},
{2.0, 2.0, 1.4142135623730951},
{-2.0, -2.0, Double.NaN},
{1e300, 1e300, 1e150},
{-1e300, -1e300, Double.NaN},
{4503599627370495.0, 4503599627370496.0, 6.710886399999999e7},
{-4503599627370496.0, -4503599627370495.0, Double.NaN},
{0.0, 1.0, 2.2227587494850775e-162},
{-1.0, -0.0, Double.NaN},
{Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY},
{Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN},
{Double.NaN, Double.NaN, Double.NaN},
{2.0, 2.0, 1.4142135623730951},
{0.0, 1.0, 1e-150},
{0.0, 1.0, 0.31622776601683794},
};
public static void main(String[] args) {
int failures = 0;
for (int i = 0; i < INPUTS.length; i++) {
double x = INPUTS[i];
double[] got = {Math.floor(x), Math.ceil(x), Math.sqrt(x)};
for (int k = 0; k < 3; k++) {
if (!same(got[k], EXPECTED[i][k])) {
failures++;
System.out.println("probe mismatch: " + new String[] {"floor", "ceil", "sqrt"}[k] + "(" + x
+ ") = " + got[k] + ", expected " + EXPECTED[i][k]);
}
}
}
System.out.println(failures == 0 ? "probe passed" : "probe failed: " + failures + " mismatches");
}
private static boolean same(double a, double b) {
return Double.isNaN(a) ? Double.isNaN(b) : Double.doubleToRawLongBits(a) == Double.doubleToRawLongBits(b);
}
}
@@ -0,0 +1,33 @@
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Regression probe for tools/webbuild's TypeCaptures: a Netty encoder decides which
* messages it takes from its superclass's type argument, read by reflection. The browser build
* kept no generic superclasses for Netty's handlers, so every encoder took every message: the
* game's {@code PacketEncoder} ({@code MessageToByteEncoder<Packet<T>>}) was handed its pipeline's
* configuration messages and failed with a ClassCastException. Prints "probe passed" when an
* encoder of the same shape takes its own messages and passes others by.
*/
public final class MessageTypeProbe {
/** A generic message, like the game's {@code Packet<T>}. */
interface Box<T> {}
static final class StringBox implements Box<String> {}
static final class BoxEncoder<T> extends MessageToByteEncoder<Box<T>> {
@Override
protected void encode(ChannelHandlerContext ctx, Box<T> message, ByteBuf out) {}
}
private MessageTypeProbe() {}
public static void main(String[] args) throws Exception {
BoxEncoder<String> encoder = new BoxEncoder<>();
boolean takesBox = encoder.acceptOutboundMessage(new StringBox());
boolean takesOther = encoder.acceptOutboundMessage("not a box");
System.out.println(takesBox && !takesOther ? "probe passed" : "probe failed: " + takesBox + ", " + takesOther);
}
}
@@ -0,0 +1,15 @@
/**
* Regression probe for web-classlib's {@code Module} and {@code ModuleLayer}: the check the
* game's {@code JvmProfiler} makes in its static initializer, which the first packet sent reaches.
* Without them the survey's rules turned the calls into nulls and the initializer threw, so the
* handshake never left. Prints "probe passed" when the check runs and finds no {@code jdk.jfr}.
*/
public final class ModuleProbe {
private ModuleProbe() {}
public static void main(String[] args) {
boolean jfr = Runtime.class.getModule().getLayer().findModule("jdk.jfr").isPresent();
System.out.println(!jfr ? "probe passed" : "probe failed: jdk.jfr found");
}
}
@@ -0,0 +1,246 @@
import java.util.ArrayDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Measures what handing a packet to the game's thread costs in the browser build (the lead in ADR
* 0032's "Not done"). The game decodes each packet on the network's thread and calls its handler
* there; the handler's first line ({@code PacketUtils.ensureRunningOnSameThread}) queues the packet
* for the game's thread and throws a shared, stack-less {@code RunningOnDifferentThreadException},
* which {@code Connection.channelRead0} catches. In the page's profiles that function's own time was
* 2.5% of combat's samples, and the profile can't say whether it's the throw or the queueing.
*
* <p>Times, per packet, each part on its own, through three calls as in the game (the handoff's
* check, the packet's {@code handle}, the connection's dispatch), the calls made through
* interfaces with two implementations each so they stay calls: the call path alone; the thread
* check; the queueing (an {@code ArrayDeque}, and a {@code ConcurrentLinkedQueue} as the game's
* {@code PacketProcessor} has); the throw and catch; and all of it, as the game does it. Each also
* through frames compiled as coroutines (most of the game's packet handlers are: a call that could
* suspend, never made); from the stack's bottom and 30 calls up; on the page's main thread, in a
* thread that slept first, and in one that never suspended. Prints the figures and "probe passed".
*
* <p>What it found (2026-10-03, Chrome on the desktop, development and release builds alike): the
* throw and catch is most of the handoff, 65 to 100 ns on the page's main thread, and 640 to
* 860 ns on any other thread, slept or not, against 5 to 15 ns for the calls and 20 to 30 ns for
* either queue. The stack's depth doesn't matter. The game's network runs on another thread, so
* every packet pays the dear throw.
*/
public final class PacketHandoffProbe {
private static final int PACKETS = 50_000;
private static final int ROUNDS = 5;
/** As the game's exception: shared, no stack trace. */
static final class Handoff extends RuntimeException {
static final Handoff INSTANCE = new Handoff();
private Handoff() {
setStackTrace(new StackTraceElement[0]);
}
@Override
public synchronized Throwable fillInStackTrace() {
setStackTrace(new StackTraceElement[0]);
return this;
}
}
record Queued(Object listener, Object packet) {}
/**
* What the handoff does: 0 nothing, 1 check, 2 queue (an ArrayDeque), 3 queue (a
* ConcurrentLinkedQueue, as the game's PacketProcessor), 4 throw, 5 check + queue + throw as the
* game (the concurrent queue).
*/
static int mode;
/** Never true; makes the coroutine variants' methods able to suspend. */
static volatile boolean suspend;
static final ArrayDeque<Queued> QUEUE = new ArrayDeque<>();
static final ConcurrentLinkedQueue<Queued> CONCURRENT = new ConcurrentLinkedQueue<>();
static Thread gameThread;
static volatile long sink;
interface Handler {
void handle(Object packet);
}
interface Dispatch {
void read(Handler handler, Object packet);
}
static void handoff(Object listener, Object packet) {
switch (mode) {
case 1 -> {
if (Thread.currentThread() == gameThread) {
sink++;
}
}
case 2 -> QUEUE.add(new Queued(listener, packet));
case 3 -> CONCURRENT.add(new Queued(listener, packet));
case 4 -> throw Handoff.INSTANCE;
case 5 -> {
if (Thread.currentThread() != gameThread) {
CONCURRENT.add(new Queued(listener, packet));
throw Handoff.INSTANCE;
}
}
default -> {}
}
}
static void maybeSuspend() {
if (suspend) {
Thread.yield();
}
}
static final class PlainHandler implements Handler {
@Override
public void handle(Object packet) {
handoff(this, packet);
sink += packet.hashCode();
}
}
static final class OtherHandler implements Handler {
@Override
public void handle(Object packet) {
sink -= packet.hashCode();
}
}
static final class CoroutineHandler implements Handler {
@Override
public void handle(Object packet) {
maybeSuspend();
handoff(this, packet);
maybeSuspend();
sink += packet.hashCode();
}
}
static final class PlainDispatch implements Dispatch {
@Override
public void read(Handler handler, Object packet) {
try {
handler.handle(packet);
} catch (Handoff e) {
sink++;
}
}
}
static final class OtherDispatch implements Dispatch {
@Override
public void read(Handler handler, Object packet) {
sink--;
}
}
static final class CoroutineDispatch implements Dispatch {
@Override
public void read(Handler handler, Object packet) {
maybeSuspend();
try {
handler.handle(packet);
} catch (Handoff e) {
sink++;
}
maybeSuspend();
}
}
private PacketHandoffProbe() {}
public static void main(String[] args) {
// The game's thread is another: the check fails, as on the network's thread.
gameThread = new Thread(() -> {});
StringBuilder report = new StringBuilder("PacketHandoffProbe, ns a packet (best of " + ROUNDS + "):\n");
// From the stack's bottom, and from deep in it, as the game's network pipeline is.
for (int depth : new int[] {0, 30}) {
report.append(deep(depth, depth));
}
// Depth -1: a thread that slept first; -2: a thread that never suspended.
// And in a thread that has suspended and resumed, as the network's event loop has: it
// waits for each message.
StringBuilder resumed = new StringBuilder();
Thread network = new Thread(() -> {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
resumed.append(measure(-1));
});
network.start();
try {
network.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
report.append(resumed);
// A thread that never suspended, to tell the thread from the suspension.
StringBuilder fresh = new StringBuilder();
Thread plain = new Thread(() -> fresh.append(measure(-2)));
plain.start();
try {
plain.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
report.append(fresh);
System.out.println(report);
System.out.println("probe passed");
}
/** Measures {@code depth} calls down the stack. */
static String deep(int remaining, int depth) {
if (remaining > 0) {
String result = deep(remaining - 1, depth);
sink += result.length();
return result;
}
return measure(depth);
}
static String measure(int depth) {
Object packet = new Object();
Handler[] handlers = {new PlainHandler(), new OtherHandler(), new CoroutineHandler()};
Dispatch[] dispatches = {new PlainDispatch(), new OtherDispatch(), new CoroutineDispatch()};
String[] modes = {"call path only", "thread check", "ArrayDeque add", "concurrent add", "throw and catch", "as the game (all)"};
StringBuilder report = new StringBuilder();
for (int variant = 0; variant < 2; variant++) {
Handler handler = handlers[variant == 0 ? 0 : 2];
Dispatch dispatch = dispatches[variant == 0 ? 0 : 2];
// The other implementations, called once, so neither interface has a single target.
dispatches[1].read(handlers[1], packet);
handlers[1].handle(packet);
for (int m = 0; m < modes.length; m++) {
mode = m;
double best = Double.MAX_VALUE;
for (int round = 0; round < ROUNDS + 1; round++) {
QUEUE.clear();
CONCURRENT.clear();
long start = System.nanoTime();
for (int i = 0; i < PACKETS; i++) {
dispatch.read(handler, packet);
if ((i & 1023) == 0) {
QUEUE.clear();
// As the game's thread drains it each frame.
while (CONCURRENT.poll() != null) {}
}
}
double ns = (System.nanoTime() - start) / (double) PACKETS;
if (round > 0) {
best = Math.min(best, ns);
}
}
report.append(String.format(
" depth %3d %-10s %-18s %8.1f%n",
depth, variant == 0 ? "plain" : "coroutine", modes[m], best));
}
}
return report.toString();
}
}
@@ -0,0 +1,49 @@
# Probes
Small programs compiled alone with TeaVM against the browser build's class library and run in
headless Chromium, in seconds rather than the full build's ten minutes (`app-web/README.md`,
Experiments). Regression probes guard a fix in `tools/teavm-patches`, `tools/webbuild` or
`web-classlib` and print "probe passed". Measurements print the cost an ADR relied on; checks confirm a behaviour the build depends on.
```sh
app-web/probes/run.sh <Name> [Gradle options] # for example -Pteavm.fast, -Pbrowser.gpu=webgpu
```
| Probe | Kind | What it checks |
| --- | --- | --- |
| `ArrayDequeProbe` | Regression | tools/teavm-patches' TArrayDeque fix |
| `ArrayInstanceOfProbe` | Regression | Via's StructuredItemRewriter |
| `ByteCopyProbe` | Measurement | How bytes cross between Java arrays and JavaScript buffers |
| `ChannelClassProbe` | Check | `Bootstrap.channel(Class)` throws for a channel class ReflectionDeclarations doesn't declare |
| `CoroutineCostProbe` | Measurement | What TeaVM's coroutine transformation costs ordinary code (ADR 0036) |
| `DeflateProbe` | Check | The build's deflate and inflate streams, used as the game writes chunks and NBT |
| `DirectAllocationProbe` | Regression | Heap growth (a tools/teavm-patches fix until TeaVM 0.16.0 had it) |
| `EventLoopProbe` | Regression | Netty's event loop and a channel's pipeline setup under TeaVM (its assertions hold; the catalog's Netty must be the game's) |
| `EventLoopHopProbe` | Measurement | How long a task handed to a Netty local event loop waits when the main thread then ends its frame |
| `FetchFailureProbe` | Check | A failed download reported to a suspended coroutine is caught, and the page doesn't crash |
| `FileReadProbe` | Regression | web-classlib's FileInputStreamAdditions, and `RandomAccessFile.read` (fixed in TeaVM 0.16.0) |
| `ImmutableCollectionsProbe` | Regression | tools/teavm-patches' TTemplateCollections hashing (ADR 0034) |
| `InflatePacketProbe` | Measurement | Inflating and deflating packets with a reset in place, against a new zlib stream each (ADR 0075) |
| `InitOrderProbe` | Regression | tools/teavm-patches' ClassInitializerInsertionTransformer fix |
| `InterruptedWaitProbe` | Regression | tools/teavm-patches' TObject fix |
| `JspiProbe` | Check | Java threads behave the same in the Fast build (JSPI) as in the Compatible build |
| `MathProbe` | Check | tools/webbuild's `MathIntrinsics`: `Math.floor`, `ceil` and `sqrt` as WebAssembly instructions |
| `MessageTypeProbe` | Regression | tools/webbuild's TypeCaptures |
| `ModuleProbe` | Regression | web-classlib's `Module` and `ModuleLayer` |
| `PacketHandoffProbe` | Measurement | What handing a packet to the game's thread costs (ADR 0033) |
| `ReloadLeakProbe` | Check | Memory held across page reloads in one tab (read with a CDP script) |
| `SharableProbe` | Regression | tools/webbuild's RemovalTransformer |
| `SocketDeliveryProbe` | Measurement | What handing one WebSocket message from the page's queue to Java costs |
| `StorageProbe` | Regression | platform-web's file system (ADR 0011) under TeaVM's own java.io and java.nio.file |
| `SuppressedProbe` | Regression | Suppressed exceptions (a tools/teavm-patches fix until TeaVM 0.16.0 had it) |
| `SuspendingReflectionProbe` | Regression | tools/teavm-patches' CoroutineTransformation fix for non-nullable locals |
| `SuspendingTernaryProbe` | Regression | A suspending `c ? a : b` (a tools/teavm-patches fix until TeaVM 0.16.0 had it) |
| `ThreadLocalProbe` | Check | web-classlib's `ThreadLocal` across thread switches |
| `ThrowCensusProbe` | Check | The throw census, `-Pteavm.throwCensus` (ADR 0033) |
| `ViaPipelineUtilProbe` | Regression | web-classlib's substitute for Via's `PipelineUtil` |
| `ViaTypeTokenProbe` | Regression | TypeCaptures' entry for Via's bundled Gson |
| `WaitRoutingProbe` | Regression | tools/webbuild's MonitorElision routing every `Object.wait` through web-classlib's `Waits` |
| `WeakQueueProbe` | Check | References polled from a ReferenceQueue keep their own class's methods |
| `WebGpuCallProbe` | Measurement | What one WebGPU call costs from Java (`docs/webgpu-backend.md`) |
| `WrapIntProbe` | Check | `int`s reach JavaScript as the same Numbers (tools/webbuild's `JsoIntrinsics`) |
| `ZipFileProbe` | Regression | tools/teavm-patches' TZipFile fix |
@@ -0,0 +1,39 @@
/**
* Holds 50 MB and parks a thread on a monitor for good, then prints "probe ready". Loaded several
* times in one tab (tools: a CDP script reloading it and reading the heap after a collection), it
* shows whether a reloaded page's module, its objects and its suspended threads are freed. With
* the Fast build (JSPI, {@code -Pteavm.fast}) a thread parked forever is a suspended engine stack.
*
* <p>What it found (2026-10-05, Chromium 151 and 153): the coroutine build's heap stayed under
* 2 MB over five loads (its parked thread holds nothing the engine sees), the JSPI build's grew
* 50 MB a load: V8 never frees a suspended stack, so every earlier page stayed whole. Ending the
* fibers on {@code pagehide} (jspi.ts) keeps it at the one live page's 51 MB.
*/
public final class ReloadLeakProbe {
static final Object LOCK = new Object();
static byte[][] held;
public static void main(String[] args) throws InterruptedException {
held = new byte[50][];
for (int i = 0; i < held.length; i++) {
held[i] = new byte[1 << 20];
held[i][i] = (byte) i;
}
Thread parked = new Thread(() -> {
synchronized (LOCK) {
while (true) {
try {
LOCK.wait();
} catch (InterruptedException e) {
return;
}
}
}
}, "parked");
parked.setDaemon(true);
parked.start();
Thread.sleep(50);
System.out.println("probe ready " + held[7][7]);
}
}
@@ -0,0 +1,28 @@
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Regression probe for tools/webbuild's RemovalTransformer: Netty's {@code @Sharable} check
* reads the annotation at run time, through a class TeaVM generates for it
* ({@code ChannelHandler$Sharable$$_impl}). The removal step took that class for a missing one,
* since it doesn't exist until after transformers run, and replaced it with a throwing reference
* under the catch-all Netty rule: adding any handler to a pipeline threw. Prints "probe passed"
* when a sharable handler reads as sharable and another doesn't.
*/
public final class SharableProbe {
@ChannelHandler.Sharable
static final class Shared extends ChannelInboundHandlerAdapter {}
static final class NotShared extends ChannelInboundHandlerAdapter {}
private SharableProbe() {}
public static void main(String[] args) {
ChannelHandlerAdapter shared = new Shared();
ChannelHandlerAdapter notShared = new NotShared();
boolean passed = shared.isSharable() && !notShared.isSharable();
System.out.println(passed ? "probe passed" : "probe failed: " + shared.isSharable() + ", " + notShared.isSharable());
}
}
@@ -0,0 +1,136 @@
import java.nio.ByteBuffer;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Measures what delivering one WebSocket message from the page's queue to Java costs in the
* WebAssembly GC build (platform-web's {@code WebSocketNetwork}), for a server's mix of packet
* sizes: the route as it was (each entry's type read as a string, its time, its buffer wrapped in a
* new Int8Array, then copied) against an entry's type as a number and the copy made from a view the
* page built when the message came. Prints microseconds per message and "probe passed" when all
* routes read the same bytes.
*/
public final class SocketDeliveryProbe {
private SocketDeliveryProbe() {}
public static void main(String[] args) {
int messages = 20_000;
JSObject queue = fill(messages);
long expected = 0;
for (int round = 0; round < 3; round++) {
expected = asBefore(queue, messages);
numbered(queue, messages);
}
int rounds = 10;
double start = now();
long before = 0;
for (int i = 0; i < rounds; i++) {
before = asBefore(queue, messages);
}
double beforeMicros = (now() - start) * 1000 / rounds / messages;
start = now();
long after = 0;
for (int i = 0; i < rounds; i++) {
after = numbered(queue, messages);
}
double afterMicros = (now() - start) * 1000 / rounds / messages;
start = now();
long copyOnly = 0;
for (int i = 0; i < rounds; i++) {
copyOnly = copyOnly(queue, messages);
}
double copyMicros = (now() - start) * 1000 / rounds / messages;
System.out.println("SocketDeliveryProbe: per message (mean " + meanSize(queue, messages) + " B): as before "
+ beforeMicros + " us, numbered types and kept views " + afterMicros + " us, the copy alone "
+ copyMicros + " us");
boolean same = expected == before && before == after && after == copyOnly;
System.out.println(same ? "probe passed" : "probe failed: the routes read different bytes");
}
private static long asBefore(JSObject queue, int count) {
long sum = 0;
double now = now();
double longest = 0;
for (int i = 0; i < count; i++) {
longest = Math.max(longest, now - queuedTime(queue, i));
switch (queuedType(queue, i)) {
case "message" -> {
byte[] message = new Int8Array(queuedData(queue, i)).copyToJavaArray();
sum += checksum(ByteBuffer.wrap(message));
}
default -> {}
}
}
return sum + (longest < 0 ? 1 : 0);
}
private static long numbered(JSObject queue, int count) {
long sum = 0;
double now = now();
double longest = 0;
for (int i = 0; i < count; i++) {
longest = Math.max(longest, now - queuedTime(queue, i));
if (kind(queue, i) == 1) {
byte[] message = view(queue, i).copyToJavaArray();
sum += checksum(ByteBuffer.wrap(message));
}
}
return sum + (longest < 0 ? 1 : 0);
}
private static long copyOnly(JSObject queue, int count) {
long sum = 0;
for (int i = 0; i < count; i++) {
byte[] message = view(queue, i).copyToJavaArray();
sum += checksum(ByteBuffer.wrap(message));
}
return sum;
}
private static long checksum(ByteBuffer buffer) {
int n = buffer.remaining();
return n == 0 ? 0 : n * 31L + buffer.get(0) + buffer.get(n - 1);
}
private static int meanSize(JSObject queue, int count) {
long total = 0;
for (int i = 0; i < count; i++) {
total += view(queue, i).getLength();
}
return (int) (total / count);
}
// A server's mix: mostly small (movement, entity motion), some medium, a few chunks.
@JSBody(
params = "count",
script = "var q = [], t = [], n = [], v = []; var seed = 26;"
+ "function rnd() { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; }"
+ "for (var i = 0; i < count; i++) { var r = rnd();"
+ " var size = r < 0.8 ? 8 + (rnd() * 40 | 0) : r < 0.97 ? 100 + (rnd() * 900 | 0) : 4000 + (rnd() * 20000 | 0);"
+ " var b = new ArrayBuffer(size); var a = new Int8Array(b);"
+ " for (var j = 0; j < size; j += 7) a[j] = (i + j) & 127;"
+ " q.push(['message', b]); t.push(performance.now()); n.push(1); v.push(a); }"
+ "return {q: q, t: t, n: n, v: v};")
private static native JSObject fill(int count);
@JSBody(params = {"s", "i"}, script = "return s.q[i][0];")
private static native String queuedType(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.q[i][1];")
private static native ArrayBuffer queuedData(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.t[i];")
private static native double queuedTime(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.n[i];")
private static native int kind(JSObject s, int i);
@JSBody(params = {"s", "i"}, script = "return s.v[i];")
private static native Int8Array view(JSObject s, int i);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,94 @@
import incari.platform.web.storage.WebFileSystem;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Stream;
/**
* Regression probe for platform-web's file system (ADR 0011) under TeaVM's own java.io and
* java.nio.file: installs it, as WebMain does, and uses files the ways the game does (directories
* made with Files.createDirectories, the server list's temporary file and rename, a channel opened
* with CREATE, RandomAccessFile keeping its bytes, listing and walking), then flushes to the
* storage worker. Run it twice: the second run also finds what the first stored. Prints
* "probe passed" when everything reads back as written.
*/
public final class StorageProbe {
private StorageProbe() {}
public static void main(String[] args) throws IOException {
WebFileSystem files = WebFileSystem.install(List.of("/incari/dropped"));
StringBuilder problems = new StringBuilder();
Path game = Path.of("/incari/game");
Path marker = game.resolve("probe-runs.txt");
int runs = Files.exists(marker) ? Integer.parseInt(Files.readString(marker).trim()) : 0;
System.out.println("[probe] earlier runs stored: " + runs + " (backend " + files.backend() + ")");
Path downloads = game.resolve("downloads");
Files.createDirectories(downloads);
if (!Files.isDirectory(downloads) || Files.exists(Path.of("/incari/game/incari"))) {
problems.append(" createDirectories");
}
try (FileChannel log = FileChannel.open(
downloads.resolve("log.json"), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
log.write(ByteBuffer.wrap("{}\n".getBytes(StandardCharsets.UTF_8)));
}
// ServerList.save: a temporary file, then Util.safeReplaceFile's renames.
Path temporary = Files.createTempFile(game, "servers", ".dat");
Files.write(temporary, new byte[] {0x0A, (byte) 0xC8, (byte) 0xFF, 0});
Path servers = game.resolve("servers.dat");
if (Files.exists(servers)) {
Files.move(servers, game.resolve("servers.dat_old"), StandardCopyOption.REPLACE_EXISTING);
}
Files.move(temporary, servers, StandardCopyOption.REPLACE_EXISTING);
try (InputStream in = Files.newInputStream(servers);
DataInputStream data = new DataInputStream(in)) {
if (data.readUnsignedByte() != 0x0A || data.readUnsignedShort() != 0xC8FF) {
problems.append(" servers.dat");
}
}
File region = game.resolve("r.0.0.mca").toFile();
// TeaVM's RandomAccessFile doesn't create a missing file in "rw" mode, as the JDK's does;
// the game opens its region files through FileChannel, which does (web-classlib).
region.createNewFile();
try (RandomAccessFile raf = new RandomAccessFile(region, "rw")) {
raf.write("0123456789".getBytes(StandardCharsets.US_ASCII));
}
try (RandomAccessFile raf = new RandomAccessFile(region, "rw")) {
raf.seek(4);
raf.write('x');
}
if (!Files.readString(region.toPath()).equals("0123x56789")) {
problems.append(" random access: ").append(Files.readString(region.toPath()));
}
Files.writeString(game.resolve("options.txt"), "fov:1.0\n");
try (Stream<Path> walk = Files.walk(game)) {
long count = walk.count();
if (count < 6) {
problems.append(" walk ").append(count);
}
}
if (!new File("/incari/classpath").exists() && new File("/tmp").isDirectory()) {
// Nothing mounted in a probe; /tmp is there.
} else if (!new File("/tmp").isDirectory()) {
problems.append(" /tmp");
}
Files.writeString(marker, Integer.toString(runs + 1));
files.flush();
System.out.println(problems.isEmpty() ? "probe passed" : "probe failed:" + problems);
}
}
@@ -0,0 +1,20 @@
/**
* Regression probe for tools/teavm-patches' TThrowable fix: {@code getSuppressed} and
* {@code addSuppressed} on a fresh exception. TeaVM's class library left the suppressed array
* null, so both threw NullPointerException; Netty's {@code DefaultPromise.syncUninterruptibly}
* calls {@code getSuppressed} on every failure it rethrows, which hid why a connection failed.
* Prints "probe passed" when an exception starts with none and keeps the one added.
*/
public final class SuppressedProbe {
private SuppressedProbe() {}
public static void main(String[] args) {
RuntimeException failure = new RuntimeException("failure");
int before = failure.getSuppressed().length;
failure.addSuppressed(new IllegalStateException("suppressed"));
Throwable[] after = failure.getSuppressed();
boolean passed = before == 0 && after.length == 1 && after[0].getMessage().equals("suppressed");
System.out.println(passed ? "probe passed" : "probe failed: " + before + ", " + after.length);
}
}
@@ -0,0 +1,74 @@
import io.netty.util.ReferenceCounted;
import java.lang.reflect.Method;
/**
* Regression probe for tools/teavm-patches' CoroutineTransformation fix for non-nullable locals
*: a method called through reflection that takes two or more arguments and suspends. TeaVM
* generates a caller for it that keeps the argument array's data in a non-nullable local, and the
* coroutine transformation's save and restore code read that local where WebAssembly doesn't count
* it as set: the module failed to validate ("uninitialized local").
*
* <p>The method is the one that showed it, Netty's {@code ReferenceCountUtil.touch(Object, Object)},
* which the browser build's reflection policy (tools/webbuild ReflectionDeclarations) already
* declares. It calls {@link ReferenceCounted#touch(Object)}, which suspends here, as it can in the
* game's build, so its reflection caller is a coroutine. Prints "probe passed" when the call
* reaches the object and returns it.
*/
public final class SuspendingReflectionProbe {
/** A reference-counted object whose {@code touch} suspends. */
static final class Touched implements ReferenceCounted {
String hint = "";
@Override
public ReferenceCounted touch(Object hint) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
this.hint = String.valueOf(hint);
return this;
}
@Override
public ReferenceCounted touch() {
return touch(null);
}
@Override
public int refCnt() {
return 1;
}
@Override
public ReferenceCounted retain() {
return this;
}
@Override
public ReferenceCounted retain(int increment) {
return this;
}
@Override
public boolean release() {
return false;
}
@Override
public boolean release(int decrement) {
return false;
}
}
private SuspendingReflectionProbe() {}
public static void main(String[] args) throws ReflectiveOperationException {
Method touch = Class.forName("io.netty.util.ReferenceCountUtil").getMethod("touch", Object.class, Object.class);
Touched message = new Touched();
Object result = touch.invoke(null, message, "hint");
boolean passed = result == message && message.hint.equals("hint");
System.out.println(passed ? "probe passed" : "probe failed: " + result + ", hint " + message.hint);
}
}
@@ -0,0 +1,126 @@
import java.util.ArrayList;
import java.util.List;
/**
* Regression probe for tools/teavm-patches' CoroutineTransformation fix: a conditional
* expression whose one branch suspends, left on the operand stack as an argument of a call that
* suspends too. The two branches build different subclasses of the declared result type, the else
* branch's being the narrower one. Before the fix, the coroutine transformation typed the restore
* block after the conditional with the else branch's class, and the module failed to validate
* ("type error in branch"): the shape of the game's {@code Connection.configureSerialization}
* with Netty's pipeline. Prints "probe passed" when the handlers arrive in order.
*/
public final class SuspendingTernaryProbe {
interface Handler {
String id();
}
abstract static class Base implements Handler {}
static class Wide extends Base {
@Override
public String id() {
return "wide";
}
}
static final class Narrow extends Wide {
@Override
public String id() {
return "narrow";
}
}
/** A handler whose constructor suspends, so the conditional that makes it does too. */
static final class Suspending extends Base {
private final int value;
Suspending(int value) {
this.value = value;
pause();
}
@Override
public String id() {
return "suspending" + value;
}
}
/** An interface call that suspends, with the conditional's value among its arguments. */
interface Pipeline {
Pipeline add(String name, Handler handler);
Pipeline add(Handler... handlers);
}
static final class ListPipeline implements Pipeline {
final List<String> names = new ArrayList<>();
@Override
public Pipeline add(String name, Handler handler) {
pause();
names.add(name + "=" + handler.id());
return this;
}
@Override
public Pipeline add(Handler... handlers) {
for (Handler handler : handlers) {
add("anonymous", handler);
}
return this;
}
}
enum Flow {
IN,
OUT;
Flow opposite() {
return this == IN ? OUT : IN;
}
}
private static final Integer INITIAL = 7;
private SuspendingTernaryProbe() {}
private static void pause() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
private static String name(boolean configure) {
return configure ? "configured" : "unconfigured";
}
private static Handler framing(boolean local) {
return local ? new Wide() : new Narrow();
}
static void configure(Pipeline pipeline, Flow inbound, boolean local) {
Flow outbound = inbound.opposite();
boolean configureInbound = inbound == Flow.OUT;
boolean configureOutbound = outbound == Flow.OUT;
pipeline.add("splitter", framing(local))
.add(new Wide())
.add(name(configureInbound), configureInbound ? new Suspending(INITIAL) : new Narrow())
.add("prepender", framing(local))
.add(name(configureOutbound), configureOutbound ? new Suspending(INITIAL) : new Narrow());
}
public static void main(String[] args) {
ListPipeline pipeline = new ListPipeline();
configure(pipeline, Flow.IN, false);
configure(pipeline, Flow.OUT, true);
String expected = "[splitter=narrow, anonymous=wide, unconfigured=narrow, prepender=narrow,"
+ " configured=suspending7, splitter=wide, anonymous=wide, configured=suspending7,"
+ " prepender=wide, unconfigured=narrow]";
String actual = pipeline.names.toString();
System.out.println(actual.equals(expected) ? "probe passed" : "probe failed: " + actual);
}
}
@@ -0,0 +1,53 @@
/**
* web-classlib's {@code ThreadLocal} in the browser: four threads take turns through sleeps (each
* wait switches threads, so each thread-local's remembered last thread keeps changing), each
* setting and reading its own value, with {@code withInitial}'s value per thread and after
* {@code remove}. Prints "probe passed". Run it in both builds.
*/
public final class ThreadLocalProbe {
private static final ThreadLocal<String> NAME = new ThreadLocal<>();
private static final ThreadLocal<int[]> COUNTER = ThreadLocal.withInitial(() -> new int[1]);
static volatile String failure;
private ThreadLocalProbe() {}
static void check(boolean condition, String what) {
if (!condition && failure == null) {
failure = what;
}
}
public static void main(String[] args) throws InterruptedException {
NAME.set("main");
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
String name = "worker-" + i;
threads[i] = new Thread(() -> {
check(NAME.get() == null, name + " saw another thread's value");
NAME.set(name);
for (int n = 0; n < 50; n++) {
COUNTER.get()[0]++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
check(name.equals(NAME.get()), name + " read " + NAME.get() + " after a switch");
}
check(COUNTER.get()[0] == 50, name + " counted " + COUNTER.get()[0]);
NAME.remove();
check(NAME.get() == null, name + " still had a value after remove");
}, name);
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
check("main".equals(NAME.get()), "main read " + NAME.get());
check(COUNTER.get()[0] == 0, "main's counter was " + COUNTER.get()[0]);
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
}
@@ -0,0 +1,49 @@
/**
* Checks the throw census (`-Pteavm.throwCensus`, ADR 0033): throws a known number of times on the
* main thread and on another, across one census report, then prints "probe passed". Run with the
* census on and read the "[Incari] Throws" lines: the main thread's site counts 1000 on it, the
* other thread's 3000 off it.
*/
public final class ThrowCensusProbe {
static int caught;
private ThrowCensusProbe() {}
static void fail(int i) {
throw new IllegalStateException("throw " + i);
}
static void failElsewhere(int i) {
throw new UnsupportedOperationException("throw " + i);
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
try {
fail(i);
} catch (IllegalStateException e) {
caught++;
}
}
Thread other = new Thread(() -> {
for (int i = 0; i < 3000; i++) {
try {
failElsewhere(i);
} catch (UnsupportedOperationException e) {
caught++;
}
}
});
other.start();
other.join();
// The census reports at the first throw ten seconds after its first.
Thread.sleep(10_500);
try {
fail(-1);
} catch (IllegalStateException e) {
caught++;
}
System.out.println(caught == 4001 ? "probe passed" : "probe failed: caught " + caught);
}
}
@@ -0,0 +1,29 @@
import com.viaversion.viaversion.util.PipelineUtil;
/**
* Regression probe for web-classlib's substitute for Via's {@code PipelineUtil}: Via's own
* looks up Netty's codec methods reflectively when it loads, which the browser can't do, so the
* class failed to initialize, and Via's checks for a cancelled packet ({@code containsCause})
* failed with it: the first packet Via dropped on purpose (the game's Login Acknowledged, for a
* 1.8 server) ended the connection. Prints "probe passed" when a cause is found inside a wrapper.
*/
public final class ViaPipelineUtilProbe {
private ViaPipelineUtilProbe() {}
public static void main(String[] args) {
Thread thread = new Thread(ViaPipelineUtilProbe::run, "probe");
thread.start();
}
private static void run() {
try {
// Via's own cancel exceptions need a running Via; any cause shows the class loads.
RuntimeException wrapped = new RuntimeException(new java.io.IOException("cancelled"));
boolean found = PipelineUtil.containsCause(wrapped, java.io.IOException.class);
System.out.println(found ? "probe passed" : "probe failed: the cancel wasn't found");
} catch (Throwable t) {
System.out.println("probe failed: " + t);
}
}
}
@@ -0,0 +1,34 @@
import com.viaversion.viaversion.libs.gson.Gson;
import com.viaversion.viaversion.libs.gson.reflect.TypeToken;
import java.util.Map;
/**
* Regression probe for TypeCaptures' entry for Via's bundled Gson: Via reads its 1.12-to-
* 1.13 block ids as {@code Map<String, String[]>} through an anonymous {@code TypeToken}, which
* reads its type argument from its generic superclass. TeaVM keeps no generic signatures unless
* TypeCaptures records them; without the entry, Via's 1.13 data failed to load and no server older
* than 1.13 could be joined. Prints "probe passed" when the map's values come back as arrays.
*/
public final class ViaTypeTokenProbe {
private ViaTypeTokenProbe() {}
public static void main(String[] args) {
Thread thread = new Thread(ViaTypeTokenProbe::run, "probe");
thread.start();
}
private static void run() {
try {
Map<String, String[]> map = new Gson()
.fromJson("{\"stone\": [\"minecraft:stone\", \"minecraft:granite\"]}",
new TypeToken<Map<String, String[]>>() {}.getType());
String[] ids = map.get("stone");
System.out.println(ids != null && ids.length == 2 && ids[1].equals("minecraft:granite")
? "probe passed"
: "probe failed: " + map);
} catch (Throwable t) {
System.out.println("probe failed: " + t);
}
}
}
@@ -0,0 +1,48 @@
/**
* Regression probe for tools/webbuild's MonitorElision routing every {@code Object.wait} through
* web-classlib's {@code Waits}, which times the render thread's waits: plain, timed and
* nanosecond waits still wait, wake on a notify from another thread, and time out; a join and a
* CompletableFuture's join (which wait underneath) still return. The first build that routed waits
* also routed Object's own wait(long) call to wait(long, int), which recursed until the stack ran
* out at start. Prints "probe passed".
*/
public final class WaitRoutingProbe {
private static final Object LOCK = new Object();
private static boolean ready;
private WaitRoutingProbe() {}
public static void main(String[] args) throws Exception {
// A timed wait that times out.
long start = System.currentTimeMillis();
synchronized (LOCK) {
LOCK.wait(30);
LOCK.wait(5, 500);
}
long waited = System.currentTimeMillis() - start;
// A wait that another thread's notify ends.
Thread notifier = new Thread(() -> {
synchronized (LOCK) {
ready = true;
LOCK.notifyAll();
}
});
notifier.start();
synchronized (LOCK) {
while (!ready) {
LOCK.wait();
}
}
notifier.join();
// A future completed on another thread, joined here.
java.util.concurrent.CompletableFuture<String> future = new java.util.concurrent.CompletableFuture<>();
new Thread(() -> future.complete("done")).start();
String joined = future.join();
if (waited >= 30 && ready && joined.equals("done")) {
System.out.println("probe passed");
} else {
System.out.println("probe failed: waited " + waited + " ms, ready " + ready + ", joined " + joined);
}
}
}
@@ -0,0 +1,58 @@
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
/**
* References polled from a ReferenceQueue keep their own class's methods. TeaVM's analysis took
* everything poll() returns for a plain WeakReference, so a method only ever called on polled
* references (Guava's WeakValueReference.getEntry, when a weak-value map reclaims an entry) had
* no code in the subclass, and the call trapped ("dereferencing a null pointer"). Makes garbage
* until the browser collects some referents and the queue hands their references back.
*/
public class WeakQueueProbe {
/** Called through an interface, as Guava calls WeakValueReference.getEntry(). */
interface HasTag {
int tag();
}
static class Tagged extends WeakReference<Object> implements HasTag {
private final int tag;
Tagged(Object referent, ReferenceQueue<Object> queue, int tag) {
super(referent, queue);
this.tag = tag;
}
/** Called only on references that came back from the queue. */
@Override
public int tag() {
return tag;
}
}
public static void main(String[] args) throws Exception {
ReferenceQueue<Object> queue = new ReferenceQueue<>();
Tagged[] kept = new Tagged[20_000];
for (int i = 0; i < kept.length; i++) {
kept[i] = new Tagged(new int[64], queue, i + 1);
}
long sum = 0;
int polled = 0;
Object[] churn = new Object[1024];
for (int round = 0; round < 400 && polled == 0; round++) {
for (int i = 0; i < 200_000; i++) {
churn[i & 1023] = new int[32];
}
// Lets the page's event loop run, where the finalization callbacks come.
Thread.sleep(20);
Reference<?> reference;
while ((reference = queue.poll()) != null) {
sum += ((HasTag) reference).tag();
polled++;
}
}
System.out.println("polled " + polled + " references, tags summing to " + sum);
System.out.println(polled > 0 && sum > 0 ? "probe passed" : "probe failed: nothing came back from the queue");
}
}
@@ -0,0 +1,303 @@
import org.teavm.interop.Async;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.JSProperty;
import org.teavm.jso.typedarrays.Int32Array;
import org.teavm.jso.typedarrays.Uint32Array;
import org.teavm.jso.webgl.WebGL2RenderingContext;
import org.teavm.jso.webgl.WebGLUniformLocation;
import org.teavm.jso.webgpu.GPUBindGroup;
import org.teavm.jso.webgpu.GPUDevice;
import org.teavm.jso.webgpu.GPURenderPassEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
/**
* What one WebGPU call costs from Java (docs/webgpu-backend.md, the W0 spike's open question):
* the same frame of draws, each with its own uniform (a dynamic offset), encoded five ways and timed
* on the CPU. Through TeaVM's JSO, a call per command, as a Java backend would; in one JavaScript
* loop, the floor any language could reach; Java writing commands into linear memory and one
* JavaScript call replaying them, the TypeScript layer a backend could fall back on; a render bundle
* recorded once; and WebGL2's uniform and draw per object through JSO, as {@code render-webgl2}
* draws what it doesn't multi-draw. Needs a WebGPU adapter: {@code app-web/probes/run.sh
* WebGpuCallProbe -Pbrowser.gpu=webgpu} (Linux Chrome gives WebGPU only on Vulkan). Prints
* microseconds a draw and "probe passed".
*/
public final class WebGpuCallProbe {
private static final int DRAWS = 2000;
private static final int WARMUP_FRAMES = 20;
private static final int FRAMES = 100;
/** Command codes for the replay route: one int code, then its arguments. */
private static final int SET_BIND_GROUP = 1;
private static final int DRAW_INDEXED = 2;
private WebGpuCallProbe() {}
/**
* TeaVM's render pass, plus the dynamic-offset overload that takes a range of the offsets array,
* which TeaVM's binding lacks: without it each draw would allocate a subarray.
*/
interface Pass extends GPURenderPassEncoder {
void setBindGroup(int index, GPUBindGroup group, Uint32Array offsets, int start, int length);
}
/** What {@link #setUp} made: the pipeline, buffers, bind group and target, and a recorded bundle. */
interface Scene extends JSObject {
@JSProperty
GPUBindGroup bindGroup();
@JSProperty
Uint32Array offsets();
@JSProperty
WebGL2RenderingContext gl();
@JSProperty
WebGLUniformLocation glOffset();
}
@JSFunctor
interface Done extends JSObject {
void done(JSObject value);
}
public static void main(String[] args) {
GPUDevice device = (GPUDevice) requestDevice();
if (device == null) {
System.out.println("probe failed: no WebGPU adapter (" + adapterNote() + ")");
return;
}
System.out.println("WebGpuCallProbe: adapter " + adapterNote() + ", " + DRAWS + " draws a frame, "
+ FRAMES + " frames");
Scene scene = setUp(device, DRAWS);
IntBuffer commands = ByteBuffer.allocateDirect(DRAWS * 8 * 4).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
// An Int32Array over the same linear memory, made once: the replay reads it in place.
Int32Array commandView = Int32Array.fromJavaBuffer(commands);
String[] names = {"JSO, a call per command", "one JavaScript loop", "replayed from linear memory",
"render bundle", "WebGL2 through JSO"};
double[] totals = new double[names.length];
for (int frame = 0; frame < WARMUP_FRAMES + FRAMES; frame++) {
for (int route = 0; route < names.length; route++) {
double start = now();
switch (route) {
case 0 -> {
Pass pass = beginPass(device, scene);
GPUBindGroup group = scene.bindGroup();
Uint32Array offsets = scene.offsets();
for (int i = 0; i < DRAWS; i++) {
pass.setBindGroup(0, group, offsets, i, 1);
pass.drawIndexed(3, 1, 0, 0, 0);
}
endPass(device, scene);
}
case 1 -> {
Pass pass = beginPass(device, scene);
drawAllInJs(pass, scene, DRAWS);
endPass(device, scene);
}
case 2 -> {
Pass pass = beginPass(device, scene);
commands.clear();
for (int i = 0; i < DRAWS; i++) {
commands.put(SET_BIND_GROUP).put(i);
commands.put(DRAW_INDEXED).put(3).put(0).put(0);
}
replay(pass, scene, commandView, commands.position());
endPass(device, scene);
}
case 3 -> {
Pass pass = beginPass(device, scene);
executeBundle(pass, scene);
endPass(device, scene);
}
default -> {
WebGL2RenderingContext gl = scene.gl();
WebGLUniformLocation offset = scene.glOffset();
prepareGl(scene);
for (int i = 0; i < DRAWS; i++) {
gl.uniform4f(offset, (i % 50) * 0.04f - 1, (i / 50) * 0.04f - 1, 0, 0);
gl.drawElements(WebGL2RenderingContext.TRIANGLES, 3, WebGL2RenderingContext.UNSIGNED_SHORT, 0);
}
gl.flush();
}
}
double elapsed = now() - start;
if (frame >= WARMUP_FRAMES) {
totals[route] += elapsed;
}
// Untimed: let the GPU catch up, so the next frame's calls don't wait on a full queue.
if (route == names.length - 1) {
glFinish(scene);
} else {
workDone(device);
}
}
}
for (int route = 0; route < names.length; route++) {
double frameMillis = totals[route] / FRAMES;
System.out.println(String.format(" %-28s %7.3f ms a frame, %6.3f us a draw", names[route], frameMillis,
frameMillis * 1000 / DRAWS));
}
String error = takeError(scene);
System.out.println(error == null ? "probe passed" : "probe failed: " + error);
}
@Async
private static native JSObject requestDevice();
private static void requestDevice(org.teavm.interop.AsyncCallback<JSObject> callback) {
requestDevice(value -> callback.complete(value));
}
@JSBody(
params = "done",
script = "if (!navigator.gpu) { done(null); return; }"
+ "navigator.gpu.requestAdapter().then(function(a) {"
+ " if (!a) return null;"
+ " globalThis.probeAdapter = a.info.vendor + '/' + a.info.architecture"
+ " + (a.info.isFallbackAdapter ? ' (fallback)' : '');"
+ " return a.requestDevice();"
+ "}).then(function(d) { done(d || null); }, function() { done(null); });")
private static native void requestDevice(Done done);
@JSBody(script = "return globalThis.probeAdapter || (navigator.gpu ? 'none' : 'no navigator.gpu');")
private static native String adapterNote();
@Async
private static native JSObject workDone(GPUDevice device);
private static void workDone(GPUDevice device, org.teavm.interop.AsyncCallback<JSObject> callback) {
workDone(device, value -> callback.complete(value));
}
@JSBody(
params = {"device", "done"},
script = "device.queue.onSubmittedWorkDone().then(function() { done(null); });")
private static native void workDone(GPUDevice device, Done done);
/**
* A pipeline drawing one small triangle per draw, moved by a uniform read at a dynamic offset
* (256 bytes apart, WebGPU's minimum); a 256x256 target; the same draws recorded as a bundle;
* and a WebGL2 program doing the same on an OffscreenCanvas.
*/
@JSBody(
params = {"device", "draws"},
script = "var s = {};"
+ "var code = 'struct U { offset: vec4f };'"
+ " + '@group(0) @binding(0) var<uniform> u: U;'"
+ " + '@vertex fn vs(@location(0) p: vec2f) -> @builtin(position) vec4f {'"
+ " + ' return vec4f(p * 0.02 + u.offset.xy, 0.0, 1.0); }'"
+ " + '@fragment fn fs() -> @location(0) vec4f { return vec4f(1.0, 0.5, 0.0, 1.0); }';"
+ "device.pushErrorScope('validation');"
+ "var module = device.createShaderModule({ code: code });"
+ "var layout = device.createBindGroupLayout({ entries: [{ binding: 0,"
+ " visibility: GPUShaderStage.VERTEX, buffer: { type: 'uniform', hasDynamicOffset: true } }] });"
+ "s.pipeline = device.createRenderPipeline({"
+ " layout: device.createPipelineLayout({ bindGroupLayouts: [layout] }),"
+ " vertex: { module: module, entryPoint: 'vs', buffers: [{ arrayStride: 8,"
+ " attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }] },"
+ " fragment: { module: module, entryPoint: 'fs', targets: [{ format: 'rgba8unorm' }] },"
+ " primitive: { topology: 'triangle-list' } });"
+ "var uniforms = new Float32Array(draws * 64);"
+ "for (var i = 0; i < draws; i++) {"
+ " uniforms[i * 64] = (i % 50) * 0.04 - 1; uniforms[i * 64 + 1] = Math.floor(i / 50) * 0.04 - 1; }"
+ "var ubuf = device.createBuffer({ size: uniforms.byteLength,"
+ " usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });"
+ "device.queue.writeBuffer(ubuf, 0, uniforms);"
+ "s.bindGroup = device.createBindGroup({ layout: layout,"
+ " entries: [{ binding: 0, resource: { buffer: ubuf, size: 16 } }] });"
+ "s.offsets = new Uint32Array(draws);"
+ "for (var i = 0; i < draws; i++) s.offsets[i] = i * 256;"
+ "s.vbuf = device.createBuffer({ size: 24, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });"
+ "device.queue.writeBuffer(s.vbuf, 0, new Float32Array([0, 0, 1, 0, 0, 1]));"
+ "s.ibuf = device.createBuffer({ size: 8, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });"
+ "device.queue.writeBuffer(s.ibuf, 0, new Uint16Array([0, 1, 2, 0]));"
+ "s.view = device.createTexture({ size: [256, 256], format: 'rgba8unorm',"
+ " usage: GPUTextureUsage.RENDER_ATTACHMENT }).createView();"
+ "var b = device.createRenderBundleEncoder({ colorFormats: ['rgba8unorm'] });"
+ "b.setPipeline(s.pipeline); b.setVertexBuffer(0, s.vbuf); b.setIndexBuffer(s.ibuf, 'uint16');"
+ "for (var i = 0; i < draws; i++) { b.setBindGroup(0, s.bindGroup, s.offsets, i, 1);"
+ " b.drawIndexed(3, 1, 0, 0, 0); }"
+ "s.bundle = b.finish();"
+ "device.popErrorScope().then(function(e) { if (e) s.error = e.message; });"
+ "device.onuncapturederror = function(e) { s.error = s.error || e.error.message; };"
+ "var gl = new OffscreenCanvas(256, 256).getContext('webgl2');"
+ "function shader(type, src) { var sh = gl.createShader(type); gl.shaderSource(sh, src);"
+ " gl.compileShader(sh); return sh; }"
+ "var p = gl.createProgram();"
+ "gl.attachShader(p, shader(gl.VERTEX_SHADER, '#version 300 es\\nin vec2 p; uniform vec4 offset;'"
+ " + ' void main() { gl_Position = vec4(p * 0.02 + offset.xy, 0.0, 1.0); }'));"
+ "gl.attachShader(p, shader(gl.FRAGMENT_SHADER, '#version 300 es\\nprecision mediump float;'"
+ " + ' out vec4 c; void main() { c = vec4(1.0, 0.5, 0.0, 1.0); }'));"
+ "gl.bindAttribLocation(p, 0, 'p'); gl.linkProgram(p);"
+ "if (!gl.getProgramParameter(p, gl.LINK_STATUS)) s.error = 'WebGL2 link: ' + gl.getProgramInfoLog(p);"
+ "s.glProgram = p; s.glOffset = gl.getUniformLocation(p, 'offset');"
+ "var vao = gl.createVertexArray(); gl.bindVertexArray(vao);"
+ "var vb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vb);"
+ "gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1]), gl.STATIC_DRAW);"
+ "gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);"
+ "var ib = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib);"
+ "gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 0]), gl.STATIC_DRAW);"
+ "s.gl = gl;"
+ "return s;")
private static native Scene setUp(GPUDevice device, int draws);
@JSBody(
params = {"device", "s"},
script = "s.encoder = device.createCommandEncoder();"
+ "var pass = s.encoder.beginRenderPass({ colorAttachments: [{ view: s.view,"
+ " loadOp: 'clear', storeOp: 'store', clearValue: [0, 0, 0, 1] }] });"
+ "pass.setPipeline(s.pipeline); pass.setVertexBuffer(0, s.vbuf); pass.setIndexBuffer(s.ibuf, 'uint16');"
+ "s.pass = pass; return pass;")
private static native Pass beginPass(GPUDevice device, Scene scene);
/** Ends the pass {@link #beginPass} began and submits its commands. */
@JSBody(
params = {"device", "s"},
script = "s.pass.end(); device.queue.submit([s.encoder.finish()]);")
private static native void endPass(GPUDevice device, Scene scene);
@JSBody(
params = {"pass", "s", "draws"},
script = "var g = s.bindGroup, o = s.offsets;"
+ "for (var i = 0; i < draws; i++) { pass.setBindGroup(0, g, o, i, 1); pass.drawIndexed(3, 1, 0, 0, 0); }")
private static native void drawAllInJs(Pass pass, Scene scene, int draws);
@JSBody(
params = {"pass", "s", "view", "length"},
script = "var g = s.bindGroup, o = s.offsets, i = 0;"
+ "while (i < length) {"
+ " var op = view[i];"
+ " if (op === 1) { pass.setBindGroup(0, g, o, view[i + 1], 1); i += 2; }"
+ " else { pass.drawIndexed(view[i + 1], 1, view[i + 2], view[i + 3], 0); i += 4; } }")
private static native void replay(Pass pass, Scene scene, Int32Array view, int length);
@JSBody(params = {"pass", "s"}, script = "pass.executeBundles([s.bundle]);")
private static native void executeBundle(Pass pass, Scene scene);
@JSBody(
params = "s",
script = "var gl = s.gl; gl.useProgram(s.glProgram); gl.viewport(0, 0, 256, 256);"
+ "gl.clear(gl.COLOR_BUFFER_BIT);")
private static native void prepareGl(Scene scene);
@JSBody(params = "s", script = "s.gl.finish();")
private static native void glFinish(Scene scene);
@JSBody(
params = "s",
script = "var e = s.error || null; if (!e && s.gl.getError() !== 0) e = 'WebGL2 error ' + s.gl.getError();"
+ " return e;")
private static native String takeError(Scene scene);
@JSBody(script = "return performance.now();")
private static native double now();
}
@@ -0,0 +1,51 @@
import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
/**
* {@code int}s handed to JavaScript arrive as the same Numbers (tools/webbuild's {@code
* JsoIntrinsics}: an i31 where the value fits, else TeaVM's import): each side of the i31 range's
* edges, the int range's ends, and values from a loop, so they aren't constants; through a
* {@code @JSBody} argument and through a JSO interface method's. Prints "probe passed".
*/
public final class WrapIntProbe {
private WrapIntProbe() {}
/** A JavaScript object whose method reports what it got, as a JSO interface call reaches it. */
interface Checker extends JSObject {
String check(int value, String expected);
}
public static void main(String[] args) {
int[] values = {0, 1, -1, 7, 36160, (1 << 30) - 1, 1 << 30, -(1 << 30), -(1 << 30) - 1,
Integer.MAX_VALUE, Integer.MIN_VALUE, 0x7fff_fffe, 123_456_789, -987_654_321};
Checker checker = checker();
String failure = null;
for (int round = 0; round < 3 && failure == null; round++) {
for (int value : values) {
// Not a constant the compiler could fold: a value read from the array, shifted and back.
int v = (value ^ round) ^ round;
String expected = Integer.toString(v);
String body = describe(v, expected);
String method = checker.check(v, expected);
if (body != null || method != null) {
failure = body != null ? body : method;
break;
}
}
}
System.out.println(failure == null ? "probe passed" : "probe failed: " + failure);
}
@JSBody(
params = {"value", "expected"},
script = "return typeof value === 'number' && String(value) === expected ? null"
+ " : '@JSBody got ' + typeof value + ' ' + value + ', expected ' + expected;")
private static native String describe(int value, String expected);
@JSBody(
script = "return { check: function(value, expected) {"
+ " return typeof value === 'number' && String(value) === expected ? null"
+ " : 'a method got ' + typeof value + ' ' + value + ', expected ' + expected; } };")
private static native Checker checker();
}
@@ -0,0 +1,62 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Regression probe for tools/teavm-patches' TZipFile fix: TeaVM's ZipFile gave its raw
* inflater exactly an entry's compressed bytes, and InflaterInputStream threw EOFException when
* the inflater still asked for input at their end, as it can for a whole entry (638 textures of a
* community resource pack). The JDK's ZipFile adds a dummy byte; the patch does too. Writes entries
* of many sizes and kinds, reads each back to its end, and prints "probe passed" when all match.
*/
public final class ZipFileProbe {
private ZipFileProbe() {}
public static void main(String[] args) throws IOException {
Random random = new Random(5);
byte[][] contents = new byte[400][];
File file = new File("/probe.zip");
try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(file))) {
for (int i = 0; i < contents.length; i++) {
byte[] data = new byte[random.nextInt(4000)];
// Some random (incompressible), some patterned, some mixed: PNG-like variety.
for (int j = 0; j < data.length; j++) {
data[j] = (byte) (i % 3 == 0 ? random.nextInt() : i % 3 == 1 ? j / 7 : (j % 13) * random.nextInt(3));
}
contents[i] = data;
zip.putNextEntry(new ZipEntry("entry" + i));
zip.write(data);
zip.closeEntry();
}
}
int failures = 0;
String first = "";
try (ZipFile zip = new ZipFile(file)) {
for (int i = 0; i < contents.length; i++) {
try (InputStream in = zip.getInputStream(zip.getEntry("entry" + i))) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
for (int read = in.read(buffer); read >= 0; read = in.read(buffer)) {
out.write(buffer, 0, read);
}
if (!Arrays.equals(out.toByteArray(), contents[i])) {
failures++;
first = first.isEmpty() ? "entry" + i + " differs" : first;
}
} catch (IOException e) {
failures++;
first = first.isEmpty() ? "entry" + i + ": " + e : first;
}
}
}
System.out.println(failures == 0 ? "probe passed" : "probe failed: " + failures + " entries, first " + first);
}
}
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# Compiles one probe (app-web/probes/<Name>.java) with TeaVM against the browser build's class
# library and runs it in headless Chromium until it prints "probe passed" (see README.md,
# Experiments). Takes seconds, not the full build's ten minutes.
#
# app-web/probes/run.sh SuspendingTernaryProbe
# app-web/probes/run.sh WebGpuCallProbe -Pbrowser.gpu=webgpu -Pteavm.fast (more Gradle options)
set -euo pipefail
name="${1:?usage: app-web/probes/run.sh <ProbeName>}"
root="$(cd "$(dirname "$0")/../.." && pwd)"
classes="$root/app-web/build/probes/$name"
rm -rf "$classes"
# Probes may use the Netty the browser build keeps (the teavm task puts it on TeaVM's class path);
# javac finds the pinned version in Gradle's cache, which any build of the repo has filled.
netty="$(sed -n 's/^netty = "\(.*\)"/\1/p' "$root/gradle/libs.versions.toml")"
netty_jars=""
for module in netty-common netty-buffer netty-transport netty-codec-base; do
jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$module-$netty.jar" | head -n 1)"
netty_jars="$netty_jars:$jar"
done
# Probes may call TeaVM's interop and JSO APIs, as the page's own code does.
teavm="$(sed -n 's/^teavm = "\(.*\)"/\1/p' "$root/gradle/libs.versions.toml")"
for module in teavm-interop teavm-jso teavm-jso-apis; do
jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$module-$teavm.jar" | head -n 1)"
netty_jars="$netty_jars:$jar"
done
# Probes may use the Via the browser build compiles in.
for library in viaversion viabackwards; do
version="$(sed -n "s/^$library = \"\(.*\)\"/\1/p" "$root/gradle/libs.versions.toml")"
jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$library-common-$version.jar" | head -n 1)"
netty_jars="$netty_jars:$jar"
done
# Probes may also use Incari's platform classes (StorageProbe installs the file system).
cd "$root"
./gradlew -q :platform-web:classes
# Probes compile for Java 25, as the game does; a newer javac must be told.
javac --release 25 -cp "${netty_jars#:}:$root/platform-web/build/classes/java/main" -d "$classes" \
"$root/app-web/probes/$name.java"
./gradlew :app-web:browserCheck -Pteavm.main="$name" -Pteavm.classpath="$classes" \
"-Pbrowser.expect=probe (passed|failed.*)" -Pbrowser.count=1 -Pbrowser.seconds=60 "${@:2}" \
| tee "$root/app-web/build/probes/$name.log"
grep -q "probe passed" "$root/app-web/build/probes/$name.log"
@@ -0,0 +1,45 @@
version:5023
onboardAccessibility:false
pauseOnLostFocus:false
joinedFirstServer:true
skipMultiplayerWarning:true
tutorialStep:none
realmsNotifications:false
graphicsPreset:"custom"
fov:0.0
fovEffectScale:0.0
guiScale:2
renderDistance:8
simulationDistance:6
biomeBlendRadius:2
ao:true
renderClouds:"true"
cloudRange:64
particles:0
mipmapLevels:4
textureFiltering:1
maxAnisotropyBit:1
entityShadows:true
entityDistanceScaling:1.0
improvedTransparency:false
cutoutLeaves:true
weatherRadius:10
chunkSectionFadeInTime:0.0
menuBackgroundBlurriness:5
prioritizeChunkUpdates:0
bobView:false
gamma:0.5
vignette:true
screenEffectScale:1.0
darknessEffectScale:1.0
damageTiltStrength:0.0
hideLightningFlashes:true
enableVsync:false
maxFps:60
inactivityFpsLimit:"minimized"
fullscreen:false
chatVisibility:2
showSubtitles:false
narrator:0
soundCategory_master:0.0
lang:en_us
@@ -0,0 +1,219 @@
# The screenshot-diff harness's scenes: ./gradlew :app-web:screenshotDiff renders each one
# with the desktop game (Mojang's OpenGL backend) and the browser build (WebGL2), and compares the
# pairs by SSIM. The format is tools/webbuild's SceneScript; ADR 0012 explains the threshold.
#
# Each game joins its own fresh world from server.properties' seed as IncariShot, with
# options.txt's options. The harness freezes each world as soon as its server is up, so the only
# ticks either world runs are the ones the harness and these scenes step (tick step): the same in
# both, so clouds, animated textures and the like line up. Loading chunks takes ticks, so a
# teleport to somewhere new steps the world. Every scene sets its own time, weather, blocks and
# entities, so scenes don't depend on each other. Built scenes float at y 150 and above, so they
# don't depend on the terrain either. In a frozen world a killed entity never finishes dying, so
# entities are cleared by moving them out of sight (up and far away, never into the void, where a
# spectator still following one would die); particles only appear once the world ticks,
# so their scene steps it by one tick; and overworld chunks that reload after a trip to another
# dimension come back unlit, so the dimensions come last.
threshold 0.90
setup
rcon:gamerule advance_time false
rcon:gamerule advance_weather false
rcon:gamerule spawn_mobs false
rcon:gamemode spectator IncariShot
# Hide the HUD and the hand: the scenes are about the world.
key:F1
scene terrain Overworld terrain at noon: solid, cutout and translucent terrain, grass, fog, sky
rcon:weather clear
rcon:time set 6000
rcon:tp IncariShot 0 100 0 45 20
sleep:3000
settle
shot:terrain
scene translucency Water, stained glass, ice, slime and honey, with regular and improved (OIT) transparency
rcon:weather clear
rcon:time set 6000
rcon:tp IncariShot 20.5 154 34.5 0 25
sleep:2000
rcon:fill 13 149 39 27 149 53 minecraft:smooth_stone
rcon:fill 14 150 40 19 153 45 minecraft:glass hollow
rcon:fill 15 150 41 18 152 44 minecraft:water
rcon:setblock 21 150 41 minecraft:red_stained_glass
rcon:setblock 22 150 41 minecraft:lime_stained_glass
rcon:setblock 23 150 41 minecraft:blue_stained_glass
rcon:setblock 22 151 41 minecraft:yellow_stained_glass
rcon:fill 21 150 44 26 152 44 minecraft:light_blue_stained_glass_pane
rcon:setblock 21 150 47 minecraft:ice
rcon:setblock 23 150 47 minecraft:slime_block
rcon:setblock 25 150 47 minecraft:honey_block
rcon:setblock 25 150 42 minecraft:tinted_glass
sleep:2000
settle
shot:translucency
# F3+X switches improved transparency (the order-independent transparency passes) on and off.
key:F3+KeyX
sleep:2000
settle
shot:translucency_oit
key:F3+KeyX
sleep:1000
scene entities Mobs, an armor stand, a dropped item, block entities, shadows and a glowing outline
rcon:weather clear
rcon:time set 6000
rcon:tp IncariShot -23.5 154 35.5 0 25
sleep:2000
rcon:tp @e[type=!minecraft:player] 0 250 -400
rcon:fill -32 149 38 -15 149 54 minecraft:grass_block
rcon:summon minecraft:cow -27.5 150 43.5 {NoAI:1b,Rotation:[30f,0f]}
rcon:summon minecraft:sheep -24.5 150 44.5 {NoAI:1b,Color:14b,Rotation:[-20f,0f]}
rcon:summon minecraft:villager -20.5 150 43.5 {NoAI:1b,Rotation:[180f,0f]}
rcon:summon minecraft:zombie -25.5 150 47.5 {NoAI:1b,PersistenceRequired:1b,Glowing:1b,Rotation:[160f,0f]}
rcon:summon minecraft:armor_stand -21.5 150 47.5 {ShowArms:1b,Rotation:[200f,0f],equipment:{head:{id:"minecraft:diamond_helmet"},chest:{id:"minecraft:golden_chestplate"},mainhand:{id:"minecraft:iron_sword"}}}
rcon:summon minecraft:item -18.5 150 42.5 {Item:{id:"minecraft:diamond",count:1},PickupDelay:32767,Age:-32768}
rcon:setblock -29 150 50 minecraft:chest[facing=north]
rcon:setblock -28 150 50 minecraft:oak_sign[rotation=8]{front_text:{messages:["Incari","Scene","",""]}}
rcon:setblock -27 150 50 minecraft:white_banner[rotation=8]
rcon:setblock -26 150 50 minecraft:enchanting_table
rcon:setblock -25 150 50 minecraft:purple_shulker_box
rcon:setblock -24 150 50 minecraft:skeleton_skull[rotation=8]
rcon:setblock -23 150 50 minecraft:bell[attachment=floor,facing=north]
rcon:setblock -22 150 50 minecraft:decorated_pot
rcon:setblock -21 150 50 minecraft:lectern[has_book=true,facing=north]
rcon:setblock -20 150 50 minecraft:conduit
sleep:2000
settle
shot:entities
scene particles Particles of several kinds, fixed in place by the frozen world
rcon:weather clear
rcon:time set 6000
rcon:tp IncariShot -23.5 154 75.5 0 20
sleep:2000
rcon:fill -32 149 80 -15 149 92 minecraft:stone
rcon:particle minecraft:flame -27.5 151 83.5 0 0 0 0 1 force
rcon:particle minecraft:heart -25.5 151.5 83.5 0 0 0 0 1 force
rcon:particle minecraft:happy_villager -23.5 151 83.5 0 0 0 0 1 force
rcon:particle minecraft:end_rod -21.5 151.5 83.5 0 0 0 0 1 force
rcon:particle minecraft:note -19.5 151 83.5 0 0 0 0 1 force
rcon:particle minecraft:explosion -23.5 152 86.5 0 0 0 0 1 force
rcon:particle minecraft:soul_fire_flame -27.5 151 85.5 0 0 0 0 1 force
rcon:particle minecraft:crit -19.5 151.5 85.5 0 0 0 0 1 force
# The client adds particles on its next tick.
rcon:tick step 1
sleep:2000
settle
shot:particles
scene sky Sunrise and midnight: sun, moon, stars, clouds, the sky's colors
rcon:weather clear
rcon:time set 23600
rcon:tp IncariShot 0 110 0 -90 -10
sleep:2000
settle
shot:sky_sunrise
rcon:time set 18000
rcon:tp IncariShot 0 110 0 0 -60
sleep:2000
settle
shot:sky_midnight
scene gui The creative inventory: items, block items, text, and an enchanted item's glint; then the HUD
rcon:weather clear
rcon:time set 6000
# Players tick in a frozen world, and a creative player falls: stand them on a platform.
rcon:fill -2 149 -2 2 149 2 minecraft:smooth_stone
rcon:tp IncariShot 0 150 0 45 20
rcon:gamemode creative IncariShot
rcon:item replace entity IncariShot hotbar.0 with minecraft:diamond_sword
rcon:item replace entity IncariShot hotbar.1 with minecraft:grass_block
rcon:item replace entity IncariShot hotbar.2 with minecraft:oak_log
rcon:item replace entity IncariShot hotbar.3 with minecraft:bow
rcon:item replace entity IncariShot hotbar.4 with minecraft:enchanted_golden_apple
rcon:item replace entity IncariShot hotbar.5 with minecraft:water_bucket
rcon:item replace entity IncariShot hotbar.6 with minecraft:torch
rcon:item replace entity IncariShot hotbar.7 with minecraft:shield
rcon:item replace entity IncariShot hotbar.8 with minecraft:red_bed
sleep:2000
key:KeyE
move:0.02,0.02
sleep:1500
settle
shot:gui_inventory
key:Escape
# The HUD over the world: the page keeps it in a texture between refreshes (ADR 0030).
key:F1
sleep:1000
settle
shot:gui_hud
key:F1
rcon:gamemode spectator IncariShot
sleep:1000
scene distant_terrain A wide floor seen at a grazing angle: mipmaps and texture filtering
rcon:weather clear
rcon:time set 6000
rcon:tp IncariShot 0.5 185 90.5 0 30
rcon:tick step 100
sleep:7000
rcon:fill -90 180 0 90 180 180 minecraft:bricks
rcon:tp IncariShot 0.5 181.7 1.5 0 4
sleep:3000
settle
shot:distant_terrain
rcon:tp IncariShot 0 100 0 45 20
rcon:fill -90 180 0 90 180 180 minecraft:air
scene post_effects Post effects: the pause menu's blur, and a creeper's view
rcon:weather clear
rcon:time set 6000
rcon:tp IncariShot 0 100 0 45 20
sleep:2000
settle
key:Escape
move:0.02,0.02
sleep:1000
settle
shot:post_menu_blur
key:Escape
sleep:1000
rcon:tp @e[type=minecraft:creeper] 0 250 -400
rcon:summon minecraft:creeper 2.5 101 2.5 {NoAI:1b,NoGravity:1b,Rotation:[45f,20f]}
rcon:spectate @e[type=minecraft:creeper,limit=1] IncariShot
sleep:2000
settle
shot:post_creeper
# A teleport ends spectating; only then may the creeper leave (a spectator follows its target).
rcon:tp IncariShot 0 100 0 45 20
sleep:1000
rcon:tp @e[type=minecraft:creeper] 0 250 -400
sleep:1000
scene weather Rain over the terrain: the weather pass and its darker sky
rcon:weather rain
rcon:time set 6000
rcon:tp IncariShot 0 100 0 45 20
# Rain fades in over a few seconds of ticks.
rcon:tick step 200
sleep:12000
settle
shot:weather
rcon:weather clear
scene dimensions The Nether and the End: their fog, sky and terrain
rcon:execute in minecraft:the_nether run tp IncariShot 0 80 0 45 10
rcon:tick step 200
sleep:12000
settle
shot:nether
rcon:execute in minecraft:the_end run tp IncariShot 40 80 40 135 15
rcon:tick step 200
sleep:12000
rcon:execute in minecraft:the_end run tp @e[type=minecraft:ender_dragon] 0 250 -400
settle
shot:the_end
rcon:execute in minecraft:overworld run tp IncariShot 0 100 0 45 20
rcon:tick step 200
sleep:12000
@@ -0,0 +1,18 @@
# The screenshot-diff harness's game server (see scenes.txt). The harness adds the address,
# ports and a random RCON password, and starts every run with a fresh world from this seed.
level-seed=20260928
level-type=minecraft\:normal
generate-structures=true
online-mode=false
white-list=false
difficulty=easy
spawn-monsters=false
view-distance=8
simulation-distance=6
spawn-protection=0
pause-when-empty-seconds=0
max-tick-time=-1
broadcast-console-to-ops=false
broadcast-rcon-to-ops=false
sync-chunk-writes=false
enable-status=true
@@ -0,0 +1,79 @@
package incari.app.web;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import incari.classlib.resources.ClassPathResources;
import incari.platform.web.storage.WebFileSystem;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jspecify.annotations.Nullable;
/**
* The asset pack (ADR 0014): what the build prepares for the game ahead of time, in one zip
* the page mounts read-only at {@value #ROOT}: the translated shaders, and the vanilla sprites
* decoded with their mip levels (ADR 0026). Like the client jar, the storage worker keeps it
* (under its hash, so a new build's pack is fetched once) and it's mounted in place, each file
* inflated when opened.
*
* <p>The pack holds translated Mojang files, so it's made on the machine that builds the game
* ({@code :app-web:assetPack}) and never published.
*
* <p>Its layout: {@code pack.json} ({@code {"format": 1, "game": "26.3"}}), then the files by the
* names the game's loaders read ({@code shaders.json}, {@code sprites.bin}), and under {@value #CLASSPATH} resources
* libraries read from the class path (Via's mapping data).
*/
final class AssetPack {
/** Where the pack's files appear in the page's file system. */
static final String ROOT = "/incari-pack";
/** The pack's directory of class-path resources. */
static final String CLASSPATH = "classpath";
/** The layout this code reads; a pack of another format is refused. */
static final int FORMAT = 1;
private AssetPack() {}
/**
* Mounts the build's pack, if the build manifest names one; suspends while it's fetched.
*
* @return whether a pack is mounted
*/
static boolean mount(WebFileSystem files) throws IOException {
String url = LoaderPage.packUrl();
if (url == null) {
return false;
}
double start = Fetch.now();
WebFileSystem.Mounted mounted = files.mountZip(ROOT, url, cacheKey(url), name -> true);
JsonObject manifest = JsonParser.parseString(
new String(Files.readAllBytes(Path.of(ROOT, "pack.json")), StandardCharsets.UTF_8))
.getAsJsonObject();
int format = manifest.get("format").getAsInt();
String game = manifest.get("game").getAsString();
if (format != FORMAT || !game.equals(ClientJar.VERSION)) {
throw new IOException("The asset pack is format " + format + " for " + game + "; this build reads format "
+ FORMAT + " for " + ClientJar.VERSION);
}
ClassPathResources.addRoot(ROOT + "/" + CLASSPATH);
System.out.println("[Incari] Asset pack: " + mounted.files() + " files, "
+ (mounted.cached() ? "from storage" : "downloaded") + ", in " + Math.round(Fetch.now() - start)
+ " ms");
return true;
}
/** A file of the mounted pack, or null if there's no pack or it lacks the file. */
static byte @Nullable [] read(String name) throws IOException {
Path file = Path.of(ROOT, name);
return Files.isRegularFile(file) ? Files.readAllBytes(file) : null;
}
/** The storage key: the pack's version (its URL's {@code ?v=}), so each build's is kept apart. */
static String cacheKey(String url) {
int version = url.indexOf("?v=");
return "pack-" + (version < 0 ? "unversioned" : url.substring(version + 3));
}
}
@@ -0,0 +1,42 @@
package incari.app.web;
import incari.classlib.resources.ClassPathResources;
import incari.client.IncariBuild;
import incari.platform.web.storage.WebFileSystem;
import java.io.IOException;
/**
* Puts the client jar's resources where the game looks for them ({@link ClassPathResources}):
* the build compiles the game's classes but not the rest of the jar, which is Mojang's to
* distribute. The page fetches the jar the player's machine already has; for development that's
* the one {@code ./incari setup} downloaded, which {@code :app-web:serve} offers at {@value #URL}.
*
* <p>The jar isn't unpacked: the storage worker keeps it (so later loads don't fetch
* it again), and it's mounted read-only in place, each resource inflated when the game opens it.
* Its bytes stay in the page, outside the game's heap (ADR 0011).
*/
final class ClientJar {
static final String URL = "client.jar";
/**
* The game version the jar is, which names its cached copy: a new version's replaces it. From
* incari.properties, so a version bump can't leave players on a stale cached jar.
*/
static final String VERSION = IncariBuild.MINECRAFT_VERSION;
private ClientJar() {}
/** Mounts every resource that isn't a class or jar metadata; suspends while it's fetched. */
static void mount(WebFileSystem files) throws IOException {
double start = Fetch.now();
WebFileSystem.Mounted mounted = files.mountZip(
ClassPathResources.ROOT,
URL,
"client-" + VERSION + ".jar",
name -> !name.endsWith(".class") && !name.startsWith("META-INF/"));
System.out.println("[Incari] Client jar: " + mounted.files() + " resources mounted, "
+ (mounted.cached() ? "from storage" : "downloaded") + ", in " + Math.round(Fetch.now() - start)
+ " ms");
}
}
@@ -0,0 +1,155 @@
package incari.app.web;
import java.io.IOException;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/** Downloads files from next to the page: before the game starts, and for its resource reloads. */
final class Fetch {
private Fetch() {}
/**
* The whole file at {@code url}. Suspends the calling coroutine until the download finishes:
* must not block the page.
*
* @param hint what to check if it fails, for the error message
*/
static byte[] bytes(String url, String hint) throws IOException {
Outcome outcome = fetch(url);
ArrayBuffer buffer = outcome.buffer();
if (buffer == null) {
throw new IOException("Couldn't fetch " + url + ": " + outcome.error() + " (" + hint + ")");
}
return new Int8Array(buffer).copyToJavaArray();
}
/**
* The whole file at {@code url}, tried up to {@code attempts} times while it fails for a reason
* that may pass (no connection, a server error, too many requests), waiting longer each time.
* Suspends the calling thread: never the page's own.
*
* @param hint what to check if it fails, for the error message
*/
static byte[] bytesRetrying(String url, String hint, int attempts) throws IOException {
for (int attempt = 1; ; attempt++) {
Outcome outcome = fetch(url);
ArrayBuffer buffer = outcome.buffer();
if (buffer != null) {
return new Int8Array(buffer).copyToJavaArray();
}
String error = String.valueOf(outcome.error());
if (attempt >= attempts || !passing(error)) {
throw new IOException("Couldn't fetch " + url + ": " + error + " (" + hint + ")");
}
try {
Thread.sleep(500L * attempt);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted fetching " + url, e);
}
}
}
/** Whether a fetch's failure may pass: anything but a 4xx answer, except time-outs and rate limits. */
static boolean passing(String error) {
if (!error.startsWith("Error: HTTP 4")) {
return true;
}
return error.equals("Error: HTTP 408") || error.equals("Error: HTTP 429");
}
/**
* The whole files at {@code urls}, in their order, downloaded side by side. Suspends the calling
* coroutine until all have finished: must not block the page.
*
* @param hint what to check if one fails, for the error message
*/
static byte[][] all(List<String> urls, String hint) throws IOException {
Outcome[] outcomes = fetchAll(urls.toArray(String[]::new));
byte[][] files = new byte[outcomes.length][];
for (int i = 0; i < outcomes.length; i++) {
ArrayBuffer buffer = outcomes[i].buffer();
if (buffer == null) {
throw new IOException("Couldn't fetch " + urls.get(i) + ": " + outcomes[i].error() + " (" + hint + ")");
}
files[i] = new Int8Array(buffer).copyToJavaArray();
}
return files;
}
/**
* A download's contents, or why it failed. A failure comes back as a value and is thrown here, not
* through {@code AsyncCallback.error}: TeaVM's WebAssembly GC runtime rethrows an error it
* resumes with out of the JavaScript callback as well, after the caller has caught it, and the
* page crashes on the unhandled rejection (probe: {@code app-web/probes/FetchFailureProbe}).
*/
private record Outcome(
@Nullable ArrayBuffer buffer, @Nullable String error) {}
@Async
private static native Outcome fetch(String url);
private static void fetch(String url, AsyncCallback<Outcome> callback) {
start(
url,
buffer -> callback.complete(new Outcome(buffer, null)),
message -> callback.complete(new Outcome(null, message)));
}
@Async
private static native Outcome[] fetchAll(String[] urls);
private static void fetchAll(String[] urls, AsyncCallback<Outcome[]> callback) {
Outcome[] outcomes = new Outcome[urls.length];
if (urls.length == 0) {
callback.complete(outcomes);
return;
}
int[] left = {urls.length};
for (int i = 0; i < urls.length; i++) {
int index = i;
start(
urls[i],
buffer -> {
outcomes[index] = new Outcome(buffer, null);
if (--left[0] == 0) {
callback.complete(outcomes);
}
},
message -> {
outcomes[index] = new Outcome(null, message);
if (--left[0] == 0) {
callback.complete(outcomes);
}
});
}
}
@JSFunctor
interface Done extends JSObject {
void done(ArrayBuffer buffer);
}
@JSFunctor
interface Failed extends JSObject {
void failed(String message);
}
@JSBody(
params = {"url", "done", "failed"},
script = "fetch(url).then(function(r) {"
+ " if (!r.ok) throw new Error('HTTP ' + r.status); return r.arrayBuffer(); })"
+ ".then(function(b) { done(b); }, function(e) { failed(String(e)); });")
private static native void start(String url, Done done, Failed failed);
@JSBody(script = "return performance.now();")
static native double now();
}
@@ -0,0 +1,137 @@
package incari.app.web;
import incari.classlib.concurrent.Waits;
import incari.classlib.resources.ClassPathResources;
import incari.client.datafix.DataFixing;
import incari.client.memory.LightCopies;
import incari.client.net.PacketHandoff;
import incari.client.net.PlatformEventLoopGroupHolder;
import incari.client.singleplayer.ChannelLink;
import incari.client.singleplayer.WorldWorker;
import incari.client.startup.CriterionCodecs;
import incari.client.world.BiomeCells;
import incari.client.world.ChunkCompression;
import incari.client.world.Collisions;
import incari.client.world.DensityBranches;
import incari.client.world.GoalFlags;
import incari.client.world.Heights;
import incari.client.world.PositionalRandoms;
import incari.client.world.RemoteTerrain;
import incari.client.world.SpawnCosts;
import incari.client.world.StrongholdRings;
import incari.client.world.SurfaceBuffers;
import incari.client.world.SurfaceWrites;
import incari.platform.api.Platforms;
import incari.platform.web.WebPlatform;
import incari.platform.web.WorkerPlatform;
import incari.platform.web.storage.WebFileSystem;
import java.io.IOException;
import java.util.List;
import org.teavm.jso.JSBody;
import org.teavm.jso.typedarrays.ArrayBuffer;
/**
* The entry point of a copy of the game in a worker (ADR 0039): {@code WebMain.main(["--worker",
* role])}, as {@code game-worker.ts} starts it. It sets up what the role needs and nothing of the
* client: a file system of its own (filled by the page), the client jar's resources, the headless
* platform, and the settings the page makes that the server's code reads too.
*/
final class GameWorkerMain {
/** Where the page's storage worker keeps the client jar, from the private file system's root. */
private static final String CACHED_JAR = ".incari-cache/client-" + ClientJar.VERSION + ".jar";
private GameWorkerMain() {}
/** {@code query}: the page's query string, for the page options read here too. */
static void main(String role, String query) throws IOException {
LibraryDefaults.apply();
// A background pool task that blocks gives the pool up, as on the page.
Waits.beforeWait(WebPlatform::beforeWait);
WebFileSystem files = WebFileSystem.installDetached(List.of(ClassPathResources.ROOT));
int mounted = mountClientJar(files, !"all".equals(option(query, "workerjar")));
System.out.println("[Incari] Worker (" + role + "): " + mounted + " of the client jar's resources mounted");
Platforms.install(new WorkerPlatform(WebStorage.DEFAULT, files));
PlatformEventLoopGroupHolder.useLocalEventLoops();
// The page's defaults for what the server's code reads as well (WebMain).
DataFixing.buildLazily();
LightCopies.setEnabled(true);
Collisions.setEnabled(true);
PacketHandoff.setEnabled(true);
StrongholdRings.setEnabled(!"game".equals(option(query, "rings")));
SpawnCosts.setEnabled(!"game".equals(option(query, "spawncosts")));
SpawnCosts.setVerify("verify".equals(option(query, "spawncosts")));
SurfaceWrites.setEnabled(!"game".equals(option(query, "surface")));
BiomeCells.setEnabled(!"game".equals(option(query, "biomecells")));
BiomeCells.setVerify("verify".equals(option(query, "biomecells")));
Heights.setEnabled(!"game".equals(option(query, "heights")));
GoalFlags.setEnabled(!"game".equals(option(query, "goalflags")));
DensityBranches.setEnabled(!"game".equals(option(query, "densitychoices")));
RemoteTerrain.setHelpers(terrainHelpers(option(query, "terrainworkers")));
CriterionCodecs.setEnabled(!"game".equals(option(query, "criteria")));
ChunkCompression.setEnabled(!"game".equals(option(query, "deflate")));
PositionalRandoms.setEnabled(!"game".equals(option(query, "randoms")));
SurfaceBuffers.setEnabled(!"game".equals(option(query, "surfacebuffers")));
// ADR 0041's packets a flush per message (?packets=each: one each, as before).
ChannelLink.setBatched(!"each".equals(option(query, "packets")));
switch (role) {
case "server" -> WorldWorker.run();
case "terrain" -> RemoteTerrain.serve();
default -> throw new IllegalArgumentException("No such worker role: " + role);
}
}
/**
* Mounts the client jar's resources a worker reads, and returns how many. A server (or a
* terrain helper) reads the data packs, the language file and the root files (the version, the
* markers that find the vanilla pack's roots), never the client's assets: those stay out, and
* the jar's buffer is let go once they're copied (ADR 0043). {@code ?workerjar=all} mounts
* every resource, as before. The buffer is a local here so that it isn't held for the
* program's life by {@code main}'s frame, which never returns.
*/
private static int mountClientJar(WebFileSystem files, boolean serverOnly) throws IOException {
ArrayBuffer jar = WorkerPlatform.cachedZip(CACHED_JAR, ClientJar.URL);
return files.mountZip(
ClassPathResources.ROOT, jar, serverOnly ? GameWorkerMain::serverResource : GameWorkerMain::resource);
}
/** Every resource of the jar: not a class, not its signature. */
private static boolean resource(String name) {
return !name.endsWith(".class") && !name.startsWith("META-INF/");
}
/** A resource a server reads: the data packs, the languages, and the files at the root. */
private static boolean serverResource(String name) {
return resource(name)
&& (name.startsWith("data/")
|| name.startsWith("assets/minecraft/lang/")
|| name.equals("assets/.mcassetsroot")
|| name.indexOf('/') < 0);
}
/**
* How many terrain helpers singleplayer's server starts (ADR 0042): the page's
* {@code ?terrainworkers=N}, none otherwise. Off by default: no gain was measured where the
* server keeps up, and where the page and the server have two cores between them a helper would
* only take from both.
*/
private static int terrainHelpers(String option) {
if (option.isEmpty()) {
return 0;
}
try {
return Math.min(Integer.parseInt(option), Math.max(1, hardwareConcurrency() - 2));
} catch (NumberFormatException e) {
return 0;
}
}
@JSBody(script = "return (self.navigator && self.navigator.hardwareConcurrency) || 1;")
private static native int hardwareConcurrency();
/** A parameter of the page's query string, or "" if it has none. */
@JSBody(
params = {"query", "name"},
script = "return new URLSearchParams(query).get(name) || '';")
private static native String option(String query, String name);
}
@@ -0,0 +1,49 @@
package incari.app.web;
/**
* Library settings for the page, set as system properties before the libraries read them (they
* read them once, in static initializers).
*
* <p>Netty's buffers (ADR 0008):
*
* <ul>
* <li>{@code io.netty.allocator.type=unpooled}: Netty 4.2's default adaptive allocator can't
* start without method handles ({@code ConcurrentSkipListIntObjMultimap} looks up its own
* fallback through one). Unpooled heap buffers are plain {@code byte[]}, which WebAssembly GC
* allocates cheaply, and a page with one thread gains little from pooling.
* <li>{@code io.netty.noUnsafe=true}: there is no {@code Unsafe}; saying so skips the reflective
* probing and the warning about it. With no cleaner, Netty prefers heap buffers; a direct
* buffer, where a caller asks for one, is TeaVM's, in the module's linear memory.
* <li>{@code io.netty.leakDetection.level=disabled}: leak records capture stack traces and rely
* on reference queues, costly here; leaks are found on the desktop build.
* <li>{@code io.netty.machineId} and {@code io.netty.processId}: what Netty's channel ids
* ({@code DefaultChannelId}) are made from, otherwise found from the network interfaces' MAC
* addresses and the process handle, neither of which a page has. Singleplayer's in-memory
* channels are the first to use them. A fixed machine and process are fine: the ids only
* have to differ within the page, which the counter and the time in each id see to.
* </ul>
*
* <p>JOML: {@code joml.format=false}. JOML's {@code Options} builds a {@code DecimalFormat} from a
* pattern TeaVM's parser rejects (a leading space), which failed the first {@code org.joml.Math}
* call (vertex sorting by distance); without it JOML formats with the locale's number format.
*/
final class LibraryDefaults {
private LibraryDefaults() {}
static void apply() {
setDefault("io.netty.allocator.type", "unpooled");
setDefault("io.netty.noUnsafe", "true");
setDefault("io.netty.leakDetection.level", "disabled");
setDefault("io.netty.machineId", "00:00:00:00:00:00:00:01");
setDefault("io.netty.processId", "1");
setDefault("joml.format", "false");
}
/** Keeps a value set before, so a development page can still choose another. */
private static void setDefault(String key, String value) {
if (System.getProperty(key) == null) {
System.setProperty(key, value);
}
}
}
@@ -0,0 +1,36 @@
package incari.app.web;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
/**
* The host page's loader ({@code src/main/ts/boot.ts}), as the game's start-up sees it: the
* steps it shows under the progress bar, and what the build manifest says about the build. Without
* the loader (an experiment's page), every call does nothing.
*/
final class LoaderPage {
private LoaderPage() {}
/** Shows a start-up step on the loading screen, and logs it. */
static void status(String text) {
System.out.println("[Incari] Loading: " + text);
show(text);
}
@JSBody(params = "text", script = "var loader = window.incariLoader; if (loader) loader.status(text);")
private static native void show(String text);
/** The asset pack's URL (versioned by its hash) from the build manifest, or null if the build has none. */
@JSBody(script = "var build = window.incariBuild; return build && build.pack ? build.pack : null;")
static native @Nullable String packUrl();
/**
* The build's id from the build manifest (a hash over its files), or null without a manifest or
* for a development build, whose id names no particular files.
*/
@JSBody(
script = "var build = window.incariBuild;"
+ " return build && build.id && build.id !== 'development' ? build.id : null;")
static native @Nullable String buildId();
}
@@ -0,0 +1,165 @@
package incari.app.web;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import incari.client.audio.RemoteSounds;
import incari.client.resources.RemoteAssets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The game's files from the asset index, laid out by name under the assets directory (the layout
* the game reads when it's given no {@code --assetIndex}), where the vanilla pack finds them.
*
* <p>The index is hundreds of megabytes, so little is downloaded up front. At start: the sound list
* ({@code sounds.json}), the pack's metadata ({@code pack.mcmeta}, which lists the languages and
* is read before the first reload) and the built-in packs' zips (ADR 0055). The sounds get an empty placeholder each, so the game knows they
* exist, and {@link RemoteSounds} fetches one the first time it plays (ADR 0013). The
* Unicode font and the selected language are fetched by {@link RemoteAssets} before
* each resource reload that reads them (ADR 0037). The page gets all of it from next to itself: the
* index at {@value #INDEX_URL} and its objects under {@value #OBJECTS_URL}, which the dev server
* serves from {@code ./incari assets}' download and {@code ./incari build} copies into its folder.
*
* <p>Not the launcher's layout with an index: the game reads that through its own link file
* system, which TeaVM's {@code java.nio.file} can't walk.
*/
final class WebAssets {
static final String INDEX_URL = "asset-index.json";
static final String OBJECTS_URL = "assets/objects/";
/** Fetched before the game starts, because it reads them while loading. */
private static final List<String> AT_START = List.of("minecraft/sounds.json", "pack.mcmeta");
/**
* The built-in packs (Programmer Art, High Contrast; 0.7 MB), fetched at start too: the pack
* repository lists them once, before the first reload (ADR 0055).
*/
private static final List<String> BUILT_IN_PACKS = List.of("minecraft/resourcepacks/");
/** Tries for each sound's download before it plays silent (and is asked for again later). */
private static final int SOUND_ATTEMPTS = 3;
private static final String HINT = "is the dev server serving the assets?";
private WebAssets() {}
/**
* Stores the files read at start and a placeholder for every sound, and installs the fetchers
* for the rest. Without an asset index the page runs silent and in
* English only.
*/
static void install(String assetsDirectory) {
double start = Fetch.now();
byte[] indexFile;
try {
indexFile = Fetch.bytes(INDEX_URL, "has ./incari assets downloaded the asset index?");
} catch (IOException e) {
System.out.println("[Incari] No asset index, so no sounds: " + e.getMessage());
return;
}
try {
File root = new File(assetsDirectory);
JsonObject objects = JsonParser.parseString(new String(indexFile, StandardCharsets.UTF_8))
.getAsJsonObject()
.getAsJsonObject("objects");
Map<String, String> sounds = new HashMap<>();
Map<String, String> others = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : objects.entrySet()) {
String name = entry.getKey();
String hash = entry.getValue().getAsJsonObject().get("hash").getAsString();
if (name.endsWith(".ogg")) {
sounds.put(name, hash);
File placeholder = new File(root, name);
if (!placeholder.exists()) {
write(placeholder, new byte[0]);
}
} else {
others.put(name, hash);
}
}
Index index = new Index(root, others);
index.fetch(AT_START);
try {
index.fetch(BUILT_IN_PACKS);
} catch (IOException e) {
// Sounds and languages still work; the Resource Packs screen lists no built-in packs.
System.out.println("[Incari] No built-in resource packs: " + e.getMessage());
}
RemoteSounds.install(name -> {
String hash = sounds.get(name);
// A sound fetched as it first plays meets whatever the network is doing then.
return hash == null ? null : Fetch.bytesRetrying(objectUrl(hash), HINT, SOUND_ATTEMPTS);
});
RemoteAssets.install(index::fetch);
System.out.println("[Incari] Assets: " + sounds.size() + " sounds listed in "
+ Math.round(Fetch.now() - start) + " ms");
} catch (IOException | RuntimeException e) {
System.out.println("[Incari] Couldn't set up the assets, so no sounds: " + e);
}
}
/** The index's files other than sounds, written under {@code root} as they're fetched. */
private record Index(File root, Map<String, String> hashes) {
/**
* Downloads, side by side, each of {@code assets} (names, or folders ending in {@code /})
* that isn't written yet, and writes it. Suspends the calling coroutine: the entry point at
* start, a background thread before a reload.
*/
void fetch(List<String> assets) throws IOException {
double start = Fetch.now();
List<String> names = new ArrayList<>();
List<String> urls = new ArrayList<>();
for (Map.Entry<String, String> entry : hashes.entrySet()) {
String name = entry.getKey();
if (wanted(assets, name) && !new File(root, name).exists()) {
names.add(name);
urls.add(objectUrl(entry.getValue()));
}
}
if (names.isEmpty()) {
return;
}
byte[][] files = Fetch.all(urls, HINT);
long bytes = 0;
for (int i = 0; i < files.length; i++) {
write(new File(root, names.get(i)), files[i]);
bytes += files[i].length;
}
System.out.println("[Incari] Assets: fetched " + names.size() + " files (" + bytes / 1024 + " KB) in "
+ Math.round(Fetch.now() - start) + " ms");
}
private static boolean wanted(List<String> assets, String name) {
for (String asset : assets) {
if (asset.endsWith("/") ? name.startsWith(asset) : name.equals(asset)) {
return true;
}
}
return false;
}
}
private static String objectUrl(String hash) {
return OBJECTS_URL + hash.substring(0, 2) + "/" + hash;
}
private static void write(File file, byte[] contents) throws IOException {
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Can't create " + parent);
}
try (OutputStream out = new FileOutputStream(file)) {
out.write(contents);
}
}
}
@@ -0,0 +1,39 @@
package incari.app.web;
import incari.client.credits.Credit;
import incari.client.credits.Credits;
import java.net.URI;
/**
* What the browser build contains that the desktop doesn't, for the credits screen: TeaVM's
* runtime and class library, ThreeTen Backport, which TeaVM maps {@code java.time} onto, and JZlib,
* the deflate engine under TeaVM's zip classes. All are compiled into the build's WebAssembly.
*/
final class WebCredits {
private WebCredits() {}
static void install() {
Credits.add(new Credit(
"TeaVM",
null,
"Alexey Andreev and contributors",
"Apache-2.0",
Credits.APACHE_2,
URI.create("https://github.com/konsoletyper/teavm")));
Credits.add(new Credit(
"ThreeTen Backport",
null,
"Stephen Colebourne and Michael Nascimento Santos",
"BSD-3-Clause",
Credits.BSD_3_CLAUSE,
URI.create("https://github.com/ThreeTen/threetenbp")));
Credits.add(new Credit(
"JZlib",
null,
"ymnk, JCraft, Inc.",
"BSD-3-Clause",
Credits.BSD_3_CLAUSE,
URI.create("https://github.com/ymnk/jzlib")));
}
}
@@ -0,0 +1,388 @@
package incari.app.web;
import com.mojang.renderpearl.api.device.GpuBackend;
import incari.app.web.headless.HeadlessBackend;
import incari.classlib.concurrent.Waits;
import incari.classlib.resources.ClassPathResources;
import incari.client.TickPacing;
import incari.client.datafix.DataFixing;
import incari.client.gui.HudCache;
import incari.client.memory.LightCopies;
import incari.client.memory.PackedUnihex;
import incari.client.modules.IncariModules;
import incari.client.net.PacketHandoff;
import incari.client.net.PlatformEventLoopGroupHolder;
import incari.client.online.IncariOnline;
import incari.client.online.UpdateNotice;
import incari.client.particle.AmbientParticles;
import incari.client.particle.ParticleBudget;
import incari.client.particle.ParticleInstancing;
import incari.client.particle.ParticleLight;
import incari.client.platform.GraphicsBackends;
import incari.client.platform.OnlineServices;
import incari.client.profile.PlayerName;
import incari.client.profiler.Profiling;
import incari.client.render.AnimatedSprites;
import incari.client.render.EntityOcclusion;
import incari.client.render.GlyphQuads;
import incari.client.render.GraphUpdates;
import incari.client.render.QuadSort;
import incari.client.render.SignLines;
import incari.client.render.SpriteCache;
import incari.client.render.TerrainVertexFormat;
import incari.client.render.TextLayouts;
import incari.client.render.TintBlend;
import incari.client.render.VertexMath;
import incari.client.render.entity.ModelBatches;
import incari.client.render.entity.OpaqueSkins;
import incari.client.render.mesher.ChestBaking;
import incari.client.render.mesher.MeshTableCache;
import incari.client.render.mesher.Meshing;
import incari.client.render.terrain.TerrainDrawLists;
import incari.client.singleplayer.ChannelLink;
import incari.client.singleplayer.QuickWorlds;
import incari.client.singleplayer.WorkerWorlds;
import incari.client.startup.CriterionCodecs;
import incari.client.startup.DeferredModels;
import incari.client.startup.LoadingFade;
import incari.client.tier.DeviceTier;
import incari.client.world.BiomeCells;
import incari.client.world.ChunkCompression;
import incari.client.world.Collisions;
import incari.client.world.DensityBranches;
import incari.client.world.GoalFlags;
import incari.client.world.Heights;
import incari.client.world.PositionalRandoms;
import incari.client.world.SpawnCosts;
import incari.client.world.StrongholdRings;
import incari.client.world.SurfaceBuffers;
import incari.client.world.SurfaceWrites;
import incari.platform.api.Platforms;
import incari.platform.web.WebPlatform;
import incari.platform.web.storage.WebFileSystem;
import incari.render.webgl2.WebGl2Backend;
import incari.render.webgl2.shaders.ShaderManifest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.teavm.jso.JSBody;
/**
* The browser build's entry point: opens the stored files ({@link WebFileSystem}), mounts the
* client jar ({@link ClientJar}) and asset pack ({@link AssetPack}), loads the translated shaders
* ({@link WebShaders}), installs {@link WebPlatform} and the WebGL2 backend, then starts the
* game's {@code Main}. Each step shows on the loading screen ({@link LoaderPage}).
*
* <p>Page options, for development:
*
* <ul>
* <li>{@code ?renderer=headless}: run without drawing.
* <li>{@code ?shaders=eager}: link every WebGL program at start-up, so all compile errors show
* at once.
* <li>{@code ?server=ws://...}: join that server once started. {@code ?name=...}: the offline
* name.
* <li>{@code ?world=<name>}: open that singleplayer world; with {@code &seed=<seed>}, create it
* first (the singleplayer benchmark).
* <li>{@code ?share=<relay>}: share the open world on that relay. {@code ?shared=<relay>|<code>}:
* join a shared world (ADR 0062).
* <li>{@code ?options=<file>}: start with that options file from beside the page (the
* screenshot diffs pin their options this way).
* <li>{@code ?profile}: collect frame measurements from the start, for the benchmark.
* {@code ?overlay}: show the profiler's overlay.
* <li>{@code ?drawcensus}: log each pipeline's draws a frame every 600 frames.
* {@code ?gpucensus}: the same for GPU time.
* <li>{@code ?tier=potato|standard|high}: the device tier budgets scale by (particles, largest
* atlas, terrain heaps, decoded sounds). Standard is the default.
* <li>{@code ?mesher=inline|vanilla|verify}: mesh terrain on the page's thread, with the game's
* compiler, or both and compare, instead of in Incari's workers.
* </ul>
*
* <p>To compare an Incari change with the game's own way:
*
* <ul>
* <li>Memory and start-up: {@code ?text=game} (lay out world text every frame),
* {@code ?quads=game}, {@code ?copies=all} (keep a copy of every WebGL buffer),
* {@code ?models=now} (load models before the title screen), {@code ?sprites=off} (decode
* every sprite).
* <li>{@code ?multidraw=off}: one draw per terrain section, not WEBGL_multi_draw (ADR 0022).
* <li>ADR 0027: {@code ?uniforms=each} (upload each uniform write alone), {@code ?rebase=off}
* (move the vertex attributes for each base vertex).
* <li>ADR 0030: {@code ?sort=game}, {@code ?tint=game}, {@code ?items=game} (no instancing),
* {@code ?skins=game}, {@code ?drawlists=game}, {@code ?faces=all} (draw back faces),
* {@code ?animations=all} (animate unseen sprites), {@code ?hud=live} (draw the HUD every
* frame), {@code ?chests=game} (closed chests as block entities).
* <li>ADR 0031: {@code ?ambient=game}, {@code ?glyphs=game}, {@code ?signs=game} (submit blank
* lines), {@code ?graph=game} (full occlusion update at once), {@code ?particlelight=frame}
* (read particle light every frame).
* </ul>
*/
public final class WebMain {
/** The background pool's least share of a frame while it has work (ADR 0035). */
private static final double DEFAULT_POOL_FLOOR_MILLIS = 4.0;
private WebMain() {}
public static void main(String[] args) throws IOException {
if (args.length >= 2 && args[0].equals("--worker")) {
// A copy of the game in a worker (ADR 0039): singleplayer's server, never the client.
// The page's query comes third, for the page options the server's code reads too.
GameWorkerMain.main(args[1], args.length > 2 ? args[2] : "");
return;
}
// Before any library reads them: Netty and JOML read their settings once, at class load.
LibraryDefaults.apply();
// This thread becomes the game's render thread: its waits hold back the page's frame, so
// they're timed for the frame monitor.
Waits.watch(Thread.currentThread());
// A background pool task that blocks gives the pool up, so what it waits for can run.
Waits.beforeWait(WebPlatform::beforeWait);
// Before anything touches a file. Dropped files, the jar's resources and the sound
// placeholders (rewritten from the asset index on every load) are never stored.
LoaderPage.status("Opening saved files");
WebFileSystem files = WebFileSystem.install(List.of(
WebPlatform.DROP_DIRECTORY,
ClassPathResources.ROOT,
AssetPack.ROOT,
WebStorage.DEFAULT.assetsDirectory()));
LoaderPage.status("Loading game files");
ClientJar.mount(files);
LoaderPage.status("Loading textures");
boolean pack = AssetPack.mount(files);
if (pack && !"off".equals(option("sprites"))) {
// The vanilla sprites the build decoded, with their mip levels (ADR 0026).
SpriteCache.install(Path.of(AssetPack.ROOT, "sprites.bin"));
}
LoaderPage.status("Loading sounds");
WebAssets.install(WebStorage.DEFAULT.assetsDirectory());
Platforms.install(new WebPlatform(WebStorage.DEFAULT, files));
WebCredits.install();
// Realms is stripped from the browser build (tools/survey/rules.txt).
OnlineServices.disableRealms();
// Nor does it call Mojang's other services: no discovery, profile, key or telemetry requests.
OnlineServices.disableMojang();
// No sockets, so no selector for Netty's event loops to wait on (ADR 0008).
PlatformEventLoopGroupHolder.useLocalEventLoops();
// Terrain meshing (ADR 0023): Incari's mesher in Web Workers, writing the compact
// terrain vertex. ?mesher=inline meshes on the page's thread instead; ?mesher=vanilla uses
// the game's compiler and vertex format; ?mesher=verify meshes both ways and compares.
String mesher = option("mesher");
switch (mesher) {
case "vanilla" -> Meshing.configure(Meshing.Mode.VANILLA, false);
case "verify" -> Meshing.configure(Meshing.Mode.VERIFY, false);
default -> {
TerrainVertexFormat.useCompact();
Meshing.configure(Meshing.Mode.INCARI, !"inline".equals(mesher));
// Translucent layers in an order that holds from every camera are never re-sorted
// (ADR 0034); ?resort=game sorts them all as the game does.
Meshing.setFixedOrder(!"game".equals(option("resort")));
// Snapshots read each section's copied blocks directly (ADR 0034);
// ?snapshotreads=game reads them a block at a time through the region.
Meshing.setDirectReads(!"game".equals(option("snapshotreads")));
// The mesher's tables kept from start to start (ADR 0032); ?meshtables=build builds
// them every time.
String build = LoaderPage.buildId();
if (build != null && !"build".equals(option("meshtables"))) {
MeshTableCache.enable(Path.of("/incari/cache/mesher-tables.bin"), build);
}
// Closed chests meshed into terrain (ADR 0030); ?chests=game draws them the game's way.
if (!"game".equals(option("chests"))) {
ChestBaking.enable();
}
}
}
// Entities, particles and text (ADR 0024): ?entityculling=off draws entities no visible
// section holds, and ?instancing=off entity models the game's way, to compare; ?particles=potato,
// standard or high picks the particle cap whatever the device's tier.
EntityOcclusion.setEnabled(!"off".equals(option("entityculling")));
if (!"off".equals(option("instancing")) && !"headless".equals(option("renderer"))) {
ModelBatches.enable();
// Particles too (ADR 0032); ?particlequads=game builds their vertices as the game does.
if (!"game".equals(option("particlequads"))) {
ParticleInstancing.enable();
}
}
// The device's tier (not yet picked from the device): ?tier=potato, standard (the default) or high.
DeviceTier tier = DeviceTier.named(option("tier"));
DeviceTier.set(tier == null ? DeviceTier.STANDARD : tier);
ParticleBudget.setTier(DeviceTier.named(option("particles")));
// The memory diet (ADR 0025): the data fixer is built only if something old arrives.
DataFixing.buildLazily();
// Start-up (ADR 0026): the loading screen fades in half a second, not two, and the
// title screen shows before the block, item and entity models are loaded.
LoadingFade.set(250);
if (!"now".equals(option("models"))) {
DeferredModels.enable();
}
// The memory diet's reuse of world text and its baked-quad writer: ?text=game and
// ?quads=game take the game's own paths, to compare.
TextLayouts.setEnabled(!"game".equals(option("text")));
VertexMath.setQuadsEnabled(!"game".equals(option("quads")));
// ADR 0027's changes, each with the game's (or ADR 0025's) way to compare.
QuadSort.setEnabled(!"game".equals(option("sort")));
ModelBatches.setItemsEnabled(!"game".equals(option("items")));
OpaqueSkins.setEnabled(!"game".equals(option("skins")));
TintBlend.setEnabled(!"game".equals(option("tint")));
// ADR 0030's terrain draw list and sprite animation, each with the game's way to compare.
TerrainDrawLists.setEnabled(!"game".equals(option("drawlists")));
TerrainDrawLists.setFacingCulling(!"all".equals(option("faces")));
AnimatedSprites.setEnabled(!"all".equals(option("animations")));
HudCache.setEnabled(!"live".equals(option("hud")));
// Development: ?modules=minimap,coordinates (or all) turns those modules on at start.
if (!option("modules").isEmpty()) {
IncariModules.startWith(Arrays.asList(option("modules").split(",")));
}
// ADR 0031's changes, each with the game's way to compare.
AmbientParticles.setEnabled(!"game".equals(option("ambient")));
GlyphQuads.setEnabled(!"game".equals(option("glyphs")));
SignLines.setEnabled(!"game".equals(option("signs")));
GraphUpdates.setEnabled(!"game".equals(option("graph")));
ParticleLight.setAcrossFrames(!"frame".equals(option("particlelight")));
// ADR 0032's catch-up ticks spread over frames; ?ticks=game runs them back to back.
TickPacing.setEnabled(!"game".equals(option("ticks")));
// The background pool's least share of a frame while it has work (ADR 0035);
// ?poolfloor=<ms> to compare, 1 being the old minimum.
String poolFloor = option("poolfloor");
WebPlatform.setPoolFloor(poolFloor.isEmpty() ? DEFAULT_POOL_FLOOR_MILLIS : Double.parseDouble(poolFloor));
Collisions.setEnabled(!"game".equals(option("collisions")));
// Singleplayer's server on the page (?singleplayer=page); the worker reads the same options.
StrongholdRings.setEnabled(!"game".equals(option("rings")));
SpawnCosts.setEnabled(!"game".equals(option("spawncosts")));
SpawnCosts.setVerify("verify".equals(option("spawncosts")));
// ADR 0041's world generation and loading changes, each with the game's way to compare.
SurfaceWrites.setEnabled(!"game".equals(option("surface")));
BiomeCells.setEnabled(!"game".equals(option("biomecells")));
BiomeCells.setVerify("verify".equals(option("biomecells")));
Heights.setEnabled(!"game".equals(option("heights")));
CriterionCodecs.setEnabled(!"game".equals(option("criteria")));
// Saved chunks deflated at zlib's fastest level (?deflate=game: its default).
ChunkCompression.setEnabled(!"game".equals(option("deflate")));
// The surface rules' positional randoms drawn without making them (?randoms=game: made).
PositionalRandoms.setEnabled(!"game".equals(option("randoms")));
SurfaceBuffers.setEnabled(!"game".equals(option("surfacebuffers")));
// The Unicode font's glyphs packed into arrays (?unihex=game: an object each, as the game keeps them).
PackedUnihex.setEnabled(!"game".equals(option("unihex")));
// ADR 0042's lazy range choices (the server worker reads the same option).
GoalFlags.setEnabled(!"game".equals(option("goalflags")));
DensityBranches.setEnabled(!"game".equals(option("densitychoices")));
// ADR 0041's packets a flush per message (?packets=each: one each, as before).
ChannelLink.setBatched(!"each".equals(option("packets")));
// ADR 0041's region files left in place for the worker (?inplace=off: handed over whole, as before).
WebFileSystem.setInPlaceHandOver(!"off".equals(option("inplace")));
// ADR 0032's light maps brought up to date in place; ?light=game copies them as the game does.
LightCopies.setEnabled(!"game".equals(option("light")));
LightCopies.setVerify("verify".equals(option("light")));
// ADR 0033: packets their handlers only hand to the game's thread queued without the round
// trip; ?handoff=game calls the handler on the network's thread first, as the game does.
PacketHandoff.setEnabled(!"game".equals(option("handoff")));
// ADR 0039: singleplayer's server in a worker; ?singleplayer=page runs it on the page, as ADR 0038 did.
WorkerWorlds.setEnabled(!"page".equals(option("singleplayer")));
WebGl2Backend.uploadEachUniformWrite("each".equals(option("uniforms")));
WebGl2Backend.movePointersForQuadDraws("off".equals(option("rebase")));
// Development: ?drawcensus logs each pipeline's draws a frame to the console.
WebGl2Backend.countDrawsByPipeline(present("drawcensus"));
// Development: ?gpucensus logs each pipeline's GPU time a frame (ADR 0031).
WebGl2Backend.timeDrawsByPipeline(present("gpucensus"));
// ?copies=all: every WebGL buffer keeps the game's copy, as before ADR 0025, to compare.
WebGl2Backend.keepAllCopies("all".equals(option("copies")));
if ("headless".equals(option("renderer"))) {
GraphicsBackends.install(preference -> new GpuBackend[] {new HeadlessBackend()});
GraphicsBackends.setRendering(false);
} else {
ShaderManifest shaders = WebShaders.load(pack);
boolean eager = "eager".equals(option("shaders"));
boolean multiDraw = !"off".equals(option("multidraw"));
GraphicsBackends.install(preference ->
new GpuBackend[] {new WebGl2Backend(WebPlatform.CANVAS_ID, shaders, eager, multiDraw)});
}
if (present("profile")) {
Profiling.collect(true);
}
if (present("overlay")) {
Profiling.showOverlay(true);
}
String options = option("options");
if (!options.isEmpty()) {
// Development: start with these options (the screenshot-diff harness pins its scenes'
// options this way), in place of whatever the game directory holds.
Path gameDirectory = Path.of(WebStorage.DEFAULT.gameDirectory());
Files.createDirectories(gameDirectory);
Files.write(
gameDirectory.resolve("options.txt"), Fetch.bytes(options, "is the page serving " + options + "?"));
}
if (present("online")) {
// Development: Incari accounts against another service (ADR 0058), ?online=ws://localhost:8080/v1/ws;
// ?online= (empty) turns them off.
IncariOnline.useUrl(option("online"));
}
if ("on".equals(option("updates"))) {
// Testing: the title screen's update notice in a dev build too, ?updates=on (with
// ?online= against tools/onlinedev --release <version>).
UpdateNotice.force(true);
}
String name = option("name");
if (!name.isEmpty() || !option("server").isEmpty()) {
// The page names the player, or joins a server straight away: no Edit Profile first.
PlayerName.fixAtLaunch();
}
List<String> arguments = new ArrayList<>(Arrays.asList(new String[] {
"--version",
ClientJar.VERSION,
"--versionType",
"incari-web",
"--gameDir",
WebStorage.DEFAULT.gameDirectory(),
"--assetsDir",
WebStorage.DEFAULT.assetsDirectory(),
"--accessToken",
"0",
// No profile, user property or chat key requests to Mojang (OnlineServices).
"--offlineDeveloperMode",
"--username",
// A first start suggests a name of its own, as Eagler clients do; Edit Profile keeps it.
name.isEmpty() ? PlayerName.suggest(new Random()) : name
}));
String server = option("server");
if (!server.isEmpty()) {
// Straight into a server, as a launcher's quick play does.
arguments.addAll(List.of("--quickPlayMultiplayer", server));
String via = option("via");
if (!via.isEmpty() && !incari.client.net.ServerVersions.setQuickPlay(server, via)) {
System.err.println("Not a Via choice: ?via=" + via + " (off, auto or a release)");
}
}
String world = option("world");
String seed = option("seed");
if (!world.isEmpty() && !seed.isEmpty()) {
// The singleplayer benchmark's world: made from the seed at the title screen, or opened.
QuickWorlds.createAtTitle(world, Long.parseLong(seed));
} else if (!world.isEmpty()) {
arguments.addAll(List.of("--quickPlaySingleplayer", world));
}
String sharedWorld = option("shared");
int bar = sharedWorld.lastIndexOf('|');
if (bar > 0) {
// The shared-world check's guest (ADR 0062): joins a shared world from the title screen.
QuickWorlds.joinSharedAtTitle(sharedWorld.substring(0, bar), sharedWorld.substring(bar + 1));
}
String share = option("share");
if (!share.isEmpty()) {
// The shared-world check's host (ADR 0062): the world shared on this relay once it's open.
incari.client.singleplayer.WorkerWorlds.shareWhenOpen(share);
}
LoaderPage.status("Starting the game");
net.minecraft.client.main.Main.main(arguments.toArray(String[]::new));
}
/** A query parameter of the page's URL, or "" if it has none. */
@JSBody(params = "name", script = "return new URLSearchParams(location.search).get(name) || '';")
private static native String option(String name);
/** Whether the page's URL has a query parameter, with or without a value. */
@JSBody(params = "name", script = "return new URLSearchParams(location.search).has(name);")
private static native boolean present(String name);
}
@@ -0,0 +1,34 @@
package incari.app.web;
import incari.render.webgl2.shaders.ShaderManifest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* The game's shaders as the build translated them for WebGL2 ({@code tools/shaders}). They're
* translated Mojang files, so like the client jar they're kept beside the page, never built into
* it: in the asset pack ({@link AssetPack}), or as the manifest {@code :app-web:shaders} wrote, which
* {@code :app-web:serve} offers at {@value #URL}.
*/
final class WebShaders {
static final String URL = "shaders.json";
private WebShaders() {}
/**
* The translated shaders: from the asset pack if one is mounted, else fetched from beside
* the page, as an experiment's build without a pack has them.
*/
static ShaderManifest load(boolean fromPack) throws IOException {
double start = Fetch.now();
byte[] bytes = fromPack ? AssetPack.read(URL) : null;
if (bytes == null) {
bytes = Fetch.bytes(URL, "is the development server serving the shaders? run ./gradlew :app-web:shaders");
}
ShaderManifest manifest = ShaderManifest.parse(new String(bytes, StandardCharsets.UTF_8));
System.out.println("[Incari] Shaders: " + manifest.stages().size() + " translated stages loaded "
+ (fromPack ? "from the asset pack " : "") + "in " + Math.round(Fetch.now() - start) + " ms");
return manifest;
}
}
@@ -0,0 +1,13 @@
package incari.app.web;
import incari.platform.api.storage.PlatformStorage;
import org.jspecify.annotations.Nullable;
/** Where the browser build keeps its files: under {@code WebFileSystem.ROOT}, which survives a reload. */
record WebStorage(
String gameDirectory,
String assetsDirectory,
@Nullable String assetIndex) implements PlatformStorage {
static final WebStorage DEFAULT = new WebStorage("/incari/game", "/incari/assets", null);
}
@@ -0,0 +1,36 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.device.GpuBackend;
import com.mojang.renderpearl.api.device.GpuDebugOptions;
import com.mojang.renderpearl.api.device.GpuDevice;
import org.jspecify.annotations.Nullable;
/**
* A graphics backend that draws nothing, for running the game before the browser has a renderer
* (as before the WebGL2 backend existed). Its device accepts every call and keeps no GPU state;
* the entry point also switches the frame's render step off, so the game only ticks.
*/
public final class HeadlessBackend implements GpuBackend {
@Override
public String getName() {
return "Headless";
}
@Override
public void loadLibrary() {}
@Override
public void unloadLibrary() {}
/** The canvas is the window; the handle only has to be non-zero. */
@Override
public long createWindow(@Nullable String title, int width, int height, long flags) {
return 1L;
}
@Override
public GpuDevice createDevice(GpuDebugOptions debugOptions) {
return new HeadlessDevice();
}
}
@@ -0,0 +1,72 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.jspecify.annotations.Nullable;
import org.lwjgl.system.MemoryUtil;
/**
* A buffer as plain memory, allocated when first mapped or written: the game writes uniforms and
* vertices into mapped buffers and sometimes reads them back, so that has to work even with
* nothing to draw. The memory comes from LWJGL's {@code MemoryUtil}, since the game treats mapped
* memory as native ({@code memCopy}, {@code memAddress}); closing frees it.
*/
final class HeadlessBuffer implements GpuBuffer {
private final @GpuBuffer.Usage int usage;
private final long size;
private @Nullable ByteBuffer memory;
private boolean closed;
HeadlessBuffer(@GpuBuffer.Usage int usage, long size) {
this.usage = usage;
this.size = size;
}
@Override
public long size() {
return size;
}
@Override
public @GpuBuffer.Usage int usage() {
return usage;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public GpuBufferSlice.MappedView map(long offset, long length, boolean read, boolean write) {
ByteBuffer view = memory().duplicate().order(ByteOrder.nativeOrder());
view.limit(Math.toIntExact(offset + length)).position(Math.toIntExact(offset));
return new GpuBufferSlice.MappedView(
slice(offset, length), view.slice().order(ByteOrder.nativeOrder()), () -> {});
}
void write(long offset, ByteBuffer data) {
ByteBuffer target = memory().duplicate();
target.position(Math.toIntExact(offset));
target.put(data.duplicate());
}
private ByteBuffer memory() {
ByteBuffer current = memory;
if (current == null) {
current = MemoryUtil.memCalloc(Math.toIntExact(size)).order(ByteOrder.nativeOrder());
memory = current;
}
return current;
}
@Override
public void close() {
closed = true;
MemoryUtil.memFree(memory);
memory = null;
}
}
@@ -0,0 +1,150 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.GpuFormat;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.commands.CommandEncoder;
import com.mojang.renderpearl.api.commands.GpuQueryPool;
import com.mojang.renderpearl.api.device.DeviceFeatures;
import com.mojang.renderpearl.api.device.DeviceInfo;
import com.mojang.renderpearl.api.device.DeviceLimits;
import com.mojang.renderpearl.api.device.DeviceType;
import com.mojang.renderpearl.api.device.GpuDevice;
import com.mojang.renderpearl.api.device.GpuSurface;
import com.mojang.renderpearl.api.device.HintsAndWorkarounds;
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import com.mojang.renderpearl.api.pipeline.ShaderSource;
import com.mojang.renderpearl.api.textures.AddressMode;
import com.mojang.renderpearl.api.textures.FilterMode;
import com.mojang.renderpearl.api.textures.GpuSampler;
import com.mojang.renderpearl.api.textures.GpuTexture;
import com.mojang.renderpearl.api.textures.GpuTextureView;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import org.jspecify.annotations.Nullable;
/**
* A device with no GPU behind it: textures and samplers are descriptions, buffers are plain memory
* (so mapped writes and reads behave), pipelines "compile" at once, and commands do nothing.
*/
final class HeadlessDevice implements GpuDevice {
private static final DeviceInfo INFO = new DeviceInfo(
"Headless",
"Incari",
"none",
false,
"Headless",
1.0F,
new DeviceLimits(1, 256, 8192, 256L * 1024 * 1024, 0, 8, 0),
new DeviceFeatures(false, false, false, false, false, false, false, false),
Set.of(),
new HintsAndWorkarounds(false, false, false, false),
DeviceType.CPU);
private final CommandEncoder encoder = new HeadlessEncoder();
@Override
public GpuSurface createSurface(long windowHandle, BooleanSupplier isIconified) {
return new HeadlessSurface();
}
@Override
public CommandEncoder createCommandEncoder() {
return encoder;
}
@Override
public GpuSampler createSampler(
AddressMode addressModeU,
AddressMode addressModeV,
FilterMode minFilter,
FilterMode magFilter,
int maxAnisotropy,
OptionalDouble maxLod) {
return new HeadlessSampler(addressModeU, addressModeV, minFilter, magFilter, maxAnisotropy, maxLod);
}
@Override
public GpuTexture createTexture(
@Nullable Supplier<String> label,
@GpuTexture.Usage int usage,
GpuFormat format,
int width,
int height,
int depthOrLayers,
int mipLevels) {
return createTexture(
label == null ? null : label.get(), usage, format, width, height, depthOrLayers, mipLevels);
}
@Override
public GpuTexture createTexture(
@Nullable String label,
@GpuTexture.Usage int usage,
GpuFormat format,
int width,
int height,
int depthOrLayers,
int mipLevels) {
return new HeadlessTexture(label == null ? "" : label, usage, format, width, height, depthOrLayers, mipLevels);
}
@Override
public GpuTextureView createTextureView(GpuTexture texture) {
return new HeadlessTextureView(texture, 0, texture.getMipLevels());
}
@Override
public GpuTextureView createTextureView(GpuTexture texture, int baseMipLevel, int mipLevels) {
return new HeadlessTextureView(texture, baseMipLevel, mipLevels);
}
@Override
public GpuBuffer createBuffer(@Nullable Supplier<String> label, @GpuBuffer.Usage int usage, long size) {
return new HeadlessBuffer(usage, size);
}
@Override
public GpuBuffer createBuffer(@Nullable Supplier<String> label, @GpuBuffer.Usage int usage, ByteBuffer data) {
HeadlessBuffer buffer = new HeadlessBuffer(usage, data.remaining());
buffer.write(0, data);
return buffer;
}
@Override
public List<String> getLastDebugMessages() {
return List.of();
}
@Override
public boolean isDebuggingEnabled() {
return false;
}
@Override
public CompletableFuture<CompiledRenderPipeline.Pending> compilePipeline(
RenderPipeline pipeline, ShaderSource shaderSource, Executor executor) {
CompiledRenderPipeline compiled = new HeadlessPipeline();
return CompletableFuture.completedFuture(() -> compiled);
}
@Override
public void close() {}
@Override
public GpuQueryPool createTimestampQueryPool(int size) {
return new HeadlessQueryPool(size);
}
@Override
public DeviceInfo getDeviceInfo() {
return INFO;
}
}

Some files were not shown because too many files have changed in this diff Show More