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
@@ -0,0 +1,6 @@
# app-desktop
- Wiring only: install `platform-desktop`, start the game. Logic belongs in a strict module.
- Running the game needs a GPU and a display; without them it builds but can't run.
- After changing the platform layer or its hooks, run `./gradlew :app-desktop:smokeTest` and read
`run/smoke-host/incari-smoke/report.txt` (and look at the screenshots).
+46
View File
@@ -0,0 +1,46 @@
# app-desktop: the desktop dev runtime
Runs the game on a normal JVM through `platform-desktop`, so game logic can be debugged with a real
debugger and profiler before browser problems get in the way. `DesktopMain` installs the platform
and graphics backends, then starts the game's own `Main`.
```sh
./incari assets # once (~480 MB)
./gradlew :app-desktop:run # play offline in run/; -Pincari.username=<name> skips Edit Profile
```
## Smoke tests
Unattended sessions with injected input. Each needs a display and GPU, writes a report and
screenshots under `run/smoke-*/incari-smoke/`, and halts the JVM if the game hangs. **A task can end
`BUILD SUCCESSFUL` with failed checks: read `report.txt`.**
| Task | Checks |
| --- | --- |
| `smokeTest` | A world: movement, blocks, commands, inventory, chat, sound, LAN, a server ping, pause, quit |
| `smokeHost` + `smokeJoin` | A second client joins the first over LAN |
| `smokeServer -Pincari.server=<addr>` | Join a server, change dimension, reconnect |
| `smokeLegacy` | 1.8 sneaking, reach, cooldown, ladders and sword blocking on a 1.8 server |
| `smokeAuth` | Password login, then login by cookie, on an Eagler server |
| `smokeSkinA` + `smokeSkinB` | Eagler skins both ways |
| `smokeVoiceA` + `smokeVoiceB` | Voice signalling between two clients |
| `smokeOnlineA` + `smokeOnlineB` | Accounts, presence, friends, messages, blocking against an online service (`-Pincari.online`) |
| `smokeMesher` | Incari's mesher against the game's compiler, section by section |
| `smokeModules`, `smokeFeatures`, `smokeHudModules`, `smokeVisualModules`, `smokeScreenModules`, `smokeWaypoints`, `smokeCosmetics` | Modules turned on in a world, with screenshots |
| `smokeHudEditor` | Drag and resize in the HUD editor |
| `smokeScreens`, `smokeLook`, `smokeFit` | Screen edits and skins; the look in both GUI presets; text fitting at GUI scales 2–4 |
| `smokeLayout` | Every Incari screen at six GUI sizes from 320x240, in both fonts: no widget off the screen or over another, no text past its box. Problems in `layout.txt` |
`worldgenServer -Pworldgen=on|off` runs the dedicated server for ADR 0041's world generation check.
## Invariants
- **Wires one game to one platform.** Smoke code runs only when `incari.smoke` is set.
- **An unattended run never leaves a game behind.**
## How to test
```sh
./gradlew :app-desktop:check # the layout rules' unit tests (LayoutRulesTest)
./gradlew :app-desktop:smokeLayout # after changing a screen's layout or Ui's widgets
```
@@ -0,0 +1,384 @@
import java.time.Duration
import groovy.json.JsonSlurper
import java.util.Properties
plugins {
application
}
// The desktop dev runtime: the game on a normal JVM, through platform-desktop.
// `./gradlew :app-desktop:run` starts it offline, with its game directory in run/ (git-ignored).
dependencies {
implementation(project(":client"))
implementation(project(":platform-desktop"))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testRuntimeOnly(libs.junit.launcher)
}
val repoRoot = rootProject.layout.projectDirectory
val minecraftVersion: String = Properties().run {
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
getProperty("minecraft.version")
}
val versionDir = repoRoot.dir("work/cache/versions/$minecraftVersion")
/** This machine's LWJGL natives, as `incari fetch` downloaded them. */
val nativeJars = run {
val root = repoRoot.asFile
providers.fileContents(versionDir.file("natives.txt")).asText.map { text ->
text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) }
}.orElse(emptyList())
}
/** The asset index id from the version JSON; `./incari assets` downloads it. */
val assetIndex = providers.fileContents(versionDir.file("$minecraftVersion.json")).asText.map { text ->
@Suppress("UNCHECKED_CAST")
((JsonSlurper().parseText(text) as Map<String, Any>)["assetIndex"] as Map<String, Any>)["id"] as String
}
application {
applicationName = "incari-desktop"
mainClass = "incari.app.desktop.DesktopMain"
}
/** The launcher's JVM arguments for this version, with this machine's natives. */
val gameJvmArgs = repoRoot.dir("work/natives").asFile.let { natives ->
listOf(
"-Xms2G", "-Xmx4G", "-XX:+UseCompactObjectHeaders", "-XX:+UseZGC",
"-XX:StackShadowPages=32",
"--enable-native-access=ALL-UNNAMED",
"--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED",
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${natives.resolve("lwjgl")}",
"-Dio.netty.native.workdir=${natives.resolve("netty")}",
"-Dminecraft.launcher.brand=incari-dev",
) + if (System.getProperty("os.name").lowercase().startsWith("mac")) {
listOf("-XstartOnFirstThread")
} else emptyList()
}
/**
* Runs the game offline in `gameDir`, the way the launcher would: this machine's natives, the
* launcher's JVM arguments for this version (the version JSON's "jvm" and "default-user-jvm"
* lists, minus other operating systems'), and the downloaded assets.
*/
fun JavaExec.runsGame(gameDir: File, username: Provider<String>, smoke: String?) {
val assetsDir = repoRoot.dir("work/cache/assets").asFile
val version = minecraftVersion
val index = assetIndex
classpath = sourceSets.main.get().runtimeClasspath + files(nativeJars)
mainClass = "incari.app.desktop.DesktopMain"
workingDir = gameDir
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
jvmArgs(gameJvmArgs)
// `-Pincari.browserStartup`: the browser build's start-up on the desktop, to try it with a
// debugger: the data fixer built only when needed, and models loaded after the title.
if (providers.gradleProperty("incari.browserStartup").isPresent) {
systemProperty("incari.browserStartup", "true")
}
if (smoke != null) {
systemProperty("incari.smoke", smoke)
// A backstop behind the smoke test's own watchdog.
timeout = Duration.ofMinutes(15)
}
argumentProviders.add(CommandLineArgumentProvider {
listOf(
"--version", version,
"--versionType", "incari-dev",
"--gameDir", gameDir.path,
"--assetsDir", assetsDir.path,
"--assetIndex", index.get(),
"--accessToken", "0",
"--username", username.get(),
)
})
doFirst {
gameDir.mkdirs()
if (!assetsDir.resolve("indexes/${index.get()}.json").isFile) {
throw GradleException("The game's assets aren't downloaded yet. Run: ./incari assets")
}
}
}
tasks.named<JavaExec>("run") {
description = "Runs the game on the desktop platform, offline, in run/."
runsGame(repoRoot.dir("run").asFile, providers.gradleProperty("incari.username").orElse("Dev"), null)
// A name given here stands; without one, Edit Profile opens first and its saved name is used.
if (providers.gradleProperty("incari.username").isPresent) {
systemProperty("incari.fixedName", "true")
}
// `-Pincari.online=ws://127.0.0.1:8090/v1/ws`: Incari accounts against another service (ADR 0058,
// tools/onlinedev), as the page's ?online= does, without rebuilding the client for a new URL.
providers.gradleProperty("incari.online").orNull?.let { systemProperty("incari.online.url", it) }
// `-Pincari.updates=on`: the title screen's update notice, which only release builds show
// (with tools/onlinedev's `--release <version>`).
providers.gradleProperty("incari.updates").orNull?.let { systemProperty("incari.updates", it) }
// `-Pincari.sceneAgent=<port>`: remote control over a loopback port (SceneAgent), for scripted looks.
providers.gradleProperty("incari.sceneAgent").orNull?.let { systemProperty("incari.sceneAgent", it) }
}
// The smoke test (incari.app.desktop.smoke.SmokeTest): a scripted session, results and
// screenshots in run/smoke-*/incari-smoke/. smokeTest plays alone; smokeHost waits for
// smokeJoin, run at the same time from another terminal, to join its LAN world.
tasks.register<JavaExec>("smokeTest") {
group = "verification"
description = "Plays a scripted session on the desktop runtime and reports what worked."
runsGame(repoRoot.dir("run/smoke-host").asFile, providers.provider { "IncariHost" }, "host")
}
tasks.register<JavaExec>("smokeHost") {
group = "verification"
description = "Like smokeTest, then waits up to three minutes for smokeJoin to join over LAN."
runsGame(repoRoot.dir("run/smoke-host").asFile, providers.provider { "IncariHost" }, "host:180")
}
// Joins a dedicated server, over a WebSocket for a ws:// address (for a vanilla server,
// through tools/wsbridge), changes dimension there and back, disconnects and reconnects. The
// player, IncariSmoke, must be an operator on that server.
tasks.register<JavaExec>("smokeServer") {
group = "verification"
description = "Joins -Pincari.server=<address> (ws://... for WebSocket), changes dimension, reconnects."
val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:8816")
runsGame(repoRoot.dir("run/smoke-server").asFile, providers.provider { "IncariSmoke" }, null)
systemProperty("incari.smoke", "server:" + server.get())
// `-Pincari.wisp=ws://127.0.0.1:6001/`: joins a host:port server through that Wisp proxy (Wispcraft).
providers.gradleProperty("incari.wisp").orNull?.let { systemProperty("incari.smoke.wisp", it) }
timeout = Duration.ofMinutes(15)
}
// Skins both ways on an Eagler server. smokeSkinA and smokeSkinB, run at the same time, each
// set a generated skin (A: slim, with a cape; B: wide), join -Pincari.server=<ws://...>, and check
// the other's arrives from the server and draws as the texture it sent.
listOf("A" to "B", "B" to "A").forEach { (me, peer) ->
tasks.register<JavaExec>("smokeSkin$me") {
group = "verification"
description = "Joins an Eagler server as IncariSkin$me and checks IncariSkin$peer's skin (run with smokeSkin$peer)."
val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:25577")
runsGame(repoRoot.dir("run/smoke-skin-$me").asFile, providers.provider { "IncariSkin$me" }, null)
systemProperty("incari.smoke", "skins:IncariSkin$peer:" + server.get())
timeout = Duration.ofMinutes(15)
}
}
// Incari accounts and chat (ADR 0058, ADR 0059) against a real online service: smokeOnlineA and
// smokeOnlineB, run at the same time, each make an account on -Pincari.online (default a local
// online service, ws://127.0.0.1:8080/v1/ws), join -Pincari.server (default the local 26.3 server,
// 127.0.0.1:25582), see each other as Incari players, become friends, message, block, and delete
// their accounts.
listOf("A" to "B", "B" to "A").forEach { (me, peer) ->
tasks.register<JavaExec>("smokeOnline$me") {
group = "verification"
description = "Accounts and chat as IncariOnline$me with IncariOnline$peer (run with smokeOnline$peer)."
val server = providers.gradleProperty("incari.server").orElse("127.0.0.1:25582")
val online = providers.gradleProperty("incari.online").orElse("ws://127.0.0.1:8080/v1/ws")
runsGame(repoRoot.dir("run/smoke-online-$me").asFile, providers.provider { "IncariOnline$me" }, null)
systemProperty("incari.smoke", "online:IncariOnline$peer:" + server.get())
systemProperty("incari.online.url", online.get())
timeout = Duration.ofMinutes(15)
}
}
// A password login and a cookie on an Eagler server whose auth plugin asks this player
// (AuthEIncari: the EAGLER_SHA256 method) for the password "incari" and then sets a cookie.
tasks.register<JavaExec>("smokeAuth") {
group = "verification"
description = "Logs in to -Pincari.server=<ws://...> with a password, then again by the server's cookie."
val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:25577")
val name = providers.gradleProperty("incari.username").orElse("AuthEIncari")
runsGame(repoRoot.dir("run/smoke-auth").asFile, name, null)
systemProperty("incari.smoke", "auth:" + server.get())
timeout = Duration.ofMinutes(15)
}
// The legacy behaviour layer (ADR 0020) on a 1.8 server (-Pincari.server, default the 1.8.9 server's
// development bridge), checked where the server can tell; -Pincari.rcon is that server's console.
tasks.register<JavaExec>("smokeLegacy") {
group = "verification"
description = "Checks 1.8's sneaking, pick margin, cooldown, ladders and sword blocking on a 1.8 server."
val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:8801")
val rcon = providers.gradleProperty("incari.rcon").orElse("127.0.0.1:25611")
runsGame(repoRoot.dir("run/smoke-legacy").asFile, providers.provider { "IncariLegacy" }, null)
systemProperty("incari.smoke", "legacy:" + server.get())
systemProperty("incari.rcon", rcon.get())
timeout = Duration.ofMinutes(15)
}
// Voice chat's signalling on an Eagler server with voice on, with WebRTC scripted on the
// desktop (which has none): smokeVoiceA and smokeVoiceB, run together, turn global voice on and
// check the server pairs them.
listOf("A" to "B", "B" to "A").forEach { (me, peer) ->
tasks.register<JavaExec>("smokeVoice$me") {
group = "verification"
description = "Joins an Eagler server as IncariVoice$me and checks voice pairs it with IncariVoice$peer."
val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:25577")
runsGame(repoRoot.dir("run/smoke-voice-$me").asFile, providers.provider { "IncariVoice$me" }, null)
systemProperty("incari.smoke", "voice:IncariVoice$peer:" + server.get())
timeout = Duration.ofMinutes(15)
}
}
// The module menu (ADR 0046), Toggle Sprint in a world, the profile saved.
tasks.register<JavaExec>("smokeModules") {
group = "verification"
description = "Opens the module menu, latches sprint with Toggle Sprint, and screenshots the module screens."
runsGame(repoRoot.dir("run/smoke-modules").asFile, providers.provider { "IncariSmoke" }, "modules")
}
// The client's look (ADR 0048), both GUI presets, on the screens players see most.
tasks.register<JavaExec>("smokeLook") {
group = "verification"
description = "Screenshots the title, options, lists, module menu, pause menu and inventory in both GUI presets."
runsGame(repoRoot.dir("run/smoke-look").asFile, providers.provider { "IncariSmoke" }, "look")
}
// Text that must fit its box, at GUI scale 2, 3 and 4 in a Chromebook-sized window, and the
// narrowest layouts at 3 in smaller windows.
tasks.register<JavaExec>("smokeFit") {
group = "verification"
description = "Screenshots screens with long or player-chosen text at GUI scale 2, 3 and 4 in a 1366x768 window, and at 3 in 1280x720 and 1024x768."
runsGame(repoRoot.dir("run/smoke-fit").asFile, providers.provider { "IncariSmoke" }, "fit")
args("--width", "1366", "--height", "768")
}
// Every screen's layout judged at the GUI sizes players get, from 320x240 up, in both fonts: a
// widget off the screen or over another, or text past its box, fails. Problems in layout.txt.
tasks.register<JavaExec>("smokeLayout") {
group = "verification"
description = "Checks every Incari screen's layout at six GUI sizes from 320x240, in both fonts."
runsGame(repoRoot.dir("run/smoke-layout").asFile, providers.provider { "IncariSmoke" }, "layout")
}
// The HUD editor (ADR 0049) from the module menu, dragged and resized in both GUI presets.
tasks.register<JavaExec>("smokeHudEditor") {
group = "verification"
description = "Opens the HUD editor from the module menu, drags and resizes Toggle Sprint's line, checks Potato's backdrop rate."
runsGame(repoRoot.dir("run/smoke-hudeditor").asFile, providers.provider { "IncariSmoke" }, "hudeditor")
}
// ADR 0050: the first modules in a world: armor and effects, a moved sidebar, chat, fire.
tasks.register<JavaExec>("smokeFeatures") {
group = "verification"
description = "Turns on Armor & Potion View, Custom Scoreboard, Clear Chat, Low Fire and No Hurt Cam in a world and screenshots them."
runsGame(repoRoot.dir("run/smoke-features").asFile, providers.provider { "IncariSmoke" }, "features")
}
// ADR 0051: the minimap and waypoints in a world, their screens, a death's waypoint.
tasks.register<JavaExec>("smokeWaypoints") {
group = "verification"
description = "Turns on Minimap and Waypoints in a world with waypoints round the player and screenshots them and their screens."
runsGame(repoRoot.dir("run/smoke-waypoints").asFile, providers.provider { "IncariSmoke" }, "waypoints")
}
// ADR 0052: the HUD modules (Keystrokes, CPS, FPS, Reach, Coordinates, Shield & Totem) in a world.
tasks.register<JavaExec>("smokeHudModules") {
group = "verification"
description = "Turns on the HUD modules of ADR 0052 in a world, clicks a mob and holds keys, and screenshots them."
runsGame(repoRoot.dir("run/smoke-hudmodules").asFile, providers.provider { "IncariSmoke" }, "hudmodules")
}
// ADR 0053: the visual modules (Crosshair, Cooldown, Weather, Freelook, Low Shield, 1.7 Animations), Hitboxes and Schematics.
tasks.register<JavaExec>("smokeVisualModules") {
group = "verification"
description = "Runs the visual and combat modules of ADR 0053, Hitboxes and Schematics in a world and screenshots them."
runsGame(repoRoot.dir("run/smoke-visualmodules").asFile, providers.provider { "IncariSmoke" }, "visualmodules")
}
// ADR 0054: Shulker Tooltips, Screenshot Manager and Theme Editor.
tasks.register<JavaExec>("smokeScreenModules") {
group = "verification"
description = "Runs Shulker Tooltips, Screenshot Manager and Theme Editor and screenshots them."
runsGame(repoRoot.dir("run/smoke-screenmodules").asFile, providers.provider { "IncariSmoke" }, "screenmodules")
}
// ADR 0061: cosmetics worn, the Wardrobe, emotes and the emote wheel.
tasks.register<JavaExec>("smokeCosmetics") {
group = "verification"
description = "Wears cosmetics on the title screen and in a world, plays emotes and screenshots the Wardrobe."
runsGame(repoRoot.dir("run/smoke-cosmetics").asFile, providers.provider { "IncariSmoke" }, "cosmetics")
}
tasks.register<JavaExec>("smokeScreens") {
group = "verification"
description = "Screenshots the screens M2 adds (the edit-server screen's Version button, Edit Profile), edits, replaces and skins game screens (ADR 0047)."
runsGame(repoRoot.dir("run/smoke-screens").asFile, providers.provider { "IncariSmoke" }, "screens")
}
// ADR 0023: every section meshed by the game's compiler and by Incari's mesher, compared, over
// terrain of every kind, every dimension and the debug world's every block state.
tasks.register<JavaExec>("smokeMesher") {
group = "verification"
description = "Meshes varied worlds with both the game's compiler and Incari's mesher and compares them."
runsGame(repoRoot.dir("run/smoke-mesher").asFile, providers.provider { "IncariMesher" }, "mesher")
systemProperty("incari.mesher", "verify")
timeout = Duration.ofMinutes(45)
}
tasks.register<JavaExec>("smokeJoin") {
group = "verification"
description = "Joins smokeHost's LAN world through the platform transport."
runsGame(repoRoot.dir("run/smoke-join").asFile, providers.provider { "IncariGuest" }, "join:127.0.0.1:25577")
}
// How the screenshot-diff harness (tools/webbuild's ScreenshotDiff, `:app-web:screenshotDiff`)
// starts this game to render its reference images with Mojang's OpenGL backend. One line per
// token: `java <path>`, `jvm <argument>`, `classpath <entry>`, `main <class>`, `arg <argument>`;
// the harness adds the game directory, the player, the server and its remote-control port.
tasks.register("sceneLaunch") {
group = "verification"
description = "Writes build/scene-launch.txt: how the screenshot-diff harness starts the desktop game."
val classpath = sourceSets.main.get().runtimeClasspath + files(nativeJars)
val launcher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
val output = layout.buildDirectory.file("scene-launch.txt")
val jvm = gameJvmArgs
val version = minecraftVersion
val index = assetIndex
val assetsDir = repoRoot.dir("work/cache/assets").asFile
inputs.files(classpath)
inputs.property("jvm", jvm)
outputs.file(output)
doLast {
val lines = mutableListOf("java " + launcher.get().executablePath.asFile.path)
jvm.forEach { lines.add("jvm $it") }
classpath.files.forEach { lines.add("classpath " + it.path) }
lines.add("main incari.app.desktop.DesktopMain")
listOf("--version", version, "--versionType", "incari-dev", "--assetsDir", assetsDir.path,
"--assetIndex", index.get(), "--accessToken", "0").forEach { lines.add("arg $it") }
output.get().asFile.writeText(lines.joinToString("\n", postfix = "\n"))
}
}
// ADR 0041: the game's dedicated server with the browser build's world generation changes on or
// off (-Pworldgen=on|off), in run/worldgen-<on|off>/ from server.properties' seed, typing
// tools/worldgen/script.txt into its console. tools/worldgen/compare.py compares the two worlds.
tasks.register<JavaExec>("worldgenServer") {
group = "verification"
description = "Runs the dedicated server with ADR 0041's world generation changes on or off (-Pworldgen=on|off)."
val mode = providers.gradleProperty("worldgen").orElse("off")
val serverDir = mode.map { repoRoot.dir("run/worldgen-$it").asFile }
classpath = sourceSets.main.get().runtimeClasspath + files(nativeJars)
mainClass = "incari.app.desktop.smoke.WorldgenServer"
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
jvmArgs(gameJvmArgs)
systemProperty("incari.worldgen", mode.get())
systemProperty("incari.worldgen.script", repoRoot.file("tools/worldgen/script.txt").asFile.path)
// One background thread (-Pworldgen.threads=1): chunks generate in one order, so the features
// one chunk places in its neighbours land the same way each run.
providers.gradleProperty("worldgen.threads").orNull?.let { systemProperty("max.bg.threads", it) }
if (providers.gradleProperty("worldgen.verify").isPresent) {
systemProperty("incari.worldgen.verify", "true")
}
val dir = serverDir.get()
val properties = repoRoot.file("tools/worldgen/server.properties").asFile
workingDir = dir
args("--nogui", "--universe", dir.path)
timeout = Duration.ofMinutes(20)
doFirst {
dir.deleteRecursively()
dir.mkdirs()
dir.resolve("eula.txt").writeText("eula=true\n")
properties.copyTo(dir.resolve("server.properties"))
}
}
@@ -0,0 +1,91 @@
package incari.app.desktop;
import com.mojang.blaze3d.platform.NativeLibrariesBootstrap;
import com.mojang.renderpearl.api.device.GpuBackend;
import com.mojang.renderpearl.backend.opengl.GlBackend;
import com.mojang.renderpearl.backend.vulkan.VulkanBackend;
import incari.app.desktop.smoke.SceneAgent;
import incari.app.desktop.smoke.SmokeTest;
import incari.client.datafix.DataFixing;
import incari.client.platform.GraphicsBackends;
import incari.client.platform.PlatformLifecycle;
import incari.client.profile.PlayerName;
import incari.client.startup.DeferredModels;
import incari.platform.api.PlatformLog;
import incari.platform.api.Platforms;
import incari.platform.desktop.DesktopPlatform;
import incari.platform.desktop.DesktopStorage;
import java.util.List;
import net.minecraft.client.PreferredGraphicsApi;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Starts the game on the desktop platform: installs {@link DesktopPlatform} and the desktop's
* graphics backends, then hands over to the game's own {@code Main} with the same arguments a
* launcher passes.
*/
public final class DesktopMain {
private DesktopMain() {}
public static void main(String[] args) {
List<String> arguments = List.of(args);
DesktopStorage storage = new DesktopStorage(
optionValue(arguments, "--gameDir", "."),
optionValue(arguments, "--assetsDir", "assets"),
nullableOptionValue(arguments, "--assetIndex"));
Logger logger = LoggerFactory.getLogger("Platform");
DesktopPlatform platform = new DesktopPlatform(storage, slf4j(logger), logger.isDebugEnabled());
SmokeTest.configurePlatform(platform);
Platforms.install(platform);
GraphicsBackends.install(DesktopMain::desktopBackends);
GraphicsBackends.installVulkanCheck(VulkanBackend::checkBackendAvailable);
PlatformLifecycle.setNativeLibraryLoader(NativeLibrariesBootstrap::loadLibraries);
if (Boolean.getBoolean("incari.browserStartup")) {
// The browser build's start-up, to try it here: -Pincari.browserStartup.
DataFixing.buildLazily();
DeferredModels.enable();
}
if (System.getProperty("incari.smoke") != null
|| System.getProperty("incari.sceneAgent") != null
|| Boolean.getBoolean("incari.fixedName")) {
// Tests, and -Pincari.username, name the player: no Edit Profile at start-up.
PlayerName.fixAtLaunch();
}
SmokeTest.startIfRequested(storage.gameDirectory());
SceneAgent.startIfRequested();
net.minecraft.client.main.Main.main(args);
}
/** OpenGL first, as vanilla does, unless the player chose Vulkan; the other is the fallback. */
private static GpuBackend[] desktopBackends(PreferredGraphicsApi preference) {
GpuBackend opengl = new GlBackend();
GpuBackend vulkan = new VulkanBackend();
return preference == PreferredGraphicsApi.VULKAN
? new GpuBackend[] {vulkan, opengl}
: new GpuBackend[] {opengl, vulkan};
}
private static PlatformLog slf4j(Logger logger) {
return (level, message, error) -> {
switch (level) {
case DEBUG -> logger.debug(message, error);
case INFO -> logger.info(message, error);
case WARN -> logger.warn(message, error);
case ERROR -> logger.error(message, error);
}
};
}
private static String optionValue(List<String> arguments, String option, String fallback) {
String value = nullableOptionValue(arguments, option);
return value == null ? fallback : value;
}
private static @Nullable String nullableOptionValue(List<String> arguments, String option) {
int at = arguments.indexOf(option);
return at >= 0 && at + 1 < arguments.size() ? arguments.get(at + 1) : null;
}
}
@@ -0,0 +1,5 @@
/** The desktop dev runtime's entry point. */
@NullMarked
package incari.app.desktop;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,210 @@
package incari.app.desktop.smoke;
import incari.app.desktop.smoke.LayoutRules.Box;
import incari.client.ui.GuiSkin;
import incari.client.ui.Skins;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.events.ContainerEventHandler;
import net.minecraft.client.gui.navigation.ScreenRectangle;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.state.gui.GuiRenderState;
import net.minecraft.client.renderer.state.gui.GuiTextRenderState;
import net.minecraft.resources.Identifier;
import net.minecraft.util.FormattedCharSequence;
import org.jspecify.annotations.Nullable;
/**
* A screen's layout as drawn: one frame of it extracted off the window, with the pointer away,
* recording where each widget and each run of text landed, for {@link LayoutRules} to judge.
* Widgets are seen through a {@link GuiSkin} that records and passes everything on to the skin in
* use; text through the frame's text states, measured as layouts measure it. Game thread.
*/
final class LayoutCheck {
private LayoutCheck() {}
/** What's wrong with the screen shown now, in words; empty if its layout is fine. */
static List<String> problems(Minecraft minecraft, Screen screen) {
GuiRenderState state = new GuiRenderState();
GuiGraphicsExtractor graphics = new GuiGraphicsExtractor(minecraft, state, -1, -1);
Recorder recorder = new Recorder(Skins.current());
Skins.use(recorder);
try {
screen.extractRenderStateWithTooltipAndSubtitles(graphics, -1, -1, 0);
} finally {
Skins.use(recorder.inner);
}
List<Box> texts = new ArrayList<>();
state.forEachText(text -> {
Box box = laidOut(text);
if (box != null) {
texts.add(box);
}
});
return LayoutRules.problems(
graphics.guiWidth(), graphics.guiHeight(), scrolls(screen), recorder.widgets, texts);
}
/** The account screens' panel scrolls when it's taller than the screen ({@code FormScreen}). */
private static boolean scrolls(Screen screen) {
for (Class<?> type = screen.getClass(); type != null; type = type.getSuperclass()) {
if (type.getName().equals("incari.client.online.FormScreen")) {
return true;
}
}
return false;
}
private static Box box(String what, ScreenRectangle rectangle) {
return new Box(what, rectangle.left(), rectangle.top(), rectangle.right(), rectangle.bottom());
}
private static String describe(AbstractWidget widget) {
Class<?> type = widget.getClass();
while (type.getSimpleName().isEmpty()) {
type = type.getSuperclass();
}
return type.getSimpleName() + " \"" + shortened(widget.getMessage().getString()) + "\"";
}
private static String shortened(String text) {
return text.length() <= 40 ? text : text.substring(0, 37) + "...";
}
/**
* Where a run of text was laid out: its font's width by its line height, as the screen measured
* it, cut to its clip; null if the clip hides it. Not the glyphs' own box, which takes in the
* shadow and, in the pixel font, some padding, so it reaches past where any layout put it.
*/
private static @Nullable Box laidOut(GuiTextRenderState state) {
Font font = field(state, "font", Font.class);
FormattedCharSequence text = field(state, "text", FormattedCharSequence.class);
int x = field(state, "x", Integer.class);
int y = field(state, "y", Integer.class);
ScreenRectangle laid =
new ScreenRectangle(x, y, font.width(text), font.lineHeight).transformMaxBounds(state.pose);
ScreenRectangle shown = state.scissor != null ? state.scissor.intersection(laid) : laid;
if (shown == null) {
return null;
}
StringBuilder words = new StringBuilder();
text.accept((position, style, codepoint) -> {
words.appendCodePoint(codepoint);
return true;
});
return box("text \"" + shortened(words.toString()) + "\"", shown);
}
/** A text state keeps what it draws to itself. */
private static <T> T field(GuiTextRenderState state, String name, Class<T> type) {
try {
Field field = GuiTextRenderState.class.getDeclaredField(name);
field.setAccessible(true);
return type.cast(field.get(state));
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("GuiTextRenderState has no " + name, e);
}
}
/** Records each widget drawn, cut to its clip, and hands every call on to {@code inner}. */
private static final class Recorder implements GuiSkin {
final @Nullable GuiSkin inner;
final List<Box> widgets = new ArrayList<>();
Recorder(@Nullable GuiSkin inner) {
this.inner = inner;
}
@Override
public boolean widget(GuiGraphicsExtractor graphics, AbstractWidget widget, int mouseX, int mouseY, float a) {
// A list or a panel is judged by what's in it, not as one widget over its rows.
if (!(widget instanceof ContainerEventHandler)) {
ScreenRectangle drawn = widget.getRectangle();
ScreenRectangle clip = graphics.incariScissor();
ScreenRectangle shown = clip != null ? clip.intersection(drawn) : drawn;
if (shown != null) {
widgets.add(box(describe(widget), shown));
}
}
return inner != null && inner.widget(graphics, widget, mouseX, mouseY, a);
}
@Override
public boolean sprite(
GuiGraphicsExtractor graphics, Identifier sprite, int x, int y, int width, int height, int color) {
return inner != null && inner.sprite(graphics, sprite, x, y, width, height, color);
}
@Override
public boolean spritePart(
GuiGraphicsExtractor graphics,
Identifier sprite,
int spriteWidth,
int spriteHeight,
int textureX,
int textureY,
int x,
int y,
int width,
int height,
int color) {
return inner != null
&& inner.spritePart(
graphics,
sprite,
spriteWidth,
spriteHeight,
textureX,
textureY,
x,
y,
width,
height,
color);
}
@Override
public boolean texture(
GuiGraphicsExtractor graphics,
Identifier texture,
int x,
int y,
int width,
int height,
float u,
float v,
int srcWidth,
int srcHeight,
int textureWidth,
int textureHeight,
int color) {
return inner != null
&& inner.texture(
graphics,
texture,
x,
y,
width,
height,
u,
v,
srcWidth,
srcHeight,
textureWidth,
textureHeight,
color);
}
@Override
public boolean background(GuiGraphicsExtractor graphics, Screen screen, float a) {
return inner != null && inner.background(graphics, screen, a);
}
}
}
@@ -0,0 +1,113 @@
package incari.app.desktop.smoke;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* What a screen drawn at one size must not do, from where its widgets and text landed (GUI
* units, already cut to any clip they were drawn in): a widget off the screen or over another, text
* past the widget it's in, over a widget it isn't in, over other text, or off the screen. The
* geometry only; {@link LayoutCheck} gathers the boxes from a frame.
*/
final class LayoutRules {
/**
* Text's measured box takes in its shadow and anti-aliased edge, which may reach this far
* past where a layout put it without anyone seeing a problem.
*/
static final int SLACK = 1;
private LayoutRules() {}
/** A widget or a run of text, as drawn: {@code x1} and {@code y1} are exclusive. */
record Box(String what, int x0, int y0, int x1, int y1) {
boolean isEmpty() {
return x1 <= x0 || y1 <= y0;
}
/** Whether {@code other} is inside this, give or take {@code slack}. */
boolean holds(Box other, int slack) {
return other.x0 >= x0 - slack && other.y0 >= y0 - slack && other.x1 <= x1 + slack && other.y1 <= y1 + slack;
}
/** Whether this and {@code other} share more than {@code slack} each way. */
boolean overlaps(Box other, int slack) {
return Math.min(x1, other.x1) - Math.max(x0, other.x0) > slack
&& Math.min(y1, other.y1) - Math.max(y0, other.y0) > slack;
}
boolean containsPoint(int x, int y) {
return x >= x0 && x < x1 && y >= y0 && y < y1;
}
@Override
public String toString() {
return what + " at " + x0 + "," + y0 + " " + (x1 - x0) + "x" + (y1 - y0);
}
}
/** Everything wrong with one screen at {@code width} by {@code height}, in words; empty if fine. */
static List<String> problems(int width, int height, List<Box> widgets, List<Box> texts) {
return problems(width, height, false, widgets, texts);
}
/**
* {@link #problems(int, int, List, List)} for a screen that may scroll its contents up
* ({@code scrolls}): what's below its bottom edge is reached by scrolling, not cut off.
*/
static List<String> problems(int width, int height, boolean scrolls, List<Box> widgets, List<Box> texts) {
Box screen = new Box("the screen", 0, 0, width, scrolls ? Integer.MAX_VALUE / 2 : height);
List<String> found = new ArrayList<>();
List<Box> shown = widgets.stream().filter(box -> !box.isEmpty()).toList();
List<Box> words = texts.stream().filter(box -> !box.isEmpty()).toList();
for (int i = 0; i < shown.size(); i++) {
Box widget = shown.get(i);
if (!screen.holds(widget, 0)) {
found.add(widget + " runs off the screen");
}
for (int j = i + 1; j < shown.size(); j++) {
if (widget.overlaps(shown.get(j), 0)) {
found.add(widget + " overlaps " + shown.get(j));
}
}
}
for (int i = 0; i < words.size(); i++) {
Box text = words.get(i);
if (!screen.holds(text, SLACK)) {
found.add(text + " runs off the screen");
}
Box owner = owner(text, shown);
if (owner != null) {
if (!owner.holds(text, SLACK)) {
found.add(text + " runs past " + owner);
}
} else {
for (Box widget : shown) {
if (text.overlaps(widget, SLACK)) {
found.add(text + " runs into " + widget);
}
}
}
for (int j = i + 1; j < words.size(); j++) {
if (text.overlaps(words.get(j), SLACK)) {
found.add(text + " overlaps " + words.get(j));
}
}
}
return found;
}
/** The widget text starts in: where its first letter's middle is. */
private static @Nullable Box owner(Box text, List<Box> widgets) {
int x = text.x0 + SLACK;
int y = (text.y0 + text.y1) / 2;
for (Box widget : widgets) {
if (widget.containsPoint(x, y)) {
return widget;
}
}
return null;
}
}
@@ -0,0 +1,69 @@
package incari.app.desktop.smoke;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
/**
* A game server's remote console, for smoke scenarios that set up the world: one command per
* connection, which is plenty for a test. The protocol: little-endian length, id and type, the
* body, two zero bytes; type 3 logs in, type 2 runs a command.
*/
final class Rcon {
private final String host;
private final int port;
private final String password;
Rcon(String address, String password) {
int colon = address.lastIndexOf(':');
this.host = address.substring(0, colon);
this.port = Integer.parseInt(address.substring(colon + 1));
this.password = password;
}
/** Runs {@code command} and returns the server's reply. */
String run(String command) throws IOException {
try (Socket socket = new Socket(host, port)) {
socket.setSoTimeout(5000);
OutputStream out = socket.getOutputStream();
DataInputStream in = new DataInputStream(socket.getInputStream());
out.write(packet(1, 3, password));
if (read(in).id == -1) {
throw new IOException("RCON refused the password");
}
out.write(packet(2, 2, command));
return read(in).body;
}
}
private record Reply(int id, String body) {}
private static byte[] packet(int id, int type, String body) {
byte[] text = body.getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.allocate(14 + text.length).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(10 + text.length)
.putInt(id)
.putInt(type)
.put(text)
.put((byte) 0)
.put((byte) 0);
return buffer.array();
}
private static Reply read(DataInputStream in) throws IOException {
byte[] head = new byte[12];
in.readFully(head);
ByteBuffer buffer = ByteBuffer.wrap(head).order(ByteOrder.LITTLE_ENDIAN);
int length = buffer.getInt();
int id = buffer.getInt();
buffer.getInt();
byte[] body = new byte[length - 8];
in.readFully(body);
return new Reply(id, new String(body, 0, Math.max(0, body.length - 2), StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,179 @@
package incari.app.desktop.smoke;
import com.mojang.blaze3d.platform.NativeImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Screenshot;
import org.jspecify.annotations.Nullable;
import org.lwjgl.sdl.SDLVideo;
/**
* Remote control for the screenshot-diff harness ({@code tools/webbuild}'s
* {@code ScreenshotDiff}): the harness renders the same scenes here, with Mojang's OpenGL backend,
* and in the browser, and compares the two. It drives this game over a line protocol on a loopback
* port, the way it drives the browser over the DevTools protocol:
*
* <ul>
* <li>{@code state}: {@code world} when a world is shown with no screen open, {@code screen} with
* a screen over it, {@code menu} otherwise
* <li>{@code key <scancode> <keycode> <down|up>}: a key, as SDL reports it
* <li>{@code move <x> <y>} and {@code click <x> <y>}: the pointer, in fractions of the window
* <li>{@code type <text>}: text typed into whatever has the focus, as SDL's text input reports it
* <li>{@code shot <path>}: the main render target, as a PNG (what the window shows, before
* scaling); answers {@code ok <width> <height>}
* </ul>
*
* Every answer is one line, {@code ok ...} or {@code error <why>}. Off unless
* {@code -Dincari.sceneAgent=<port>}; development tooling, never in a build players get.
*/
public final class SceneAgent {
private final Minecraft minecraft;
private @Nullable SdlInjector input;
private SceneAgent(Minecraft minecraft) {
this.minecraft = minecraft;
}
/** Listens on the port {@code incari.sceneAgent} names, if it's set, on a thread of its own. */
public static void startIfRequested() {
String port = System.getProperty("incari.sceneAgent");
if (port == null || port.isBlank()) {
return;
}
Thread.ofPlatform().name("Incari scene agent").daemon().start(() -> {
try (ServerSocket server = new ServerSocket(Integer.parseInt(port), 1, InetAddress.getLoopbackAddress())) {
Minecraft minecraft = waitForGame();
SceneAgent agent = new SceneAgent(minecraft);
while (true) {
try (Socket socket = server.accept()) {
agent.serve(socket);
}
}
} catch (IOException e) {
org.slf4j.LoggerFactory.getLogger("Scene agent").error("The scene agent stopped", e);
}
});
}
private void serve(Socket socket) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
String line;
while ((line = in.readLine()) != null) {
String answer;
try {
answer = "ok" + run(line.strip().split(" ", -1));
} catch (RuntimeException | IOException e) {
answer = "error " + e.toString().replace('\n', ' ');
}
out.println(answer);
}
}
private String run(String[] command) throws IOException {
return switch (command[0]) {
case "state" -> " " + onGameThread(this::state);
case "key" -> {
injector().key(Integer.parseInt(command[1]), Integer.parseInt(command[2]), command[3].equals("down"));
yield "";
}
case "move", "click" -> {
float[] size = onGameThread(() -> new float[] {
minecraft.getWindow().getScreenWidth(),
minecraft.getWindow().getScreenHeight()
});
SdlInjector injector = injector();
injector.moveTo(Float.parseFloat(command[1]) * size[0], Float.parseFloat(command[2]) * size[1]);
if (command[0].equals("click")) {
injector.mouseButton(1, true);
injector.mouseButton(1, false);
}
yield "";
}
case "type" -> {
injector().text(String.join(" ", java.util.Arrays.copyOfRange(command, 1, command.length)));
yield "";
}
case "shot" -> " " + shot(Path.of(command[1]));
default -> throw new IllegalArgumentException("Unknown command " + command[0]);
};
}
private String state() {
if (minecraft.level == null || minecraft.player == null) {
return "menu";
}
return minecraft.gui.screen() == null ? "world" : "screen";
}
private String shot(Path file) throws IOException {
Path parent = file.toAbsolutePath().getParent();
if (parent != null) {
Files.createDirectories(parent);
}
CompletableFuture<String> written = new CompletableFuture<>();
onGameThread(() -> {
Screenshot.takeScreenshot(minecraft.gameRenderer.mainRenderTarget(), image -> {
try (NativeImage owned = image) {
owned.writeToFile(file);
written.complete(owned.getWidth() + " " + owned.getHeight());
} catch (IOException | RuntimeException e) {
written.completeExceptionally(e);
}
});
return "";
});
try {
return written.get(1, TimeUnit.MINUTES);
} catch (Exception e) {
throw new IOException("The screenshot wasn't written", e);
}
}
private SdlInjector injector() {
SdlInjector current = input;
if (current == null) {
int windowId = onGameThread(
() -> SDLVideo.SDL_GetWindowID(minecraft.getWindow().handle()));
current = new SdlInjector(windowId);
current.focus();
input = current;
}
return current;
}
private <T> T onGameThread(java.util.function.Supplier<T> task) {
try {
return minecraft.submit(task).get(1, TimeUnit.MINUTES);
} catch (Exception e) {
throw new IllegalStateException("A scene agent command failed on the game thread", e);
}
}
private static Minecraft waitForGame() {
while (true) {
Minecraft instance = Minecraft.getInstance();
if (instance != null) {
return instance;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted", e);
}
}
}
}
@@ -0,0 +1,139 @@
package incari.app.desktop.smoke;
import incari.platform.api.net.NetConnection;
import incari.platform.api.rtc.IceServer;
import incari.platform.api.rtc.Microphone;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.rtc.RemoteVoice;
import incari.platform.api.rtc.RtcPeer;
import java.util.List;
/**
* WebRTC's stand-in on the desktop, for the voice smoke test: peers exchange made-up
* descriptions and candidates, carried by the real server's signalling, and report the peer's
* audio once both descriptions and a candidate from the far side have come through. No audio flows;
* the browser checks cover that. Listener calls come on the game's thread, as in the browser.
*/
final class ScriptedRtc implements PlatformRtc {
private boolean micOpen;
@Override
public boolean supported() {
return true;
}
/** As the browser's callbacks do: later, on the game's thread. */
private static void later(Runnable action) {
net.minecraft.client.Minecraft.getInstance().execute(action);
}
@Override
public Microphone microphone() {
return new Microphone() {
@Override
public State state() {
return micOpen ? State.OPEN : State.CLOSED;
}
@Override
public void open() {
micOpen = true;
}
@Override
public void close() {
micOpen = false;
}
@Override
public void setTransmitting(boolean transmitting) {}
@Override
public void setVolume(float volume) {}
@Override
public float level() {
return 0;
}
};
}
@Override
public RtcPeer createPeer(List<IceServer> iceServers, RtcPeer.Listener listener) {
return new RtcPeer() {
private boolean local;
private boolean remote;
private boolean candidate;
private boolean audio;
private boolean closed;
@Override
public void sendMicrophone() {}
@Override
public NetConnection openDataChannel(String label, NetConnection.Listener channel) {
throw new UnsupportedOperationException("Voice only");
}
@Override
public void createOffer() {
local = true;
later(() -> {
listener.localDescription("{\"type\":\"offer\",\"sdp\":\"scripted\"}");
listener.iceCandidate("candidate:1 1 udp 1 127.0.0.1 9 typ host", 0);
});
}
@Override
public void setRemoteDescription(String json) {
remote = true;
if (json.contains("offer")) {
local = true;
later(() -> {
listener.localDescription("{\"type\":\"answer\",\"sdp\":\"scripted\"}");
listener.iceCandidate("candidate:2 1 udp 1 127.0.0.1 9 typ host", 0);
});
}
check();
}
@Override
public void addIceCandidate(String line, int sdpMLineIndex) {
candidate = true;
check();
}
private void check() {
if (local && remote && candidate && !audio && !closed) {
audio = true;
later(() -> {
listener.stateChanged("connected");
listener.remoteAudio();
});
}
}
@Override
public RemoteVoice voice() {
return new RemoteVoice() {
@Override
public void setVolume(float volume) {}
@Override
public void setPan(float pan) {}
@Override
public float level() {
return 0;
}
};
}
@Override
public void close() {
closed = true;
}
};
}
}
@@ -0,0 +1,91 @@
package incari.app.desktop.smoke;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.sdl.SDLEvents;
import org.lwjgl.sdl.SDL_Event;
import org.lwjgl.system.MemoryUtil;
/**
* Pushes synthetic events into SDL's queue, so the smoke test's input takes the same path a
* player's does: SDL's queue, the desktop platform's event pump, the game's event handler.
*/
final class SdlInjector implements AutoCloseable {
private final int windowId;
/** Text events point at UTF-8 strings SDL reads later; they stay alive until close. */
private final List<ByteBuffer> texts = new ArrayList<>();
SdlInjector(int windowId) {
this.windowId = windowId;
}
void focus() {
push(event -> event.window(
w -> w.type(SDLEvents.SDL_EVENT_WINDOW_FOCUS_GAINED).windowID(windowId)));
}
/**
* @param scancode the physical key (a HID usage id)
* @param keyCode what it types in a US layout (SDL keycode)
*/
void key(int scancode, int keyCode, boolean down) {
push(event -> event.key(k -> k.type(down ? SDLEvents.SDL_EVENT_KEY_DOWN : SDLEvents.SDL_EVENT_KEY_UP)
.windowID(windowId)
.scancode(scancode)
.key(keyCode)
.down(down)));
}
void tap(int scancode, int keyCode) {
key(scancode, keyCode, true);
key(scancode, keyCode, false);
}
void text(String text) {
ByteBuffer utf8 = MemoryUtil.memUTF8(text);
texts.add(utf8);
push(event -> event.text(
t -> t.type(SDLEvents.SDL_EVENT_TEXT_INPUT).windowID(windowId).text(utf8)));
}
/** Relative mouse motion, as while looking around. */
void look(float dx, float dy) {
push(event -> event.motion(m -> m.type(SDLEvents.SDL_EVENT_MOUSE_MOTION)
.windowID(windowId)
.xrel(dx)
.yrel(dy)));
}
/** Moves the pointer to a position in window coordinates, as over a menu. */
void moveTo(float x, float y) {
push(event -> event.motion(m ->
m.type(SDLEvents.SDL_EVENT_MOUSE_MOTION).windowID(windowId).x(x).y(y)));
}
/** @param button 1 left, 3 right */
void mouseButton(int button, boolean down) {
push(event -> event.button(
b -> b.type(down ? SDLEvents.SDL_EVENT_MOUSE_BUTTON_DOWN : SDLEvents.SDL_EVENT_MOUSE_BUTTON_UP)
.windowID(windowId)
.button((byte) button)
.down(down)
.clicks((byte) 1)));
}
private static void push(java.util.function.Consumer<SDL_Event> fill) {
try (SDL_Event event = SDL_Event.calloc()) {
fill.accept(event);
if (!SDLEvents.SDL_PushEvent(event)) {
throw new IllegalStateException("SDL refused an injected event");
}
}
}
@Override
public void close() {
texts.forEach(MemoryUtil::memFree);
texts.clear();
}
}
@@ -0,0 +1,67 @@
package incari.app.desktop.smoke;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The smoke test's results: one line per check, written to {@code <gameDir>/incari-smoke/report.txt}. */
final class SmokeReport {
private static final Logger LOGGER = LoggerFactory.getLogger("Smoke test");
private final Path file;
private final List<String> lines = new ArrayList<>();
private int failures;
SmokeReport(Path directory) {
this.file = directory.resolve("report.txt");
}
void pass(String check, String detail) {
record("PASS", check, detail);
}
void fail(String check, String detail) {
failures++;
record("FAIL", check, detail);
}
void check(String check, boolean passed, String detail) {
if (passed) {
pass(check, detail);
} else {
fail(check, detail);
}
}
boolean passed() {
return failures == 0 && !lines.isEmpty();
}
private synchronized void record(String result, String check, String detail) {
String line = result + " " + check + (detail.isEmpty() ? "" : " (" + detail + ")");
lines.add(line);
LOGGER.info(line);
write();
}
synchronized void finish() {
lines.add(passed() ? "RESULT all checks passed" : "RESULT " + failures + " check(s) failed");
LOGGER.info(lines.getLast());
write();
}
private void write() {
try {
Files.createDirectories(file.getParent());
Files.write(file, lines, StandardCharsets.UTF_8);
} catch (IOException e) {
LOGGER.warn("Couldn't write the smoke test report", e);
}
}
}
@@ -0,0 +1,79 @@
package incari.app.desktop.smoke;
import incari.client.startup.CriterionCodecs;
import incari.client.world.BiomeCells;
import incari.client.world.DensityBranches;
import incari.client.world.Heights;
import incari.client.world.SurfaceWrites;
import incari.platform.api.Platforms;
import incari.platform.desktop.DesktopPlatform;
import incari.platform.desktop.DesktopStorage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The game's dedicated server on the desktop platform, with the browser build's world generation
* changes (ADR 0041) on or off ({@code -Dincari.worldgen=on|off}): run twice on one seed, the
* worlds it saves must hold the same chunks ({@code tools/worldgen/compare.py} compares the region
* files). {@code -Dincari.worldgen.script=<file>} types its lines into the server's console, a
* line {@code sleep <seconds>} waiting instead. Arguments are the server's own
* ({@code --nogui --universe <folder>}).
*/
public final class WorldgenServer {
private WorldgenServer() {}
public static void main(String[] args) throws Exception {
boolean on = "on".equals(System.getProperty("incari.worldgen", "off"));
Logger logger = LoggerFactory.getLogger("Platform");
DesktopStorage storage = new DesktopStorage(".", "assets", null);
Platforms.install(new DesktopPlatform(storage, (level, message, error) -> logger.info(message, error), false));
SurfaceWrites.setEnabled(on);
BiomeCells.setEnabled(on);
BiomeCells.setVerify(on && Boolean.getBoolean("incari.worldgen.verify"));
Heights.setEnabled(on);
CriterionCodecs.setEnabled(on);
DensityBranches.setEnabled(on);
logger.info("[Incari] World generation changes (ADRs 0041, 0042): {}", on ? "on" : "off");
String script = System.getProperty("incari.worldgen.script");
if (script != null) {
typeInto(List.copyOf(Files.readAllLines(Path.of(script))));
}
net.minecraft.server.Main.main(args);
}
/** Types {@code lines} into the server's console, from a thread of its own. */
private static void typeInto(List<String> lines) throws IOException {
PipedOutputStream console = new PipedOutputStream();
System.setIn(new PipedInputStream(console));
Thread typist = new Thread(() -> type(lines, console), "Worldgen script");
typist.setDaemon(true);
typist.start();
}
private static void type(List<String> lines, OutputStream console) {
try {
for (String line : lines) {
if (line.isBlank() || line.startsWith("#")) {
continue;
}
if (line.startsWith("sleep ")) {
Thread.sleep(Long.parseLong(line.substring(6).trim()) * 1000);
continue;
}
console.write((line + "\n").getBytes(StandardCharsets.UTF_8));
console.flush();
}
} catch (IOException | InterruptedException e) {
System.err.println("[Incari] The worldgen script stopped: " + e);
}
}
}
@@ -0,0 +1,93 @@
package incari.app.desktop.smoke;
import static org.assertj.core.api.Assertions.assertThat;
import incari.app.desktop.smoke.LayoutRules.Box;
import java.util.List;
import org.junit.jupiter.api.Test;
class LayoutRulesTest {
private static final Box DONE = new Box("Done", 10, 10, 110, 30);
private static final Box RESET = new Box("Reset", 114, 10, 164, 30);
@Test
void controlsSideBySideAreFine() {
Box label = new Box("Done text", 45, 16, 75, 25);
assertThat(LayoutRules.problems(320, 240, List.of(DONE, RESET), List.of(label)))
.isEmpty();
}
@Test
void widgetsOverEachOtherFail() {
Box over = new Box("Over", 100, 10, 150, 30);
assertThat(LayoutRules.problems(320, 240, List.of(DONE, over), List.of()))
.singleElement()
.asString()
.contains("Done", "overlaps", "Over");
}
@Test
void widgetsTouchingEdgesAreFine() {
Box next = new Box("Next", 110, 10, 160, 30);
assertThat(LayoutRules.problems(320, 240, List.of(DONE, next), List.of()))
.isEmpty();
}
@Test
void aWidgetOffTheScreenFails() {
Box wide = new Box("Wide", 200, 10, 340, 30);
assertThat(LayoutRules.problems(320, 240, List.of(wide), List.of()))
.singleElement()
.asString()
.contains("runs off the screen");
}
@Test
void textPastItsButtonFails() {
Box long_ = new Box("A very long label", 14, 16, 130, 25);
assertThat(LayoutRules.problems(320, 240, List.of(DONE, RESET), List.of(long_)))
.anyMatch(problem -> problem.contains("runs past Done"));
}
@Test
void itsShadowMayReachAUnitPast() {
Box snug = new Box("Snug", 12, 16, 111, 26);
assertThat(LayoutRules.problems(320, 240, List.of(DONE), List.of(snug))).isEmpty();
}
@Test
void aLabelRunningIntoAControlFails() {
Box label = new Box("A row's long label", 0, 50, 140, 59);
Box toggle = new Box("Toggle", 120, 45, 170, 65);
assertThat(LayoutRules.problems(320, 240, List.of(toggle), List.of(label)))
.singleElement()
.asString()
.contains("runs into Toggle");
}
@Test
void textOverTextFails() {
Box title = new Box("Title", 100, 20, 200, 29);
Box status = new Box("Status", 120, 24, 220, 33);
assertThat(LayoutRules.problems(320, 240, List.of(), List.of(title, status)))
.singleElement()
.asString()
.contains("overlaps");
}
@Test
void emptyBoxesAreIgnored() {
Box hidden = new Box("Hidden", 50, 50, 50, 70);
assertThat(LayoutRules.problems(320, 240, List.of(DONE, hidden), List.of()))
.isEmpty();
}
@Test
void aScrollingScreenMayRunPastTheBottom() {
Box low = new Box("Low", 10, 230, 110, 250);
assertThat(LayoutRules.problems(320, 240, List.of(low), List.of())).hasSize(1);
assertThat(LayoutRules.problems(320, 240, true, List.of(low), List.of()))
.isEmpty();
}
}