# Mod development How to write a server-side Java mod for ZomboidForge. Installing mods on a server is described in the [README](README.md#mods). ## Project setup A mod is a normal Gradle project with the ZomboidForge plugin. It needs JDK 25 (Project Zomboid's runtime); the plugin sets the Java toolchain to 25. `settings.gradle.kts`: ```kotlin pluginManagement { repositories { maven("https://git.security-command.org/api/packages/overlord/maven") gradlePluginPortal() } } dependencyResolutionManagement { repositories { maven("https://git.security-command.org/api/packages/overlord/maven") mavenCentral() } } rootProject.name = "shop" ``` `build.gradle.kts`: ```kotlin plugins { id("dev.overlord.zomboidforge.mod") version "0.3.0" // the plugin's version is the API version } version = "1.2.0" zomboidForge { id = "shop" entrypoint = "com.example.shop.ShopMod" game("42.21") // only when the mod uses game classes dependsOn("economy", "2.1") // other mods: id and minimum version } dependencies { implementation("com.google.code.gson:gson:2.11.0") // libraries go into the mod's lib/ forgeMods("com.example:economy:2.1") // other mods to compile against } ``` The plugin adds the API (`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the game jar for mods that declare `game` versions. Default settings go into `src/main/resources/META-INF/zomboidforge/config.toml`. ### `zomboidForge { }` | Setting | Default | Meaning | |--------------------------|------------------------------------------|-----------------------------------------------------------------------------------| | `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters | | `entrypoint` | (required) | the class that extends `Mod` | | `name` | the id | display name | | `version` | the project version | the mod's version | | `api` | the plugin's version | ZomboidForge API version the mod is built against | | `game(...)` | none | supported Project Zomboid versions: `"42"`, `"42.21"`, `"42.21.0"` | | `dependsOn(id, version)` | none | another mod this one needs, with its minimum version | | `previousIds(...)` | none | earlier ids of the mod; their storage moves to the current id | | `gameJar` | see below | the `projectzomboid.jar` to compile and check against | | `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` | | `serverImage` | the ZomboidForge image, `latest` | image for `runServer` | | `adminPassword` | `admin` | admin password of the `runServer` server | | `dataVolume` | `zomboidforge-` | volume for the `runServer` world and server config | | `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download | | `deployDirectory` | none | a server's mods directory for `deployMod` | The plugin generates `META-INF/zomboidforge/mod.toml` from these settings; a hand-written one fails the build. ### The game jar Mods that declare `game` versions compile against `projectzomboid.jar`, which cannot be published. The plugin uses the first of: 1. `zomboidForge.gameJar`, or the Gradle property `zomboidforge.gameJar` (for example in `~/.gradle/gradle.properties`); 2. a local Steam installation of the dedicated server or the game, in any Steam library; 3. a download of the dedicated server with steamcmd (`steamcmd` if installed, otherwise its container image with podman or docker), once per Steam branch, into the Gradle user home. It is a few gigabytes. The game jar has to be one of the declared `game` versions; the check below fails otherwise. ### Tasks | Task | Does | |----------------|---------------------------------------------------------------------------------------------| | `build` | compiles, runs `checkMod`, and assembles the mod | | `checkMod` | the server's load checks, at build time (see [Checks at startup](#checks-at-startup)) | | `modFolder` | `build/mod//` with `.jar` and `lib/`, as a server expects it in `/mods` | | `modZip` | the same as `build/distributions/-.zip` | | `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world | | `deployMod` | copies the mod folder into `deployDirectory` | | `downloadGame` | installs the dedicated server for its game jar; runs only when needed | ### Working on ZomboidForge itself To build a mod against a local ZomboidForge checkout instead of a published version, include it in `settings.gradle.kts`; Gradle then builds the plugin, the API, and the mod tools from the checkout: ```kotlin pluginManagement { includeBuild("../ZomboidForge") } includeBuild("../ZomboidForge") ``` ## Entry point The entry point extends `dev.overlord.zomboidforge.api.Mod`: ```java public final class ShopMod extends Mod { record Settings(String greeting, long maxBalance) {} private final Settings settings = this.config().bind(Settings.class); // max_balance in config.toml @Override public void onLoad() // main thread, registration only { this.events().onMain(TickEvent.class, event -> { /* every frame, on the main thread */ }); } @Override public void onServerStarted() // world loaded, port open { this.modThread().scheduleAtFixedRate(() -> { // on zf-mod-shop: slow work, no game objects this.main().submit(GameServer::getPlayerCount) // game objects only on the main thread .thenAcceptAsync(players -> this.logger().log(INFO, players + " online"), this.modThread()); }, Duration.ZERO, Duration.ofMinutes(1)); } @Override public void onStopping() {} // before the world is saved } ``` ## Services Methods of `Mod`, usable from the constructor on (also in field initializers): | Method | Returns | Use | |-----------------|-----------------|---------------------------------------------------------------| | `id()` | `String` | the mod's id from `mod.toml` | | `version()` | `String` | the mod's version from `mod.toml` | | `gameVersion()` | `GameVersion` | the running Project Zomboid version | | `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path | | `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id | | `directory()` | `Path` | the mod's folder, `/mods/` | | `events()` | `Events` | event listeners | | `main()` | `MainThread` | code that touches game objects | | `modThread()` | `ModThread` | the mod's own work, one task at a time | | `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | | `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | ## Threads Game objects belong to the server's main thread. Everything else should stay off it, because it also runs the game: the main loop runs about 10 frames per second. | Executor | Thread | A task runs | |---------------|-------------------------------------|-------------------------------------------------------------------------| | `main()` | `main` | immediately when called on the main thread, otherwise in the next ticks | | `modThread()` | `zf-mod-` | one at a time, in the order submitted | | `async()` | virtual threads `zf-async--` | at once, each on its own thread | Three rules follow from that: 1. Touch game objects only on the main thread; hand results over with `main().execute(...)` or `main().submit(...)`. 2. Never wait on the main thread for another thread (`get()`, `join()`). Continue with `thenAcceptAsync(..., modThread())` instead. 3. Keep main-thread work short. Queued tasks share a time budget per tick (`forge.toml`, `main_thread.budget_ms`); the rest waits for the next tick. ## Events ```java this.events().onMain(TickEvent.class, event -> ...); // main thread, while the event is posted this.events().onModThread(SomeEvent.class, event -> ...); // later, on zf-mod- ``` Listeners are matched by the event's exact class. Events that carry live game objects, such as `TickEvent`, can only be received on the main thread. A listener that keeps throwing is removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove it earlier. ## Storage Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's save folder. Vanilla backups include it, and deleting the world deletes it. Each mod only reaches its own tables. A record declares a table's columns; each row has a `String` key: ```java record Balance(long coins, @Nullable Instant lastPaid) {} Table balances = this.storage().table("balances", Balance.class); balances.set("player1", new Balance(250, Instant.now())); Optional balance = balances.get("player1"); balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null)); this.storage().transaction(() -> { // all or nothing balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null)); balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null)); }); ``` | Component type | Stored as | |-----------------------------------|-------------------------| | `long`, `int`, `boolean` | integer, never null | | `double`, `float` | real number, never null | | `Long`, `Integer`, `Boolean`, ... | the same, may be null | | `String`, `UUID`, enums | text (enums by name) | | `Instant` | ISO-8601 text | | `byte[]` | blob | Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. When the record changes between versions of the mod: | Change | What happens | |--------------------------------|-------------------------------------------| | new component that may be null | added; existing rows read `null` | | new primitive component | needs a migration | | removed component | the column and its data stay; logged once | | component with another type | needs a migration | ```java Table balances = this.storage().define("balances", Balance.class) .version(2) .migrate(1, row -> new Balance(row.getLong("coins"), null)) // from stored version 1 .open(); ``` Things to know: 1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the server runs they throw, so use `modThread()` or `async()`. 2. Writes commit immediately, while the world is saved periodically. After a crash, the world goes back to its last save, but the mod data keeps later writes. 3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables move to the new id once. ## Checks at startup `checkMod` runs these checks when the mod is built, so a mod that would not load fails its build instead. On the server, before any mod code runs, ZomboidForge reads every class of the mod and its libraries. The server does not start when a mod 1. uses game classes without declaring `game` versions in `mod.toml`, 2. uses a game class, field, or method that does not exist in the running version, 3. uses ZomboidForge classes outside the API, or 4. contains classes in a ZomboidForge package, or a class with the name of a game class. Every problem of every mod is listed in the log. ## What a mod can see | Source | Visible | |----------------------------------------------------|-----------------------------------------------| | JDK | yes | | ZomboidForge API (`dev.overlord.zomboidforge.api`) | yes | | the mod's own jar and `lib/*.jar` | yes; own libraries win over the game's copies | | own jars of declared dependencies | yes (not their libraries) | | game jar (game code and its bundled libraries) | only with `game` declared | | ZomboidForge internals | no | ## Profiling Main-thread tasks and event listener calls appear in JFR recordings as the event `zomboidforge.ModTask`, with the mod's id and the kind of work (`task`, or `listener` and the event class).