diff --git a/.gitignore b/.gitignore index 4a58c5c..819073c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ *.md !README.md +!MOD_DEVELOPMENT.md lib .*/ !.gitea/ diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md new file mode 100644 index 0000000..43c5c21 --- /dev/null +++ b/MOD_DEVELOPMENT.md @@ -0,0 +1,138 @@ +# 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). + +## Building + +A mod is a jar compiled against the `api` module (`./gradlew :api:jar`, then +`api/build/libs/`). A mod that also uses game classes compiles against +`projectzomboid.jar` and declares the game versions it supports. + +## Descriptor + +`META-INF/zomboidforge/mod.toml` in the jar: + +```toml +id = "shop" # lowercase, digits, single underscores; the folder name +name = "Shop" +version = "1.2.0" +entrypoint = "com.example.shop.ShopMod" +api = "0.3" # ZomboidForge version the mod was built against +game = ["42.21"] # only when the mod uses game classes: "42", "42.21", "42.21.0" + +[dependencies] +economy = "2.1" # mod id = minimum version; loaded first +``` + +Default settings go into `META-INF/zomboidforge/config.toml` in the jar. + +## 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 | + +## 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. + +## Checks at startup + +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). diff --git a/README.md b/README.md index 652c186..e87f5e3 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Unset variables keep the value in the server `.ini` (or the game default). | `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` | | `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` | | `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it | -| `JVM_MIN_HEAP` | | `-Xms` | +| `JVM_MIN_HEAP` | `JVM_MAX_HEAP` | `-Xms` | | `JVM_MAX_HEAP` | `8g` | `-Xmx` | | `STEAM` | `1` | `0` runs the server without Steam | | `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards | @@ -64,20 +64,61 @@ Notes: items (`/data/steamapps`). The server runs as UID 1000. A bind-mounted host directory must be writable by UID 1000 (`chown 1000:1000 `); with rootless Podman, use `--userns=keep-id:uid=1000,gid=1000` to map it to your own user. -- **Java mods:** mount a directory at `/forge` (e.g. `-v ./forge:/forge`) with one folder - per mod: `mods//.jar`, optional `mods//lib/*.jar`, and the mod's settings in - `mods//config.toml`. A missing `config.toml` is created from the mod's defaults when - the folder is writable by UID 1000. `[forge]` `enabled = false` in it switches the mod off. - A mod that cannot be loaded (missing dependency, wrong game version, game classes that do - not exist in the running version, failing `onLoad`) stops the server with exit code 1 and - lists every problem in the log. Optional `/forge/forge.toml`: `[main_thread] budget_ms` - (time per tick for mods' main-thread tasks, default 2) and `[shutdown] timeout_s` (time - mod threads get to finish when the server stops, default 10). - **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large worlds (`podman stop -t 120`, `stop_grace_period` in compose). For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`). +## Mods + +ZomboidForge loads server-side Java mods. They run only on the server, so players keep the +official, unmodified client. Project Zomboid's own Lua and Workshop mods are configured as +usual with `MODS` and `WORKSHOP_ITEMS`. + +### Installing mods + +Mount a directory at `/forge` with one folder per mod: + +``` +forge/ +├── forge.toml optional global settings +└── mods/ + └── / + ├── .jar the mod + ├── lib/*.jar libraries of the mod (optional) + └── config.toml settings of the mod (optional) +``` + +```sh +podman run ... -v ./forge:/forge zomboidforge +``` + +- **Settings:** a missing `config.toml` is created from the mod's defaults when the folder is + writable by UID 1000; otherwise the defaults are used without a file. Keys missing from + `config.toml` take the default. +- **Switching a mod off:** `enabled = false` in the `[forge]` table of its `config.toml`. + Mods that depend on it then fail to load. +- **Failures:** a mod that cannot be loaded stops the server with exit code 1, and the log + lists every problem. Examples: a missing or too old dependency, an unsupported game + version, game classes or methods that do not exist in the running version, invalid + settings, an exception in the mod's startup code. +- **Changes** to mods and their settings take effect when the server restarts. + +`forge.toml`, every key optional: + +```toml +[main_thread] +budget_ms = 2 # time per tick for tasks that mods hand to the main thread + +[shutdown] +timeout_s = 10 # time the mods' threads get to finish when the server stops +``` + +### Mod development + +Writing a mod (descriptor, entry point, threads, events, settings, startup checks): +[MOD_DEVELOPMENT.md](MOD_DEVELOPMENT.md). + ## Development Requires JDK 25 (the game's runtime). The Gradle build compiles against a local vanilla