Author SHA1 Message Date
Overlord 22077514fe Add CancellableHookPatch to allow call skipping based on hook return values. Introduce HookArgument to pass method parameters and locals to hooks. Add HookCall and supporting tests for hook behavior validation. Update HookInjectionPatch to support argument-based hooks.
ci / image (42, public) (push) Successful in 6m4s
2026-10-03 10:56:46 +02:00
Overlord 6761f2d9ea Add ModCheckTest to test runtime mod validations and entry point superclass checks. Include Gradle verification metadata for dependency integrity. 2026-10-03 09:59:47 +02:00
Overlord 18ff32b5ce Refine tag handling in CI/release workflows and publish script to use the v* tag on HEAD, improve error messaging, and update documentation for server configuration adjustments.
ci / image (42, public) (push) Successful in 3m3s
2026-10-03 01:11:44 +02:00
Overlord 67530d35e9 Enhance transactional support with savepoints, improve error handling for nested exceptions, and provide better rollback mechanisms. Update tests to validate savepoint behavior and add new test cases for mod errors, task execution, and server configuration. Expand Gradle tasks to generate admin passwords, preserve configs during deployment, and support custom server addresses. 2026-10-03 01:10:38 +02:00
Overlord 26ca1b90a2 Add support for precise Project Zomboid versioning in builds and images. Include printGameVersion task, improve image tagging, and enhance CI/release workflows for hotfix handling.
ci / image (42, public) (push) Successful in 3m17s
2026-10-02 17:53:58 +02:00
Overlord c529b04ff0 Merge tag 'v0.3.0' into develop
ci / image (42.21, public) (push) Successful in 2m38s
Tagging version v0.3.0 v0.3.0
2026-10-02 15:36:33 +02:00
Overlord 36df4a46b9 Merge branch 'release/v0.3.0'
publish / maven (push) Successful in 3m4s
ci / image (42.21, public) (push) Successful in 16s
2026-10-02 15:36:33 +02:00
Overlord 51e90b6127 Merge branch 'feature/mods' into develop 2026-10-02 15:36:14 +02:00
Overlord 063ad8a3e1 Introduce gradle-plugin and mod-tools modules. Add ZomboidForge Gradle plugin for building, checking, and packaging mods. Include support for local test servers, automated game jar downloads, and mod descriptor generation. Add mod-tools for runtime mod checks and validations. 2026-10-02 15:36:10 +02:00
Overlord 68cd9fc4f9 Add BackupStoragePatch to wrap save folder backups, ensuring storage writes are paused during backups. Introduce ModStorage and ModTables for per-mod database management, supporting schema migrations and table versioning. Add ForgeInstance as a static reference to server-side Forge. Include relevant tests. 2026-10-02 13:57:50 +02:00
Overlord c56046469e Update README with detailed mod installation and configuration instructions for ZomboidForge. 2026-10-02 13:12:41 +02:00
Overlord a0d1ec2feb Introduce event-driven API, modular threading, and enhanced server lifecycle tools
Add `Events` and `EventBus` for mod-driven event handling with support for main-thread and mod-thread execution. Introduce `MainThread` and `AsyncExecutor` for modular threading and background task management. Add `ForgeSettings` to manage global mod configuration through `forge.toml`. Include tests for events, threading, and configuration parsing to improve robustness and maintainability.
2026-10-02 12:58:40 +02:00
Overlord 3b21fc3aa6 Add modular class loaders, enhanced mod verification, and new test cases for mod loading and validation. 2026-10-02 11:20:31 +02:00
Overlord 1b4e153898 Merge branch 'release/v0.2.0'
ci / image (42.21, public) (push) Successful in 18s
2026-10-02 08:25:57 +02:00
Overlord 90e54ec295 Merge tag 'v0.2.0' into develop
ci / image (42.21, public) (push) Successful in 1m32s
Tagging version v0.2.0 v0.2.0
2026-10-02 08:25:57 +02:00
Overlord df4d58a279 Move GameVersion and its tests to the api module and add prefix matching (42, 42.21, 42.21.0). Add the abstract Mod base class with ModContext, bound through a ScopedValue while the mod is constructed. Add mod discovery, mod.toml parsing (night-config TOML), validation of API and game versions and dependencies, dependency ordering, and per-mod class loaders in core.mods. Add Forge to load mods and call their lifecycle methods from ServerHooks, and ConsoleLogger for log output. Add tests for versions, descriptors, discovery, resolution, and loading. 2026-10-01 22:31:23 +02:00
Overlord 837367047c Add ServerLoadPatch, ServerStoppingPatch, and ServerTickPatch to enhance server lifecycle handling in GameServer. Include tests, update B42PatchSet, and integrate lifecycle management utilities. 2026-10-01 20:03:10 +02:00
Overlord 600373dc61 Refine nullability annotations in HierarchyClassWriter and JarPatcher for consistency and clarity. 2026-10-01 19:46:48 +02:00
Overlord 0966cdba89 Refine nullability annotations in HierarchyClassWriter and JarPatcher for consistency and clarity. 2026-10-01 18:11:55 +02:00
Overlord 30b0b0572f Annotate with @SuppressWarnings("NullableProblems"), clean up imports, and adjust nullability annotations for improved clarity and consistency. 2026-10-01 18:05:32 +02:00
Overlord c22aa29c88 Add new performance patches for IsoGameCharacter and IsoZombie, including caching and early-exit optimizations. Added corresponding tests. 2026-10-01 15:44:18 +02:00
Overlord 1a53f833e3 Add and test Anchor.Sequence to match instruction patterns, skipping labels and line numbers. Document sequence matching behavior and integrate new matchers (constant, opcode, invoke). 2026-10-01 14:16:44 +02:00
Overlord c9e41e2c91 Document FORGE_VERSION default and new DISABLED_PATCHES option in README, update Dockerfile to reflect default FORGE_VERSION. 2026-10-01 14:00:23 +02:00
Overlord 28c36c7eae Merge branch 'release/v0.2.0-performance'
ci / image (42.21, public) (push) Successful in 21s
2026-10-01 13:16:25 +02:00
Overlord 94a026093c Merge tag 'v0.2.0-performance' into develop
ci / image (42.21, public) (push) Successful in 1m44s
Tagging version v0.2.0-performance v0.2.0-performance
2026-10-01 13:16:25 +02:00
Overlord 134901098c Add IsoZombieNetworkComponentPerformancePatch for efficient component access by caching NetworkZombieComponent lookups. Update B42PatchSet to include the new patch and adjust related test cases. 2026-10-01 12:52:31 +02:00
Overlord acef6fd81f refactored package structure 2026-10-01 12:36:41 +02:00
Overlord 981445a797 Annotate all packages with @NotNullByDefault and suppress warnings for unstable API usage. 2026-10-01 12:29:07 +02:00
Overlord da7ae49618 Optimize IsoZombie.isVehicleBetween performance: implement IsoZombieVehiclePerformancePatch. Add SegmentReach class for efficient distance checks and ZombieVehicleHooks for targeted vehicle intersection. Include tests for new functionality and integrate patch into B42PatchSet. 2026-10-01 10:09:54 +02:00
Overlord d7151f60e8 Refactor patching structure: introduce PerformancePatch class and relocate HookInjectionPatch to Patches package. 2026-10-01 09:26:06 +02:00
Overlord abc6c6c53e Annotate interfaces and methods with proper nullability and internal use annotations, and clean up formatting. 2026-10-01 09:22:43 +02:00
Overlord 2b94a49352 Add support for anchors, hooks, and hook injection in patching logic with comprehensive tests.
ci / image (42.21, public) (push) Successful in 1m43s
Added onServerStarted Hook and Patch.
2026-09-30 21:59:22 +02:00
Overlord e13132c202 Introduce versioning from git tags and improve CI/CD workflows 2026-09-30 20:32:14 +02:00
Overlord 989cb88e0a Merge tag 'v0.1.0-SNAPSHOT' into develop
ci / image (42.21, public) (push) Successful in 20s
Tagging version v0.1.0-SNAPSHOT v0.1.0-SNAPSHOT
2026-09-30 16:38:18 +02:00
176 changed files with 15642 additions and 266 deletions

No files matched your search

+2
View File
@@ -9,6 +9,8 @@
!compat/ !compat/
!agent/ !agent/
!patcher/ !patcher/
!mod-tools/
!gradle-plugin/
!docker/ !docker/
**/build/ **/build/
**/.gradle/ **/.gradle/
+5 -2
View File
@@ -15,10 +15,13 @@ jobs:
include: include:
# One entry per supported version; add older Steam version branches # One entry per supported version; add older Steam version branches
# (e.g. pz_version 42.19, steam_branch 42.19) to keep them building. # (e.g. pz_version 42.19, steam_branch 42.19) to keep them building.
- pz_version: "42.21" - pz_version: "42"
steam_branch: public steam_branch: public
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# release.sh derives the version from the v* tags
fetch-depth: 0
- name: Build and verify - name: Build and verify
env: env:
+35
View File
@@ -0,0 +1,35 @@
# Publishes the mod API, the mod tools, and the Gradle plugin to the Gitea Maven registry
# (https://git.security-command.org/api/packages/overlord/maven) for every release tag.
# Pre-release tags (containing "-") are tested but not published (see ci/publish.sh).
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with package
# write access), the same as the image release.
name: publish
on:
push:
tags:
- "v*"
jobs:
maven:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# publish.sh derives the version from the v* tag on HEAD
fetch-depth: 0
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with:
distribution: temurin
java-version: "25"
# The tests run without the registry credentials; only the publish step gets them.
- name: Test
run: ci/publish.sh test
- name: Publish
env:
ORG_GRADLE_PROJECT_giteaUsername: ${{ secrets.REGISTRY_USER }}
ORG_GRADLE_PROJECT_giteaPassword: ${{ secrets.REGISTRY_TOKEN }}
run: ci/publish.sh publish
+17 -5
View File
@@ -1,12 +1,16 @@
# Publishes an image for every new Steam build of each supported Project Zomboid # Publishes an image for every new Project Zomboid version (hotfixes included) of each
# version. Immutable tags are never overwritten (see ci/release.sh). # matrix entry and every new ZomboidForge release; full version tags are never overwritten
# (see ci/release.sh).
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with # Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with
# package write access) and a runner with a Docker (or Podman) CLI. # package write access) and a runner with a Docker (or Podman) CLI.
name: release name: release
on: on:
# Every 2.5 hours; cron cannot divide a day into 2.5-hour steps, so the gap
# from 22:30 to 00:00 is 1.5 hours.
schedule: schedule:
- cron: "0 */6 * * *" - cron: "0 0,5,10,15,20 * * *"
- cron: "30 2,7,12,17,22 * * *"
workflow_dispatch: workflow_dispatch:
jobs: jobs:
@@ -16,11 +20,14 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
include: include:
- pz_version: "42.21" - pz_version: "42"
steam_branch: public steam_branch: public
latest: "true" latest: "true"
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# release.sh derives the version from the v* tags
fetch-depth: 0
- name: Log in to the registry - name: Log in to the registry
env: env:
@@ -36,3 +43,8 @@ jobs:
PUBLISH: "true" PUBLISH: "true"
LATEST: ${{ matrix.latest }} LATEST: ${{ matrix.latest }}
run: ci/release.sh run: ci/release.sh
# Removes the stored registry token, also when a step failed, in case the runner is reused.
- name: Log out of the registry
if: always()
run: docker logout git.security-command.org
+1
View File
@@ -1,5 +1,6 @@
*.md *.md
!README.md !README.md
!MOD_DEVELOPMENT.md
lib lib
.*/ .*/
!.gitea/ !.gitea/
+60 -12
View File
@@ -6,23 +6,34 @@
# podman build --platform linux/amd64 -t zomboidforge . # podman build --platform linux/amd64 -t zomboidforge .
# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ... # podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ...
# #
# The stage game-version (--target game-version) downloads only the server jar of
# PZ_BRANCH and writes its game version to /game-version; ci/release.sh uses it to
# name the image before the full build.
#
# Build arguments: # Build arguments:
# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...) # PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...)
# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded # PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded
# server reports another one. Default: pz.version in gradle.properties # server reports another one. Default: pz.version in gradle.properties
# STEAMCLIENT bundled (default) or steamcmd: replace the server's steamclient.so # STEAMCLIENT bundled (default) or steamcmd: replace the server's steamclient.so
# files with steamcmd's newer copies # files with steamcmd's newer copies
# FORGE_VERSION Image label only; set by ci/release.sh # FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
# STEAM_BUILDID Image label only; set by ci/release.sh # Default: 0.0.0-prerelease
# STEAM_BUILDID Image label; in the stage game-version it keeps the cached result until
# Steam publishes a new build. Set by ci/release.sh
# DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
# (debug builds only; ci/release.sh never sets it)
ARG PZ_BRANCH=public ARG PZ_BRANCH=public
ARG PZ_VERSION="" ARG PZ_VERSION=""
ARG STEAMCLIENT=bundled ARG STEAMCLIENT=bundled
ARG FORGE_VERSION="" ARG FORGE_VERSION="0.0.0-prerelease"
ARG STEAM_BUILDID="" ARG STEAM_BUILDID=""
# Base images are pinned by digest; the tag in front of the digest is for readers only.
# The same steamcmd image is in ci/steam-buildid.sh and the Gradle plugin's DownloadGame.
# --- Stage 1: vanilla dedicated server ----------------------------------------- # --- Stage 1: vanilla dedicated server -----------------------------------------
FROM docker.io/steamcmd/steamcmd:debian-13 AS server FROM docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d AS server
# steamcmd updates itself on its first run. This runs in its own layer so the # steamcmd updates itself on its first run. This runs in its own layer so the
# update is cached and separate from the app installation. # update is cached and separate from the app installation.
@@ -33,8 +44,8 @@ ARG STEAMCLIENT
COPY docker/install-server.sh /usr/local/bin/install-server COPY docker/install-server.sh /usr/local/bin/install-server
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}" RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
# --- Stage 2: ZomboidForge build and server jar patching ----------------------- # --- Stage 2: ZomboidForge sources and Gradle -----------------------------------
FROM docker.io/library/eclipse-temurin:25-jdk AS build FROM docker.io/library/eclipse-temurin:25-jdk@sha256:8c0a84ea11c8f6ed52600fc19f1040121f2a162998e9f50a5faebbbad9172dcc AS sources
WORKDIR /src WORKDIR /src
# Gradle distribution download, cached independently of the sources. # Gradle distribution download, cached independently of the sources.
@@ -48,17 +59,53 @@ COPY core core
COPY compat compat COPY compat compat
COPY agent agent COPY agent agent
COPY patcher patcher COPY patcher patcher
COPY mod-tools mod-tools
COPY gradle-plugin gradle-plugin
# --- Game version of a Steam branch, from its server jar alone ------------------
# Not part of the image; built on its own by ci/release.sh.
FROM sources AS game-version
# DepotDownloader downloads single files of a depot; steamcmd only whole apps.
ADD --checksum=sha256:a999dec66b4850fc961bd50366696d23c2d0fad7b18790e6a5647b2f19097a53 \
https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-x64.zip \
/opt/depotdownloader/depotdownloader.zip
RUN cd /opt/depotdownloader \
&& jar xf depotdownloader.zip \
&& chmod +x DepotDownloader \
&& rm depotdownloader.zip
# FORGE_VERSION only keeps Gradle from asking git (not in this stage) for the version.
ARG PZ_BRANCH
ARG STEAM_BUILDID
ARG FORGE_VERSION
RUN echo java/projectzomboid.jar > /tmp/files \
&& /opt/depotdownloader/DepotDownloader \
-app 380870 -depot 380871 -branch "${PZ_BRANCH}" -filelist /tmp/files -dir /pz \
&& ./gradlew --no-daemon --quiet \
-Ppz.jar=/pz/java/projectzomboid.jar \
-Pversion=${FORGE_VERSION} \
:patcher:printGameVersion > /game-version
# --- Stage 3: ZomboidForge build and server jar patching -----------------------
FROM sources AS build
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
# An empty PZ_VERSION keeps pz.version from gradle.properties. # An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
# value (default 0.0.0-prerelease): this stage has no git, so the version cannot come from a tag.
ARG PZ_VERSION ARG PZ_VERSION
ARG FORGE_VERSION
ARG DISABLED_PATCHES=""
RUN ./gradlew --no-daemon \ RUN ./gradlew --no-daemon \
-Ppz.jar=/pz/projectzomboid.jar \ -Ppz.jar=/pz/projectzomboid.jar \
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \ ${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
build :patcher:patchServerJar ${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
build -x :gradle-plugin:test :patcher:patchServerJar
# --- Stage 3: runtime ------------------------------------------------------------ # --- Stage 4: runtime ------------------------------------------------------------
FROM docker.io/library/debian:trixie-slim FROM docker.io/library/debian:trixie-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a
# ca-certificates: required by steamclient.so to connect to Steam. # ca-certificates: required by steamclient.so to connect to Steam.
# sqlite3: the entrypoint checks the admin account in the server database. # sqlite3: the entrypoint checks the admin account in the server database.
@@ -68,9 +115,10 @@ RUN apt-get update \
&& apt-get install --yes --no-install-recommends ca-certificates sqlite3 \ && apt-get install --yes --no-install-recommends ca-certificates sqlite3 \
&& rm --recursive --force /var/lib/apt/lists/* && rm --recursive --force /var/lib/apt/lists/*
# /forge/mods holds Java mods (one folder per mod); usually a mounted directory.
RUN useradd --create-home --uid 1000 pz \ RUN useradd --create-home --uid 1000 pz \
&& mkdir /data \ && mkdir --parents /data /forge/mods \
&& chown pz:pz /data && chown --recursive pz:pz /data /forge
COPY --from=server /server /opt/pz COPY --from=server /server /opt/pz
COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/projectzomboid.jar COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/projectzomboid.jar
+309
View File
@@ -0,0 +1,309 @@
# 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") // 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` | random, generated once per volume | admin password of the `runServer` server (see below) |
| `serverAddress` | `127.0.0.1` | host address `runServer` publishes the game ports on; `0.0.0.0` for the network |
| `dataVolume` | `zomboidforge-<id>` | 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.
Declare a minor version in `game(...)` only when the mod needs it. A mod declaring `"42.21"`
stops the server after an update to 42.22, while the server checks every game member a mod uses
against the running jar anyway.
### 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/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` |
| `modZip` | the same as `build/distributions/<id>-<version>.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`; keeps the server's `config.toml` of the mod |
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
`runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without
`adminPassword`, the first run generates a random admin password for the volume, prints it, and
keeps it in `<Gradle user home>/zomboidforge/admin-passwords/<volume>`. The server uses the
password only when it creates the admin account, on the volume's first start; a later change
needs a new volume (`dataVolume`, or remove the old one).
### 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, `<forge>/mods/<id>` |
| `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-<id>` | one at a time, in the order submitted |
| `async()` | virtual threads `zf-async-<id>-<n>` | 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-<id>
```
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. Through the API,
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<Balance> balances = this.storage().table("balances", Balance.class);
balances.set("player1", new Balance(250, Instant.now()));
Optional<Balance> 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, also when nested
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<Balance> 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.
4. While a `transaction`, `update`, or `forEach` callback runs, the storage of every mod waits.
These callbacks must not wait for other threads, for example with
`main().submit(...).join()`. A backup waits at most 10 seconds for them and then runs
without pausing storage, so its copy of `zomboidforge.db` may be incomplete.
## 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 |
These rules keep mods from linking against the wrong classes by accident. They are not a
sandbox: a mod runs with the full privileges of the server process. Through reflection or the
file system it can reach anything the server can, including other mods' data in
`zomboidforge.db`.
## 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).
+92 -26
View File
@@ -14,14 +14,18 @@ version in `gradle.properties` (`pz.version`).
podman build --platform linux/amd64 -t zomboidforge . # or: docker build ... podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
``` ```
| Build argument | Default | | | Build argument | Default | |
|---|---|---| |--------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` | | `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` |
| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version | | `PZ_VERSION` | `pz.version` | Expected Project Zomboid version |
| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) | | `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) |
| `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it |
| `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` |
Published images are tagged `<forge>-pz<pz>-build<steam buildid>` (immutable), Published images are tagged `<forge>-pz<major.minor.build>` (never overwritten),
`<forge>-pz<pz>`, and `latest`. `<forge>-pz<major.minor>` (the newest hotfix of that minor version), and `latest`. A new image
is built for every ZomboidForge release and every Project Zomboid version, hotfixes included:
the server only admits clients with the same version.
## Running ## Running
@@ -34,24 +38,24 @@ podman run -d --name zomboidforge \
Unset variables keep the value in the server `.ini` (or the game default). Unset variables keep the value in the server `.ini` (or the game default).
| Variable | Default | | | Variable | Default | |
|---|---|---| |-------------------|----------------|-----------------------------------------------------------------------------------------------------|
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) | | `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) | | `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser | | `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
| `PUBLIC_NAME` | | Name in the server browser | | `PUBLIC_NAME` | | Name in the server browser |
| `PORT` | `16261` | Game port (`-port`) | | `PORT` | `16261` | Game port (`-port`) |
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) | | `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
| `ADMIN_USERNAME` | `admin` | First start only | | `ADMIN_USERNAME` | `admin` | First start only |
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards | | `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` | | `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` | | `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` | | `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it | | `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` | | `JVM_MAX_HEAP` | `8g` | `-Xmx` |
| `STEAM` | `1` | `0` runs the server without Steam | | `STEAM` | `1` | `0` runs the server without Steam |
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards | | `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
Notes: Notes:
@@ -67,6 +71,64 @@ Notes:
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`). 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/
└── <id>/
├── <id>.jar the mod
├── lib/*.jar libraries of the mod (optional)
└── config.toml settings of the mod (optional)
```
```sh
podman run ... -v ./forge:/forge zomboidforge
```
Mods are trusted code. They run inside the server process with its full privileges: they can
read and write any file the server can, open network connections, and stop the server. The
class loader isolation and the startup checks catch mistakes; they do not contain a malicious
mod. Install only mods whose authors you trust.
A mod's settings live in its `config.toml`. When the file is missing, it is created from the
mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a
file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]`
table switches the mod off; mods that depend on it then fail to load.
Mods keep their data in `zomboidforge.db` in the world's save folder
(`/data/Saves/Multiplayer/<server>/`). Vanilla backups include it, and deleting the world
deletes it.
A mod that cannot be loaded stops the server with exit code 1, and the log lists every
problem: a missing or too old dependency, an unsupported game version, game classes or methods
that do not exist in the running version, invalid settings, or 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 ## Development
Requires JDK 25 (the game's runtime). The Gradle build compiles against a local vanilla Requires JDK 25 (the game's runtime). The Gradle build compiles against a local vanilla
@@ -78,4 +140,8 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
``` ```
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent. Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
`pz.version` in `gradle.properties` selects the targeted version. `pz.version` in `gradle.properties` selects the targeted version. `mod-tools` (the build-time
mod checks) and `gradle-plugin` (the plugin for mod authors) are for mod builds, not the server.
Release tags publish `api`, `mod-tools`, and the Gradle plugin to the Gitea Maven registry
(`.gitea/workflows/publish.yml`, `ci/publish.sh`); tags with a `-` are only tested.
+15 -5
View File
@@ -2,6 +2,7 @@
plugins { plugins {
id("zomboidforge.java-conventions") id("zomboidforge.java-conventions")
alias(libs.plugins.shadow)
} }
dependencies { dependencies {
@@ -11,10 +12,19 @@ dependencies {
compileOnly(files(projectZomboid.serverJar)) compileOnly(files(projectZomboid.serverJar))
} }
tasks.jar { // The agent jar is appended to the system class path behind the game jar and includes api,
archiveBaseName = "zomboidforge-agent" // core, compat runtime, and their libraries. The libraries are relocated, so a copy of the same
// library in the game jar cannot replace them.
tasks.shadowJar {
archiveBaseName = "zomboidforge-agent"
archiveClassifier = ""
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent") manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
// The agent jar is appended to the system class path and includes api, core and compat runtime.
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } }) relocate("org.objectweb.asm", "dev.overlord.zomboidforge.shaded.asm")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE relocate("com.electronwill.nightconfig", "dev.overlord.zomboidforge.shaded.nightconfig")
}
// Only the shadow jar is used; the plain jar would match the same file name pattern.
tasks.jar {
enabled = false
} }
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.agent;
import org.jetbrains.annotations.NotNullByDefault;
+33
View File
@@ -1,5 +1,38 @@
// API for custom Java mods. Version-independent: no references to game classes. // API for custom Java mods. Version-independent: no references to game classes.
// Published as dev.overlord.zomboidforge:api; mods compile against it.
plugins { plugins {
id("zomboidforge.java-conventions") id("zomboidforge.java-conventions")
id("zomboidforge.publishing")
`java-library`
}
java {
withSourcesJar()
withJavadocJar()
}
tasks.javadoc {
// api.internal connects the API to the runtime and is not part of the documented API.
exclude("dev/overlord/zomboidforge/api/internal/**")
(options as StandardJavadocDocletOptions).apply {
// IntelliJ's @noinspection in package-info.java is not a Javadoc tag.
tags("noinspection:X")
addStringOption("Xdoclint:all,-missing", "-quiet")
}
}
publishing {
publications {
create<MavenPublication>("api") {
from(components["java"])
}
}
}
dependencies {
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
} }
@@ -0,0 +1,20 @@
package dev.overlord.zomboidforge.api;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
/**
* Virtual threads for a mod's blocking work, such as HTTP calls or file I/O: one thread per
* task, named {@code zf-async-<id>-<n>}. ZomboidForge shuts it down when the server stops; tasks
* submitted after that are rejected with a {@link java.util.concurrent.RejectedExecutionException}.
*/
public interface AsyncExecutor extends Executor
{
/** Runs {@code task} on a new virtual thread. An exception it throws is logged with the mod's id. */
@Override
void execute(Runnable task);
/** Runs {@code task} on a new virtual thread; the future completes with its result or exception. */
<T> CompletableFuture<T> submit(Callable<T> task);
}
@@ -0,0 +1,7 @@
package dev.overlord.zomboidforge.api;
/**
* Something that happened in the server, delivered to listeners registered with
* {@link Events}. Listeners are matched by the event's exact class.
*/
public interface Event {}
@@ -0,0 +1,24 @@
package dev.overlord.zomboidforge.api;
import java.util.function.Consumer;
/**
* Registration of event listeners. Listeners of one event run in registration order. A listener
* that throws is logged with the mod's id; one that throws repeatedly is removed.
*/
public interface Events
{
/**
* {@code listener} runs on the main thread while the event is posted. It may touch game
* objects and must return quickly: it runs inside the tick.
*/
<E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener);
/**
* {@code listener} runs later on the mod's own thread. It must not touch game objects;
* main-thread work goes through {@code main()}.
*
* @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent}
*/
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
}
@@ -0,0 +1,63 @@
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.Nullable;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Project Zomboid version, e.g. 42.21.0 ({@code Core.getGameAndBuildVersion()}). */
public record GameVersion(int major, int minor, int build) implements Comparable<GameVersion>
{
// At most 9 digits per number, so every number fits an int.
private static final Pattern VERSION = Pattern.compile("(\\d{1,9})\\.(\\d{1,9})(?:\\.(\\d{1,9}))?");
private static final Pattern PREFIX = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9})(?:\\.(\\d{1,9}))?)?");
private static final Comparator<GameVersion> ORDER = Comparator
.comparingInt(GameVersion::major)
.thenComparingInt(GameVersion::minor)
.thenComparingInt(GameVersion::build);
/** Parses "42.21.0", or "42.21" as 42.21.0. */
public static GameVersion parse(String text)
{
Matcher matcher = GameVersion.VERSION.matcher(text.trim());
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version: '" + text + "'.");
int build = matcher.group(3) == null
? 0
: Integer.parseInt(matcher.group(3));
return new GameVersion(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), build);
}
/** Whether {@code text} is a version prefix for {@link #matches}: "42", "42.21", or "42.21.0". */
public static boolean isPrefix(String text) { return GameVersion.PREFIX.matcher(text.trim()).matches(); }
/**
* Whether this version starts with {@code prefix}: "42" matches every 42.x.y, "42.21" every
* 42.21.x, "42.21.0" only 42.21.0.
*/
public boolean matches(String prefix)
{
Matcher matcher = GameVersion.PREFIX.matcher(prefix.trim());
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version prefix: '" + prefix + "'.");
return GameVersion.partMatches(matcher.group(1), this.major)
&& GameVersion.partMatches(matcher.group(2), this.minor)
&& GameVersion.partMatches(matcher.group(3), this.build);
}
public boolean isAtLeast(int major, int minor) { return this.compareTo(new GameVersion(major, minor, 0)) >= 0; }
public boolean isBefore(int major, int minor) { return this.compareTo(new GameVersion(major, minor, 0)) < 0; }
@Override
public int compareTo(GameVersion other) { return GameVersion.ORDER.compare(this, other); }
@Override
public String toString() { return this.major + "." + this.minor + "." + this.build; }
/** A missing part of a prefix matches any value. */
private static boolean partMatches(@Nullable String part, int value) { return part == null || Integer.parseInt(part) == value; }
}
@@ -0,0 +1,44 @@
package dev.overlord.zomboidforge.api;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
/**
* Runs a mod's code on the server's main thread, which owns every game object. Tasks from other
* threads are queued and run during the next ticks, within a time budget per tick
* ({@code forge.toml}); a task is never interrupted. Called on the main thread itself,
* {@link #execute} and {@link #submit} run the task immediately.
*
* <p>Callbacks of the returned futures run on the thread that completes them, which is the
* main thread: {@code submit(...).thenAcceptAsync(result -> ..., modThread())} moves the
* follow-up work back. The main thread must never wait for another thread's result.
*/
public interface MainThread extends Executor
{
/**
* Runs {@code task} on the main thread. An exception it throws is logged with the mod's id.
*
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
*/
@Override
void execute(Runnable task);
/**
* Runs {@code task} on the main thread; the future completes with its result or exception.
*
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
*/
<T> CompletableFuture<T> submit(Callable<T> task);
/**
* Queues {@code task} to run on the main thread {@code ticks} frames from now, also when
* called on the main thread.
*
* @throws IllegalArgumentException when {@code ticks} is less than 1
*/
void runLater(int ticks, Runnable task);
/** Whether the calling thread is the main thread. */
boolean isMainThread();
}
@@ -0,0 +1,7 @@
package dev.overlord.zomboidforge.api;
/**
* An event that carries live game state or only makes sense during the tick. Listeners for it
* run on the main thread only; {@link Events#onModThread} rejects it.
*/
public interface MainThreadEvent extends Event {}
@@ -0,0 +1,87 @@
package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.internal.ModBinding;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import java.nio.file.Path;
/**
* Base class of every mod. The class named as {@code entrypoint} in {@code mod.toml} extends it
* and has a public constructor without parameters.
*
* <p>ZomboidForge creates one instance per mod on the main thread, in dependency order, while
* the server starts. The methods of this class work from the constructor on, so field
* initializers may use them.
*
* <p>Lifecycle, in this order:
* <ol>
* <li>{@link #onLoad()}: registration and setup. The server database, Lua, and the world do
* not exist yet.</li>
* <li>{@link #onServerStarted()}: the world is loaded and the network port is open.</li>
* <li>{@link #onStopping()}: the server stops; the world has not been saved yet.</li>
* </ol>
* An exception thrown by the constructor or {@link #onLoad()} stops the server.
*/
public abstract class Mod
{
private final ModContext context;
/** @throws IllegalStateException when the instance is not created by ZomboidForge */
protected Mod()
{
if (!ModBinding.CONTEXT.isBound())
throw new IllegalStateException("'" + this.getClass().getName() + "' can only be created by ZomboidForge.");
this.context = ModBinding.CONTEXT.get();
}
/** The id from {@code mod.toml}. */
public final String id() { return this.context.id(); }
/** The version from {@code mod.toml}. */
public final String version() { return this.context.version(); }
/** Called once on the main thread, after the instance is created. */
@SuppressWarnings("RedundantThrows")
public void onLoad() throws Exception {}
/**
* Called once on the main thread, after the world is loaded, the network port is open, and
* RCON is initialized; directly before the main loop starts.
*/
public void onServerStarted() {}
/**
* Called once on the shutdown thread when the server stops, before the world is saved.
* The main thread may still be finishing a tick. Mods are stopped in reverse load order.
*/
public void onStopping() {}
/** The running Project Zomboid version. */
protected final GameVersion gameVersion() { return this.context.gameVersion(); }
/** Logger whose messages go into the Project Zomboid log, marked with the mod's id. */
protected final System.Logger logger() { return this.context.logger(); }
/** The mod's folder, {@code <forge>/mods/<id>}. */
protected final Path directory() { return this.context.directory(); }
/** The mod's settings from {@code config.toml}. */
protected final ModConfig config() { return this.context.config(); }
/** Event listener registration. */
protected final Events events() { return this.context.events(); }
/** The server's main thread, for everything that touches game objects. */
@SuppressWarnings("ConfusingMainMethod")
protected final MainThread main() { return this.context.main(); }
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
protected final ModThread modThread() { return this.context.modThread(); }
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
protected final AsyncExecutor async() { return this.context.async(); }
/** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */
protected final ModStorage storage() { return this.context.storage(); }
}
@@ -0,0 +1,34 @@
package dev.overlord.zomboidforge.api;
import java.util.Optional;
/**
* Settings of one mod: {@code <forge>/mods/<id>/config.toml}, over the defaults in the mod's
* jar ({@code META-INF/zomboidforge/config.toml}). A key missing from the file takes the
* default. The table {@code [forge]} belongs to ZomboidForge and is not part of these settings.
*
* <p>Keys are {@code snake_case}; record components and paths use the same names converted
* from {@code camelCase} ({@code maxBalance} reads {@code max_balance}).
*/
public interface ModConfig
{
/**
* Creates a record from the settings. Supported component types: {@code String},
* {@code boolean}, {@code int}, {@code long}, {@code float}, {@code double} (and their
* wrappers), enums (by constant name), records (TOML tables), {@code List<T>},
* {@code Map<String, T>} (tables with free keys), and {@code Optional<T>} for values that
* may be missing. Every other component must have a value. Keys without a component are
* logged as warnings.
*
* @throws IllegalStateException listing every missing or mistyped value
*/
<T extends Record> T bind(Class<T> type);
/**
* The value at a dotted path, e.g. {@code "features.max_balance"}, converted like a record
* component of {@code type}. Primitive values use the wrapper types ({@code Long.class}).
*
* @throws IllegalStateException when the value exists but has another type
*/
<T> Optional<T> get(String path, Class<T> type);
}
@@ -0,0 +1,45 @@
package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import java.nio.file.Path;
/**
* What ZomboidForge provides to one mod. Mods reach it through the methods of {@link Mod};
* ZomboidForge implements it.
*/
public interface ModContext
{
/** The mod's id from {@code mod.toml}. */
String id();
/** The mod's version from {@code mod.toml}. */
String version();
/** The running Project Zomboid version. */
GameVersion gameVersion();
/** Logger whose messages go into the Project Zomboid log, marked with the mod's id. */
System.Logger logger();
/** The mod's folder, {@code <forge>/mods/<id>}. */
Path directory();
/** The mod's settings from {@code config.toml}. */
ModConfig config();
/** Event listener registration. */
Events events();
/** The server's main thread, for everything that touches game objects. */
MainThread main();
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
ModThread modThread();
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
AsyncExecutor async();
/** The mod's tables in the world's {@code zomboidforge.db}. */
ModStorage storage();
}
@@ -0,0 +1,41 @@
package dev.overlord.zomboidforge.api;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
/**
* The mod's own platform thread, {@code zf-mod-<id>}: runs one task at a time, in the order
* they were submitted. ZomboidForge shuts it down when the server stops; tasks submitted after
* that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. It must not
* touch game objects; that goes through {@code main()}.
*/
public interface ModThread extends Executor
{
/** Runs {@code task} on the mod thread. An exception it throws is logged with the mod's id. */
@Override
void execute(Runnable task);
/** Runs {@code task} on the mod thread; the future completes with its result or exception. */
<T> CompletableFuture<T> submit(Callable<T> task);
/** Runs {@code task} once after {@code delay}. An exception it throws is logged. */
ScheduledFuture<?> schedule(Runnable task, Duration delay);
/**
* Runs {@code task} after {@code initialDelay}, then every {@code period}, measured from the
* start of each run. A run that throws is logged and ends the schedule.
*/
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration initialDelay, Duration period);
/**
* Runs {@code task} after {@code initialDelay}, then again {@code delay} after each run
* finished. A run that throws is logged and ends the schedule.
*/
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration initialDelay, Duration delay);
/** Whether the calling thread is this mod thread. */
boolean isModThread();
}
@@ -0,0 +1,8 @@
package dev.overlord.zomboidforge.api;
/** A registered event listener. */
public interface Subscription
{
/** Removes the listener; it receives no further events. Calling it again has no effect. */
void cancel();
}
@@ -0,0 +1,9 @@
package dev.overlord.zomboidforge.api;
/**
* Posted on the main thread once per frame of the main loop, before the queued main-thread
* tasks run.
*
* @param tick number of the frame, counted from 1 at the first frame after the server started
*/
public record TickEvent(long tick) implements MainThreadEvent {}
@@ -0,0 +1,17 @@
package dev.overlord.zomboidforge.api.internal;
import dev.overlord.zomboidforge.api.ModContext;
import org.jetbrains.annotations.ApiStatus.Internal;
/**
* The context of the mod being created. ZomboidForge binds it while it calls a mod's
* constructor; the {@code Mod} constructor reads it.
*/
@Internal
public final class ModBinding
{
public static final ScopedValue<ModContext> CONTEXT = ScopedValue.newInstance();
private ModBinding() {}
}
@@ -0,0 +1,9 @@
/**
* Connection between the API and the ZomboidForge runtime. Not part of the mod API.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.api.internal;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,39 @@
package dev.overlord.zomboidforge.api.storage;
import java.util.function.Supplier;
/**
* The mod's tables in {@code zomboidforge.db}, next to the world's save. Every table belongs to
* the mod; this interface gives no access to the tables of other mods. It is not a security
* boundary: mod code runs with the server's privileges and can open the file directly.
*
* <p>A record declares a table's columns: {@code String}, {@code long}/{@code int},
* {@code double}/{@code float}, {@code boolean}, {@code byte[]}, {@code UUID}, {@code Instant},
* and enums. Primitive components cannot be null. Table and column names are {@code snake_case}
* ({@code lastPaid} is stored as {@code last_paid}).
*
* <p>Calls block. On the main thread they are only allowed during startup ({@code onLoad});
* once the server runs they throw an {@link IllegalStateException}, so database I/O never costs
* tick time. Use {@code modThread()} or {@code async()}.
*/
public interface ModStorage
{
/** Opens the table {@code name} with schema version 1 and no migrations. */
<R extends Record> Table<R> table(String name, Class<R> type);
/** A table with a schema version and migrations; see {@link TableDefinition}. */
<R extends Record> TableDefinition<R> define(String name, Class<R> type);
/**
* Runs {@code work} in one transaction: writes of this thread inside it are committed
* together, or not at all when {@code work} throws.
*
* <p>Storage of every mod waits while {@code work} runs, so {@code work} must not wait for
* other threads, for example with {@code main().submit(...).join()}. A backup waits at most
* 10 seconds for it and then runs without pausing storage.
*/
void transaction(Runnable work);
/** Like {@link #transaction(Runnable)}, returning the result of {@code work}. */
<T> T transaction(Supplier<T> work);
}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.api.storage;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
/**
* One row of a table in its stored form, given to migrations: the key and the columns by
* their {@code snake_case} names. Integers and booleans are stored as {@code Long}, other
* numbers as {@code Double}, texts (also UUIDs, instants, and enum constants) as
* {@code String}, bytes as {@code byte[]}.
*/
public interface Row
{
String key();
/** The names of the stored columns. */
Set<String> columns();
/** The stored value, or {@code null} when it is null. @throws IllegalArgumentException for an unknown column */
@Nullable Object get(String column);
@Nullable String getString(String column);
/** @throws IllegalStateException when the value is null */
long getLong(String column);
/** @throws IllegalStateException when the value is null */
double getDouble(String column);
/** @throws IllegalStateException when the value is null */
boolean getBoolean(String column);
byte @Nullable [] getBytes(String column);
}
@@ -0,0 +1,14 @@
package dev.overlord.zomboidforge.api.storage;
import java.io.Serial;
/** A storage operation failed: a database error, or a table that does not match its record. */
public final class StorageException extends RuntimeException
{
@Serial
private static final long serialVersionUID = 1L;
public StorageException(String message) { super(message); }
public StorageException(String message, Throwable cause) { super(message, cause); }
}
@@ -0,0 +1,58 @@
package dev.overlord.zomboidforge.api.storage;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
/**
* Rows of type {@code R}, each under a {@code String} key. Every write commits immediately,
* unless it runs inside {@link ModStorage#transaction}. Calls block; on the main thread they
* are only allowed during startup.
*/
public interface Table<R extends Record>
{
/** Stores {@code value} under {@code key}, replacing an existing row. */
void set(String key, R value);
/** Stores every entry in one transaction. */
void setAll(Map<String, R> values);
Optional<R> get(String key);
/** The rows of the given keys that exist. */
Map<String, R> getAll(Collection<String> keys);
boolean contains(String key);
/** @return whether a row was removed */
boolean delete(String key);
/** @return the number of rows removed */
int deleteAll(Collection<String> keys);
/** Every key, sorted. */
List<String> keys();
/**
* Calls {@code action} for every row, sorted by key, without loading all rows at once.
* Storage of every mod waits until it returns, so {@code action} must not wait for other
* threads.
*/
void forEach(BiConsumer<String, R> action);
long count();
/**
* Replaces the row under {@code key} with {@code change} applied to it, or to
* {@code initial} when there is none, in one transaction: no other write comes in between.
* As in {@link ModStorage#transaction}, {@code change} and {@code initial} must not wait for
* other threads.
*
* @return the stored value
*/
R update(String key, UnaryOperator<R> change, Supplier<R> initial);
}
@@ -0,0 +1,33 @@
package dev.overlord.zomboidforge.api.storage;
import java.util.function.Function;
/**
* A table to open with a schema version and migrations:
*
* <pre>{@code
* Table<Balance> balances = this.storage().define("balances", Balance.class)
* .version(2)
* .migrate(1, row -> new Balance(row.getLong("coins"), null))
* .open();
* }</pre>
*/
public interface TableDefinition<R extends Record>
{
/** Schema version of the record, at least 1. Default: 1. */
TableDefinition<R> version(int version);
/**
* How to turn a row stored with schema version {@code from} into the current record. Needed
* when the stored version is older than {@link #version} or the record changed in a way that
* cannot be applied without data.
*/
TableDefinition<R> migrate(int from, Function<Row, R> migration);
/**
* Creates the table, or checks the stored one against the record and migrates it.
*
* @throws StorageException when the stored table does not match and no migration applies
*/
Table<R> open();
}
@@ -0,0 +1,10 @@
/**
* Per-world storage for mods: record tables in a SQLite database next to the save, kept
* apart by mod id.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.api.storage;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1,4 +1,4 @@
package dev.overlord.zomboidforge.patcher; package dev.overlord.zomboidforge.api;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -7,9 +7,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
class GameVersionTest { class GameVersionTest
{
@Test @Test
void parsesTwoAndThreePartVersions() { void parsesTwoAndThreePartVersions()
{
assertEquals(new GameVersion(42, 21, 0), GameVersion.parse("42.21")); assertEquals(new GameVersion(42, 21, 0), GameVersion.parse("42.21"));
assertEquals(new GameVersion(42, 21, 3), GameVersion.parse("42.21.3")); assertEquals(new GameVersion(42, 21, 3), GameVersion.parse("42.21.3"));
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42")); assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42"));
@@ -17,17 +19,44 @@ class GameVersionTest {
} }
@Test @Test
void twoPartExpectationMatchesEveryBuild() { void prefixMatchesEveryMissingPart()
{
GameVersion version = new GameVersion(42, 21, 3); GameVersion version = new GameVersion(42, 21, 3);
assertTrue(version.matches("42"));
assertTrue(version.matches("42.21")); assertTrue(version.matches("42.21"));
assertTrue(version.matches("42.21.3")); assertTrue(version.matches("42.21.3"));
assertFalse(version.matches("42.21.0")); assertFalse(version.matches("41"));
assertFalse(version.matches("42.20")); assertFalse(version.matches("42.20"));
assertFalse(version.matches("42.21.0"));
assertFalse(version.matches("4"));
} }
@Test @Test
void comparesNumerically() { void rejectsMalformedPrefixes()
{
GameVersion version = new GameVersion(42, 21, 3);
assertThrows(IllegalArgumentException.class, () -> version.matches(""));
assertThrows(IllegalArgumentException.class, () -> version.matches("42."));
assertThrows(IllegalArgumentException.class, () -> version.matches("42.21.3.1"));
}
@Test
void rejectsNumbersOutsideTheIntRange()
{
GameVersion version = new GameVersion(42, 21, 3);
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42.99999999999"));
assertThrows(IllegalArgumentException.class, () -> version.matches("99999999999"));
assertFalse(GameVersion.isPrefix("42.99999999999"));
}
@Test
void comparesNumerically()
{
GameVersion version = new GameVersion(42, 21, 0); GameVersion version = new GameVersion(42, 21, 0);
assertTrue(version.isAtLeast(42, 9)); assertTrue(version.isAtLeast(42, 9));
assertTrue(version.isAtLeast(42, 21)); assertTrue(version.isAtLeast(42, 21));
assertFalse(version.isAtLeast(42, 22)); assertFalse(version.isAtLeast(42, 22));
@@ -2,6 +2,22 @@ plugins {
java java
} }
// Version: -Pversion if given, else the newest v* git tag, else 0.0.0-prerelease.
if (version == Project.DEFAULT_VERSION)
{
val latestTag = providers.exec {
workingDir = layout.settingsDirectory.asFile
commandLine("git", "describe", "--tags", "--abbrev=0", "--match", "v*")
isIgnoreExitValue = true
}
version = latestTag.standardOutput.asText
.map { it.trim().removePrefix("v") }
.orElse("")
.get()
.ifEmpty { "0.0.0-prerelease" }
}
val projectZomboid = extensions.create<ProjectZomboidExtension>("projectZomboid") val projectZomboid = extensions.create<ProjectZomboidExtension>("projectZomboid")
projectZomboid.serverJar.convention( projectZomboid.serverJar.convention(
layout.settingsDirectory.file( layout.settingsDirectory.file(
@@ -0,0 +1,23 @@
// Publishing to the Maven registry of the ZomboidForge Gitea. Credentials come from the Gradle
// properties giteaUsername and giteaPassword (or ORG_GRADLE_PROJECT_giteaUsername and
// ORG_GRADLE_PROJECT_giteaPassword), and are only read when a publish task runs.
plugins {
`maven-publish`
}
publishing {
repositories {
maven {
name = "gitea"
url = uri("https://git.security-command.org/api/packages/overlord/maven")
credentials(PasswordCredentials::class)
}
// build/repo of the root project: for the Gradle plugin's functional tests.
maven {
name = "build"
url = uri(layout.settingsDirectory.dir("build/repo"))
}
}
}
Executable
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env bash
#
# Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the
# Gradle plugin (dev.overlord.zomboidforge.mod) to the Maven registry of the ZomboidForge Gitea,
# in the version of the v* git tag on HEAD, without the "v".
#
# A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never
# published. Without a v* tag on HEAD nothing is published.
#
# Usage:
# ci/publish.sh test runs the checks of the published modules; needs no credentials
# ci/publish.sh publish publishes them without running the checks again
#
# Environment (publish only):
# ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access
# ORG_GRADLE_PROJECT_giteaPassword Token of that user
set -o errexit
set -o nounset
set -o pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
readonly REPO_ROOT
readonly MODULES=(
api
mod-tools
gradle-plugin
)
log() {
echo "[publish] $*" >&2
}
# Prints the v* tag on HEAD without its "v", or nothing.
release_tag_version() {
local tag
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
echo "${tag#v}"
fi
}
# Gradle tasks for every module, e.g. ":api:check".
module_tasks() {
local task="$1"
local module
for module in "${MODULES[@]}"; do
echo ":${module}:${task}"
done
}
run_gradle() {
local version="$1"
shift
"${REPO_ROOT}/gradlew" \
--no-daemon \
--project-dir "${REPO_ROOT}" \
"-Pversion=${version}" \
"$@"
}
run_tests() {
local version="$1"
local check_tasks
mapfile -t check_tasks < <(module_tasks check)
log "Testing ZomboidForge ${version}: ${MODULES[*]}"
run_gradle "${version}" :core:check "${check_tasks[@]}"
}
publish() {
local version="$1"
local publish_tasks
if [[ "${version}" == *-* ]]; then
log "${version} is a pre-release version; nothing is published."
return
fi
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
log "Publishing ZomboidForge ${version}"
run_gradle "${version}" "${publish_tasks[@]}"
log "Published ${MODULES[*]} ${version}"
}
main() {
local step="${1:-}"
local version
version="$(release_tag_version)"
if [[ -z "${version}" ]]; then
log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish."
exit 1
fi
case "${step}" in
test)
run_tests "${version}"
;;
publish)
publish "${version}"
;;
*)
log "Usage: ci/publish.sh test|publish"
exit 2
;;
esac
}
main "$@"
+83 -24
View File
@@ -1,19 +1,30 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# #
# Builds the ZomboidForge image for one Project Zomboid version and optionally # Builds the ZomboidForge image for the current build of a Steam branch and optionally
# publishes it. Published tags: # publishes it. Published tags:
# #
# <forge>-pz<pz>-build<steam_buildid> immutable; never overwritten # <forge>-pz<major.minor.build> written once per ZomboidForge and Project Zomboid version
# <forge>-pz<pz> moves to the newest Steam build of that version # <forge>-pz<major.minor> moves to the newest hotfix of that minor version
# latest only with LATEST=true # latest only with LATEST=true
# #
# Nothing is built when the immutable tag already exists in the registry. # <major.minor.build> is the version the branch's server jar reports, read before the full
# build (Dockerfile stage game-version, which downloads only the jar).
#
# <forge> is the v* git tag on HEAD, without the "v" (v0.2.0 -> 0.2.0). When HEAD has no such
# tag, it is the git describe version of HEAD (0.2.0-3-g1a2b3c4: 3 commits after v0.2.0).
# A pre-release version (containing "-", e.g. 0.2.0-rc.1 or 0.2.0-3-g1a2b3c4) is built and
# verified but never published. Without any v* tag the version is "0.0.0-prerelease".
#
# Nothing is built when <forge>-pz<major.minor.build> already exists in the registry. The
# server only admits clients with the same major.minor.build, so every hotfix (42.21.1 ->
# 42.21.2) gets an image; a new Steam build with an unchanged version does not.
# #
# Environment: # Environment:
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge # IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
# PZ_BRANCH Steam branch. Default: public # PZ_BRANCH Steam branch. Default: public
# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties # PZ_VERSION Accepted Project Zomboid versions ("42": every Build 42 version).
# PUBLISH true: push the tags. Default: false (build and verify only) # Default: pz.version in gradle.properties
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only)
# LATEST true: also push "latest". Default: false # LATEST true: also push "latest". Default: false
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman # CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
@@ -26,7 +37,7 @@ readonly REPO_ROOT
readonly IMAGE="${IMAGE:?IMAGE is required}" readonly IMAGE="${IMAGE:?IMAGE is required}"
readonly PZ_BRANCH="${PZ_BRANCH:-public}" readonly PZ_BRANCH="${PZ_BRANCH:-public}"
readonly PUBLISH="${PUBLISH:-false}" readonly REQUESTED_PUBLISH="${PUBLISH:-false}"
readonly LATEST="${LATEST:-false}" readonly LATEST="${LATEST:-false}"
log() { log() {
@@ -59,11 +70,40 @@ gradle_property() {
exit 1 exit 1
} }
# Prints the forge version without the "v": the v* tag on HEAD, else the git describe version
# of HEAD relative to the newest reachable v* tag (v0.2.0-3-g1a2b3c4), or nothing when the
# repository has no such tag.
release_tag_version() {
local tag
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
echo "${tag#v}"
elif tag="$(git -C "${REPO_ROOT}" describe --tags --match 'v*' 2> /dev/null)"; then
echo "${tag#v}"
fi
}
image_exists() { image_exists() {
local reference="$1" local reference="$1"
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1 "$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
} }
# Prints the game version of the branch's current server jar, e.g. 42.21.0. Downloads only
# the jar; the result stays cached until the build ID changes.
read_game_version() {
local build_id="$1"
local image
image="$("$(container_engine)" build --quiet \
--platform linux/amd64 \
--target game-version \
--build-arg "PZ_BRANCH=${PZ_BRANCH}" \
--build-arg "STEAM_BUILDID=${build_id}" \
"${REPO_ROOT}")"
"$(container_engine)" run --rm --entrypoint cat "${image}" /game-version
}
build_image() { build_image() {
local reference="$1" local reference="$1"
local forge_version="$2" local forge_version="$2"
@@ -104,35 +144,54 @@ push_as() {
main() { main() {
local forge_version local forge_version
local pz_version local publish="${REQUESTED_PUBLISH}"
local pz_prefix
local build_id local build_id
local game_version
forge_version="$(gradle_property version)" forge_version="$(release_tag_version)"
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}" if [[ -z "${forge_version}" ]]; then
forge_version="0.0.0-prerelease"
log "No v* git tag found (shallow clone without tags?); using version ${forge_version}."
fi
if [[ "${forge_version}" == *-* ]]; then
publish=false
log "${forge_version} is a pre-release version; nothing will be published."
fi
pz_prefix="${PZ_VERSION:-$(gradle_property pz.version)}"
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")" build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
game_version="$(read_game_version "${build_id}")"
log "ZomboidForge ${forge_version}, Project Zomboid ${game_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
local immutable_tag="${IMAGE}:${forge_version}-pz${pz_version}-build${build_id}" # Checked here as well as by the patcher, to fail before the full download.
local version_tag="${IMAGE}:${forge_version}-pz${pz_version}" if [[ "${game_version}" != "${pz_prefix}" && "${game_version}" != "${pz_prefix}."* ]]; then
log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}" log "Steam branch ${PZ_BRANCH} has Project Zomboid ${game_version}; the build accepts ${pz_prefix}."
exit 1
fi
if [[ "${PUBLISH}" == true ]] && image_exists "${immutable_tag}"; then local version_tag="${IMAGE}:${forge_version}-pz${game_version}"
log "${immutable_tag} is already published; nothing to do." # 42.21.2 -> 42.21
local minor_tag="${IMAGE}:${forge_version}-pz${game_version%.*}"
if [[ "${publish}" == true ]] && image_exists "${version_tag}"; then
log "${version_tag} is already published; nothing to do."
return return
fi fi
build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}" build_image "${version_tag}" "${forge_version}" "${game_version}" "${build_id}"
verify_build_id "${immutable_tag}" "${build_id}" verify_build_id "${version_tag}" "${build_id}"
if [[ "${PUBLISH}" != true ]]; then if [[ "${publish}" != true ]]; then
log "Built ${immutable_tag} (PUBLISH is not true; nothing pushed)" log "Built ${version_tag} (not published)"
return return
fi fi
"$(container_engine)" push "${immutable_tag}" "$(container_engine)" push "${version_tag}"
log "Pushed ${immutable_tag}" log "Pushed ${version_tag}"
push_as "${immutable_tag}" "${version_tag}" push_as "${version_tag}" "${minor_tag}"
if [[ "${LATEST}" == true ]]; then if [[ "${LATEST}" == true ]]; then
push_as "${immutable_tag}" "${IMAGE}:latest" push_as "${version_tag}" "${IMAGE}:latest"
fi fi
} }
+1 -1
View File
@@ -14,7 +14,7 @@ set -o nounset
set -o pipefail set -o pipefail
readonly APP_ID="380870" readonly APP_ID="380870"
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13" readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d"
readonly BRANCH="$1" readonly BRANCH="$1"
+7
View File
@@ -5,6 +5,13 @@ plugins {
} }
dependencies { dependencies {
implementation(project(":api"))
implementation(project(":patcher")) implementation(project(":patcher"))
implementation(libs.bundles.asm) implementation(libs.bundles.asm)
// Hook classes are read as class files to check that the patches' hooks exist.
testImplementation(project(":compat:b42:runtime"))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
} }
@@ -0,0 +1,32 @@
package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.compat.b42.patches.*;
import dev.overlord.zomboidforge.compat.b42.perf.*;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.PatchSet;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/** Every build-time patch for Build 42, in application order. */
public final class B42PatchSet implements PatchSet
{
private static final List<ClassPatch> PATCHES = List.of(
new ServerLoadPatch(),
new ServerStartedPatch(),
new ServerTickPatch(),
new ServerStoppingPatch(),
new BackupStoragePatch(),
new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(),
new IsoGameCharacterStateMachinePerformancePatch()
);
@Override
public int build() { return 42; }
@Override
public @NotNull List<ClassPatch> patches() { return B42PatchSet.PATCHES; }
}
@@ -1,21 +0,0 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.PatchSet;
import java.util.List;
/** Every build-time patch for Build 42, in application order. */
public final class B42PatchSet implements PatchSet {
private static final List<ClassPatch> PATCHES = List.of();
@Override
public int build() {
return 42;
}
@Override
public List<ClassPatch> patches() {
return PATCHES;
}
}
@@ -0,0 +1,115 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.Hook;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* Wraps {@code ZipBackup.makeBackupFile(String, BackupTypes)}, which zips the save folder
* including {@code zomboidforge.db}, so that storage writes wait during a backup:
*
* <pre>{@code
* private static void makeBackupFile(String serverName, BackupTypes type)
* {
* StorageHooks.backupRunning(true);
* try { zomboidForge$makeBackupFile(serverName, type); }
* finally { StorageHooks.backupRunning(false); }
* }
* }</pre>
*
* The vanilla method is renamed to {@code zomboidForge$makeBackupFile} and stays unchanged. It
* reads the zipped files until {@code ParallelScatterZipCreator.writeTo} returns and catches its
* own exceptions, so only a wrapper around the whole method covers the entire backup.
*/
public final class BackupStoragePatch implements ClassPatch
{
private static final String TARGET = "zombie/core/backup/ZipBackup";
private static final String RENAMED = "zomboidForge$makeBackupFile";
private static final Anchor.Method ANCHOR = new Anchor.Method(
"makeBackupFile", "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks", "backupRunning", "(Z)V"
);
@Override
public String target() { return BackupStoragePatch.TARGET; }
@Override
public Anchor.Method anchor() { return BackupStoragePatch.ANCHOR; }
@Override
public Hook hook() { return BackupStoragePatch.HOOK; }
@Override
public void apply(ClassNode node)
{
MethodNode original = BackupStoragePatch.ANCHOR.resolve(node);
if ((original.access & Opcodes.ACC_STATIC) == 0)
throw new IllegalStateException("'" + node.name + "." + original.name + original.desc + "' is not static.");
boolean taken = node.methods.stream().anyMatch(method -> method.name.equals(BackupStoragePatch.RENAMED));
if (taken) throw new IllegalStateException("'" + node.name + "' already has a method '" + BackupStoragePatch.RENAMED + "'.");
MethodNode wrapper = new MethodNode(original.access, original.name, original.desc, original.signature, original.exceptions.toArray(String[]::new));
original.name = BackupStoragePatch.RENAMED;
BackupStoragePatch.wrap(node.name, original.desc, wrapper);
node.methods.add(wrapper);
}
/** {@code hook(true); try { renamed(args); } finally { hook(false); }} */
private static void wrap(String owner, String desc, MethodNode wrapper)
{
Type[] arguments = Type.getArgumentTypes(desc);
int thrown = arguments.length;
LabelNode start = new LabelNode();
LabelNode end = new LabelNode();
LabelNode handler = new LabelNode();
InsnList code = wrapper.instructions;
for (Type argument : arguments) {
if (argument.getSize() != 1) throw new IllegalStateException("'" + owner + "." + BackupStoragePatch.ANCHOR.name() + desc + "' has a wide argument; the wrapper only passes one-slot arguments.");
}
code.add(BackupStoragePatch.hook(true));
code.add(start);
for (int i = 0; i < arguments.length; i++) code.add(new VarInsnNode(arguments[i].getOpcode(Opcodes.ILOAD), i));
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, owner, BackupStoragePatch.RENAMED, desc, false));
code.add(end);
code.add(BackupStoragePatch.hook(false));
code.add(new InsnNode(Opcodes.RETURN));
code.add(handler);
code.add(new VarInsnNode(Opcodes.ASTORE, thrown));
code.add(BackupStoragePatch.hook(false));
code.add(new VarInsnNode(Opcodes.ALOAD, thrown));
code.add(new InsnNode(Opcodes.ATHROW));
wrapper.tryCatchBlocks.add(new TryCatchBlockNode(start, end, handler, null));
}
private static InsnList hook(boolean running)
{
InsnList code = new InsnList();
code.add(new InsnNode(running ? Opcodes.ICONST_1 : Opcodes.ICONST_0));
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, BackupStoragePatch.HOOK.owner(), BackupStoragePatch.HOOK.name(), BackupStoragePatch.HOOK.desc(), false));
return code;
}
}
@@ -0,0 +1,100 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.Hook;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodInsnNode;
/**
* Calls {@code ServerHooks.onLoad()} in {@code GameServer.main}, directly after
* {@code ServerOptions.instance.init()}, and stops the server when it returns {@code false}:
*
* <pre>{@code
* if (!ServerHooks.onLoad()) {
* Runtime.getRuntime().removeShutdownHook(shutdownHook);
* System.exit(1);
* }
* }</pre>
*
* The vanilla shutdown hook saves the map on every JVM exit; before the world is loaded that
* save fails with a {@code NullPointerException} in {@code IsoMetaGrid.save()}. The inserted
* code is part of {@code GameServer}, so it reads the private field {@code shutdownHook}
* directly.
*/
public final class ServerLoadPatch implements ClassPatch
{
private static final String TARGET = "zombie/network/GameServer";
private static final String SHUTDOWN_HOOK = "shutdownHook";
private static final String SHUTDOWN_HOOK_DESC = "Ljava/lang/Thread;";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("main", "([Ljava/lang/String;)V"),
"zombie/network/ServerOptions", "init", "()V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onLoad", "()Z"
);
@Override
public String target() { return ServerLoadPatch.TARGET; }
@Override
public Anchor.Call anchor() { return ServerLoadPatch.ANCHOR; }
@Override
public Hook hook() { return ServerLoadPatch.HOOK; }
@Override
public void apply(ClassNode node)
{
ServerLoadPatch.requireShutdownHookField(node);
MethodInsnNode init = ServerLoadPatch.ANCHOR.resolve(node);
ServerLoadPatch.ANCHOR.in().resolve(node).instructions.insert(init, ServerLoadPatch.abortUnlessLoaded());
}
/** The abort path runs only when a mod fails, so a missing field would otherwise go unnoticed until then. */
private static void requireShutdownHookField(ClassNode node)
{
boolean found = node.fields.stream().anyMatch(ServerLoadPatch::isShutdownHook);
if (!found) throw new IllegalStateException("Expected the static field '" + node.name + "." + ServerLoadPatch.SHUTDOWN_HOOK + " " + ServerLoadPatch.SHUTDOWN_HOOK_DESC + "'.");
}
private static boolean isShutdownHook(FieldNode field)
{
return field.name.equals(ServerLoadPatch.SHUTDOWN_HOOK)
&& field.desc.equals(ServerLoadPatch.SHUTDOWN_HOOK_DESC)
&& (field.access & Opcodes.ACC_STATIC) != 0;
}
private static InsnList abortUnlessLoaded()
{
InsnList code = new InsnList();
LabelNode loaded = new LabelNode();
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ServerLoadPatch.HOOK.owner(), ServerLoadPatch.HOOK.name(), ServerLoadPatch.HOOK.desc(), false));
code.add(new JumpInsnNode(Opcodes.IFNE, loaded));
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false));
code.add(new FieldInsnNode(Opcodes.GETSTATIC, ServerLoadPatch.TARGET, ServerLoadPatch.SHUTDOWN_HOOK, ServerLoadPatch.SHUTDOWN_HOOK_DESC));
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Runtime", "removeShutdownHook", "(Ljava/lang/Thread;)Z", false));
code.add(new InsnNode(Opcodes.POP));
code.add(new InsnNode(Opcodes.ICONST_1));
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/System", "exit", "(I)V", false));
code.add(loaded);
return code;
}
}
@@ -0,0 +1,26 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch;
/**
* Calls {@code ServerHooks.onServerStarted()} in {@code GameServer.main}, directly after
* {@code UnitTests.runIfEnabled()} and before the {@code while (!done)} main loop: the world is
* loaded, the network port is open, and RCON is initialized.
*/
public final class ServerStartedPatch extends HookInjectionPatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("main", "([Ljava/lang/String;)V"),
"zombie/UnitTests", "runIfEnabled", "()V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onServerStarted", "()V"
);
public ServerStartedPatch() {
super("zombie/network/GameServer", ServerStartedPatch.ANCHOR, ServerStartedPatch.HOOK);
}
}
@@ -0,0 +1,67 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.Hook;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import java.util.List;
/**
* Calls {@code ServerHooks.onStopping()} in the vanilla shutdown hook {@code GameServer$1.run()},
* between {@code GameServer.done = true} and {@code ServerMap.instance.QueuedQuit()}, which saves
* the world.
*
* <p>{@code GameServer$1} is the only caller of {@code QueuedQuit()}. The {@code quit} command
* only sets {@code ServerMap.queuedQuit}; {@code ServerMap.preupdate()} then calls
* {@code System.exit(0)}, so the save runs in the shutdown hook as it does for SIGTERM and SIGINT.
*/
public final class ServerStoppingPatch implements ClassPatch
{
private static final String GAME_SERVER = "zombie/network/GameServer";
/** {@code GameServer.done = true; ServerMap.instance.QueuedQuit();} */
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
new Anchor.Method("run", "()V"),
new Anchor.Instruction.Constant(1),
new Anchor.Instruction.Opcode(Opcodes.PUTSTATIC),
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
new Anchor.Instruction.Invoke("zombie/network/ServerMap", "QueuedQuit", "()V")
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onStopping", "()V"
);
@Override
public String target() { return ServerStoppingPatch.GAME_SERVER + "$1"; }
@Override
public Anchor.Sequence anchor() { return ServerStoppingPatch.ANCHOR; }
@Override
public Hook hook() { return ServerStoppingPatch.HOOK; }
@Override
public void apply(ClassNode node)
{
List<AbstractInsnNode> matched = ServerStoppingPatch.ANCHOR.resolve(node);
FieldInsnNode done = (FieldInsnNode) matched.get(1);
if (!done.owner.equals(ServerStoppingPatch.GAME_SERVER) || !done.name.equals("done"))
throw new IllegalStateException("'" + node.name + ".run()V' sets '" + done.owner + "." + done.name + "' before 'QueuedQuit()', expected '" + ServerStoppingPatch.GAME_SERVER + ".done'.");
ServerStoppingPatch.ANCHOR.in().resolve(node).instructions.insert(
done, new MethodInsnNode(
Opcodes.INVOKESTATIC,
ServerStoppingPatch.HOOK.owner(),
ServerStoppingPatch.HOOK.name(),
ServerStoppingPatch.HOOK.desc(),
false
)
);
}
}
@@ -0,0 +1,27 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch;
/**
* Calls {@code ServerHooks.onTick()} in the main loop of {@code GameServer.main}, directly after
* {@code ServerMap.instance.preupdate()} at the start of the frame branch. The {@code while (!done)}
* loop itself also iterates while the update limiter skips a frame; the frame branch runs once
* per game frame.
*/
public final class ServerTickPatch extends HookInjectionPatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("main", "([Ljava/lang/String;)V"),
"zombie/network/ServerMap", "preupdate", "()V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onTick", "()V"
);
public ServerTickPatch() {
super("zombie/network/GameServer", ServerTickPatch.ANCHOR, ServerTickPatch.HOOK);
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.patches;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,172 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.Arrays;
import java.util.List;
/**
* Stores the {@code StateMachineComponent} of an {@code IsoGameCharacter} in a field, so that
* {@code getStateMachineComponent()} does not look it up in the entity's component map on every
* call. The lookup walks the class hierarchy of the component class and reads a {@code HashMap}.
*
* <p>The method is {@code final} and its whole body is the lookup. Every access to the component
* goes through it: the 12 call sites in {@code IsoGameCharacter}, among them
* {@code getStateMachine()}, {@code getActionContext()} and {@code getAdvancedAnimator()}, which
* zombies, players and animals call every frame.
* The patched method returns the stored component only while the component's owner is this
* character. {@code ECSEntity.setECSComponent} and {@code removeECSComponent} set the owner of a
* replaced or removed component to {@code null}, and adding the component to another entity
* changes its owner. In every other case the original lookup runs (and throws when the component
* is missing, as before), and its result is stored.
*/
public final class IsoGameCharacterStateMachinePerformancePatch extends PerformancePatch
{
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
private static final String FIELD_NAME = "zomboidForge$stateMachineComponent";
private static final String FIELD_DESC = "L" + IsoGameCharacterStateMachinePerformancePatch.COMPONENT + ";";
private static final Anchor.Method GETTER = new Anchor.Method("getStateMachineComponent", "()" + IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC);
/** {@code return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);} */
private static final Anchor.Sequence LOOKUP = new Anchor.Sequence(
IsoGameCharacterStateMachinePerformancePatch.GETTER,
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
new Anchor.Instruction.Constant(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatch.COMPONENT)),
new Anchor.Instruction.Invoke(
IsoGameCharacterStateMachinePerformancePatch.CHARACTER, "getECSComponent",
"(Ljava/lang/Class;)L" + IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT + ";"
),
new Anchor.Instruction.Opcode(Opcodes.CHECKCAST),
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
);
public IsoGameCharacterStateMachinePerformancePatch() {
super(IsoGameCharacterStateMachinePerformancePatch.CHARACTER, IsoGameCharacterStateMachinePerformancePatch.LOOKUP, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
IsoGameCharacterStateMachinePerformancePatch.requireNoFieldNamed(node);
MethodNode method = IsoGameCharacterStateMachinePerformancePatch.GETTER.resolve(node);
List<AbstractInsnNode> lookup = IsoGameCharacterStateMachinePerformancePatch.LOOKUP.resolve(node);
long instructions = Arrays.stream(method.instructions.toArray())
.filter(instruction -> instruction.getOpcode() != -1)
.count();
if (instructions != lookup.size())
throw new IllegalStateException("'" + node.name + ".getStateMachineComponent' does more than the component lookup.");
node.fields.add(new FieldNode(
Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC,
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC,
null, null
));
method.instructions.insertBefore(lookup.getLast(), IsoGameCharacterStateMachinePerformancePatch.store());
// The body is only the lookup, so the first slot after 'this' and the arguments is free.
int stored = Type.getArgumentsAndReturnSizes(method.desc) >> 2;
method.instructions.insert(IsoGameCharacterStateMachinePerformancePatch.returnStored(stored));
}
/** The patch must not collide with a field of the game class, e.g. after an update. */
private static void requireNoFieldNamed(ClassNode node)
{
boolean exists = node.fields.stream()
.anyMatch(field -> field.name.equals(IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME));
if (exists) throw new IllegalStateException("'" + node.name + "' already has a field named '" + IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME + "'.");
}
/**
* Placed at the start of the method:
*
* <pre>{@code
* StateMachineComponent stored = this.zomboidForge$stateMachineComponent;
* if (stored != null && stored.getECSOwnerEntity() == this) return stored;
* }</pre>
*/
private static InsnList returnStored(int stored)
{
LabelNode lookup = new LabelNode();
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.GETFIELD));
code.add(new VarInsnNode(Opcodes.ASTORE, stored));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new JumpInsnNode(Opcodes.IFNULL, lookup));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new MethodInsnNode(
Opcodes.INVOKEVIRTUAL,
IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT,
"getECSOwnerEntity",
"()Lzombie/characters/ecs/ECSEntity;",
false
));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new JumpInsnNode(Opcodes.IF_ACMPNE, lookup));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new InsnNode(Opcodes.ARETURN));
code.add(lookup);
return code;
}
/**
* Placed before the {@code areturn} of the lookup, with the component on the operand stack:
* {@code this.zomboidForge$stateMachineComponent = component}, leaving the component on the stack.
*/
private static InsnList store()
{
InsnList code = new InsnList();
code.add(new InsnNode(Opcodes.DUP));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new InsnNode(Opcodes.SWAP));
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.PUTFIELD));
return code;
}
private static FieldInsnNode field(int opcode)
{
return new FieldInsnNode(
opcode,
IsoGameCharacterStateMachinePerformancePatch.CHARACTER,
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC
);
}
}
@@ -0,0 +1,236 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* Stores the {@code NetworkZombieComponent} of an {@code IsoZombie} in a field instead of
* looking it up in the entity's component map on every call.
*
* <p>Every call site in {@code IsoZombie} has the same shape:
* {@code (NetworkZombieComponent) this.tryGetECSComponent(NetworkZombieComponent.class)}. The
* lookup walks the class hierarchy of the component class and reads a {@code HashMap}. The
* component is registered once by the {@code IsoObject} constructor and is never replaced or
* removed, so a value read once stays valid for the life of the zombie.
*
* <p>The patch adds the field and a private method that fills it on first use, and replaces the
* three instructions of each call site with a call to that method. A missing component is not
* stored: the method then returns {@code null} like the lookup does.
*/
public final class IsoZombieNetworkComponentPerformancePatch extends PerformancePatch
{
private static final String ZOMBIE = "zombie/characters/IsoZombie";
private static final String COMPONENT = "zombie/characters/component/NetworkZombieComponent";
private static final String LOOKUP_NAME = "tryGetECSComponent";
private static final String LOOKUP_DESC = "(Ljava/lang/Class;)Lzombie/characters/ecs/ECSComponent;";
private static final String FIELD_NAME = "zomboidForge$networkComponent";
private static final String FIELD_DESC = "L" + IsoZombieNetworkComponentPerformancePatch.COMPONENT + ";";
private static final String ACCESSOR_NAME = "zomboidForge$networkComponent";
private static final String ACCESSOR_DESC = "()" + IsoZombieNetworkComponentPerformancePatch.FIELD_DESC;
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("getOwner", "()Lzombie/core/raknet/UdpConnection;"),
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC
);
public IsoZombieNetworkComponentPerformancePatch() {
super(IsoZombieNetworkComponentPerformancePatch.ZOMBIE, IsoZombieNetworkComponentPerformancePatch.ANCHOR, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
IsoZombieNetworkComponentPerformancePatch.requireNoMemberNamed(node);
node.fields.add(new FieldNode(Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC, IsoZombieNetworkComponentPerformancePatch.FIELD_NAME, IsoZombieNetworkComponentPerformancePatch.FIELD_DESC, null, null));
node.methods.add(IsoZombieNetworkComponentPerformancePatch.accessor());
for (MethodNode method : node.methods) {
IsoZombieNetworkComponentPerformancePatch.replaceLookups(method);
}
}
/** The patch must not collide with a member of the game class, e.g. after an update. */
private static void requireNoMemberNamed(ClassNode node)
{
boolean fieldExists = node.fields.stream()
.anyMatch(field -> field.name.equals(IsoZombieNetworkComponentPerformancePatch.FIELD_NAME));
boolean methodExists = node.methods.stream()
.anyMatch(method -> method.name.equals(IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME));
if (fieldExists || methodExists)
throw new IllegalStateException("'" + node.name + "' already has a member named '" + IsoZombieNetworkComponentPerformancePatch.FIELD_NAME + "'.");
}
/**
* <pre>{@code
* private NetworkZombieComponent zomboidForge$networkComponent()
* {
* NetworkZombieComponent component = this.zomboidForge$networkComponent;
*
* if (component == null) {
* component = (NetworkZombieComponent) this.tryGetECSComponent(NetworkZombieComponent.class);
* this.zomboidForge$networkComponent = component;
* }
*
* return component;
* }
* }</pre>
*/
private static MethodNode accessor()
{
MethodNode method = new MethodNode(
Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_DESC,
null, null
);
LabelNode filled = new LabelNode();
InsnList code = method.instructions;
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(
Opcodes.GETFIELD,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.FIELD_NAME,
IsoZombieNetworkComponentPerformancePatch.FIELD_DESC
));
code.add(new VarInsnNode(Opcodes.ASTORE, 1));
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new JumpInsnNode(Opcodes.IFNONNULL, filled));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new LdcInsnNode(Type.getObjectType(IsoZombieNetworkComponentPerformancePatch.COMPONENT)));
code.add(new MethodInsnNode(
Opcodes.INVOKEVIRTUAL,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC,
false
));
code.add(new TypeInsnNode(Opcodes.CHECKCAST, IsoZombieNetworkComponentPerformancePatch.COMPONENT));
code.add(new VarInsnNode(Opcodes.ASTORE, 1));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new FieldInsnNode(
Opcodes.PUTFIELD,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.FIELD_NAME,
IsoZombieNetworkComponentPerformancePatch.FIELD_DESC
));
code.add(filled);
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new InsnNode(Opcodes.ARETURN));
return method;
}
/**
* Replaces {@code ldc NetworkZombieComponent; invokevirtual tryGetECSComponent; checkcast
* NetworkZombieComponent} with {@code invokespecial zomboidForge$networkComponent}. The
* receiver is on the operand stack before and after, and the component instead of the
* {@code Class} leaves it, so the stack stays the same. The accessor itself is skipped: it
* contains the same three instructions.
*/
private static void replaceLookups(MethodNode method)
{
if (method.name.equals(IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME)) return;
for (AbstractInsnNode instruction : method.instructions.toArray())
{
if (!IsoZombieNetworkComponentPerformancePatch.isLookup(instruction)) continue;
@Nullable AbstractInsnNode load = IsoZombieNetworkComponentPerformancePatch.previousInstruction(instruction);
@Nullable AbstractInsnNode cast = IsoZombieNetworkComponentPerformancePatch.nextInstruction(instruction);
if (!IsoZombieNetworkComponentPerformancePatch.isComponentClassLiteral(load)) continue;
if (!IsoZombieNetworkComponentPerformancePatch.isComponentCast(cast)) continue;
method.instructions.remove(load);
method.instructions.remove(cast);
method.instructions.set(
instruction, new MethodInsnNode(
Opcodes.INVOKESPECIAL,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_DESC,
false
)
);
}
}
//
private static boolean isLookup(AbstractInsnNode instruction)
{
return instruction instanceof MethodInsnNode call
&& call.getOpcode() == Opcodes.INVOKEVIRTUAL
&& call.owner.equals(IsoZombieNetworkComponentPerformancePatch.ZOMBIE)
&& call.name.equals(IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME)
&& call.desc.equals(IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC);
}
private static boolean isComponentClassLiteral(@Nullable AbstractInsnNode instruction)
{
return instruction instanceof LdcInsnNode ldc
&& ldc.cst instanceof Type type
&& type.getInternalName().equals(IsoZombieNetworkComponentPerformancePatch.COMPONENT);
}
private static boolean isComponentCast(@Nullable AbstractInsnNode instruction)
{
return instruction instanceof TypeInsnNode cast
&& cast.getOpcode() == Opcodes.CHECKCAST
&& cast.desc.equals(IsoZombieNetworkComponentPerformancePatch.COMPONENT);
}
/** The closest earlier instruction that is not a label, line number, or frame; {@code null} at the start of the method. */
private static @Nullable AbstractInsnNode previousInstruction(AbstractInsnNode instruction)
{
AbstractInsnNode previous = instruction.getPrevious();
while (previous != null && previous.getOpcode() == -1) previous = previous.getPrevious();
return previous;
}
/** The closest later instruction that is not a label, line number, or frame; {@code null} at the end of the method. */
private static @Nullable AbstractInsnNode nextInstruction(AbstractInsnNode instruction)
{
AbstractInsnNode next = instruction.getNext();
while (next != null && next.getOpcode() == -1) next = next.getNext();
return next;
}
}
@@ -0,0 +1,126 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.List;
/**
* Skips the spot-chance modifiers in {@code IsoZombie.spottedNew} when the chance is already 0.
*
* <p>Between {@code if (bForced) chance = 1000000F} and {@code chance = (float)
* PZMath.fastfloor(chance)} the method only multiplies or divides {@code chance}: bonus spot
* time, sight, inactivity, traits of the player, shelter ({@code getObstacleMod}),
* {@code isVehicleBetween}, worn items, eating. A chance of 0 stays 0, or becomes NaN when divided
* by 0, and the roll {@code Rand.Next(10000) / 100F < chance} fails for both. The chance is 0 when
* the player is outside the zombie's vision radius or behind it, and is never 0 for a forced spot.
*
* <p>The patch inserts {@code if (chance == 0F) goto rounding} after the forced-spot assignment.
* The rounding, the roll (with its {@code Rand.Next} draw) and the failed-roll branch run as in
* vanilla. The early return for a nearer current target comes before the jump. The skipped code
* writes no field or local that is read after the jump; it writes the shared scratch vector
* {@code IsoGameCharacter.tempo}, which other code sets before reading, except client debug drawing.
*/
public final class IsoZombieSpotChancePerformancePatch extends PerformancePatch
{
private static final Anchor.Method SPOTTED_NEW = new Anchor.Method("spottedNew", "(Lzombie/iso/IsoMovingObject;Z)V");
/** {@code if (bForced) chance = 1000000F;}: the store of the forced chance. */
private static final Anchor.Sequence FORCED_CHANCE = new Anchor.Sequence(
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
new Anchor.Instruction.Constant(1000000.0F),
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
);
/** {@code chance = (float) PZMath.fastfloor(chance);}: the rounding before the roll. */
private static final Anchor.Sequence ROUNDING = new Anchor.Sequence(
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
new Anchor.Instruction.Opcode(Opcodes.FLOAD),
new Anchor.Instruction.Invoke("zombie/core/math/PZMath", "fastfloor", "(F)I"),
new Anchor.Instruction.Opcode(Opcodes.I2F),
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
);
public IsoZombieSpotChancePerformancePatch() {
super("zombie/characters/IsoZombie", IsoZombieSpotChancePerformancePatch.FORCED_CHANCE, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoZombieSpotChancePerformancePatch.SPOTTED_NEW.resolve(node);
List<AbstractInsnNode> forced = IsoZombieSpotChancePerformancePatch.FORCED_CHANCE.resolve(node);
List<AbstractInsnNode> rounding = IsoZombieSpotChancePerformancePatch.ROUNDING.resolve(node);
AbstractInsnNode forcedStore = forced.getLast();
AbstractInsnNode roundingLoad = rounding.getFirst();
int chance = ((VarInsnNode) forcedStore).var;
IsoZombieSpotChancePerformancePatch.requireVariable(roundingLoad, chance);
IsoZombieSpotChancePerformancePatch.requireVariable(rounding.getLast(), chance);
if (method.instructions.indexOf(roundingLoad) < method.instructions.indexOf(forcedStore))
throw new IllegalStateException("'" + node.name + ".spottedNew': the rounding of 'chance' comes before the forced-spot assignment.");
// The check goes after the label that the 'if (bForced)' jump targets, so both paths run it.
// Inserting it before the new label keeps it ahead of that label if both precede the same instruction.
LabelNode roundingLabel = new LabelNode();
method.instructions.insertBefore(
IsoZombieSpotChancePerformancePatch.nextInstruction(forcedStore),
IsoZombieSpotChancePerformancePatch.jumpIfZero(chance, roundingLabel)
);
method.instructions.insertBefore(roundingLoad, roundingLabel);
}
/**
* {@code if (chance == 0F) goto target}. {@code fcmpl} pushes -1 for NaN, so NaN does not
* jump; -0F does.
*/
private static InsnList jumpIfZero(int chance, LabelNode target)
{
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.FLOAD, chance));
code.add(new InsnNode(Opcodes.FCONST_0));
code.add(new InsnNode(Opcodes.FCMPL));
code.add(new JumpInsnNode(Opcodes.IFEQ, target));
return code;
}
private static void requireVariable(AbstractInsnNode instruction, int chance)
{
int variable = ((VarInsnNode) instruction).var;
if (variable != chance)
throw new IllegalStateException("'IsoZombie.spottedNew': the rounding uses local " + variable + ", the forced-spot assignment local " + chance + ".");
}
/** The closest later instruction that is not a label, line number, or frame. */
private static AbstractInsnNode nextInstruction(AbstractInsnNode instruction)
{
AbstractInsnNode next = instruction.getNext();
while (next != null && next.getOpcode() == -1) next = next.getNext();
if (next == null) throw new IllegalStateException("'IsoZombie.spottedNew' ends after the forced-spot assignment.");
return next;
}
}
@@ -0,0 +1,92 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Makes {@code IsoZombie.isVehicleBetween} cheaper without changing its result, in two steps:
*
* <ul>
* <li>Returns {@code false} at the start of the method when the cell has no vehicles. The
* loop would not run, but the three pooled vectors are allocated and released first.</li>
* <li>Replaces the call to {@code BaseVehicle.getIntersectPoint} with
* {@code ZombieVehicleHooks.getIntersectPoint}, which skips vehicles that the segment
* cannot reach.</li>
* </ul>
*/
public final class IsoZombieVehiclePerformancePatch extends PerformancePatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("isVehicleBetween", "(FFF)Z"),
"zombie/vehicles/BaseVehicle", "getIntersectPoint",
"(Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", "getIntersectPoint",
"(Lzombie/vehicles/BaseVehicle;Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
);
public IsoZombieVehiclePerformancePatch() {
super("zombie/characters/IsoZombie", IsoZombieVehiclePerformancePatch.ANCHOR, IsoZombieVehiclePerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoZombieVehiclePerformancePatch.ANCHOR.in().resolve(node);
MethodInsnNode call = IsoZombieVehiclePerformancePatch.ANCHOR.resolve(node);
// The hook takes the receiver as its first argument, so the operand stack is the same
// as for the virtual call it replaces: vehicle, start, end, result -> Vector3f.
method.instructions.set(call, new MethodInsnNode(
Opcodes.INVOKESTATIC,
IsoZombieVehiclePerformancePatch.HOOK.owner(),
IsoZombieVehiclePerformancePatch.HOOK.name(),
IsoZombieVehiclePerformancePatch.HOOK.desc(),
false
));
method.instructions.insert(IsoZombieVehiclePerformancePatch.returnFalseWithoutVehicles());
}
/**
* {@code if (IsoWorld.instance.currentCell.getVehicles().isEmpty()) return false;}, the same
* expression the method iterates over. The method starts with an empty operand stack, so the
* stack map frame at the jump target is the one of the method entry; the class writer
* computes it.
*/
private static InsnList returnFalseWithoutVehicles()
{
LabelNode hasVehicles = new LabelNode();
InsnList code = new InsnList();
code.add(new FieldInsnNode(Opcodes.GETSTATIC, "zombie/iso/IsoWorld", "instance", "Lzombie/iso/IsoWorld;"));
code.add(new FieldInsnNode(Opcodes.GETFIELD, "zombie/iso/IsoWorld", "currentCell", "Lzombie/iso/IsoCell;"));
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "zombie/iso/IsoCell", "getVehicles", "()Ljava/util/Set;", false));
code.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, "java/util/Set", "isEmpty", "()Z", true));
code.add(new JumpInsnNode(Opcodes.IFEQ, hasVehicles));
code.add(new InsnNode(Opcodes.ICONST_0));
code.add(new InsnNode(Opcodes.IRETURN));
code.add(hasVehicles);
return code;
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.perf;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1 +1 @@
dev.overlord.zomboidforge.compat.b42.patches.B42PatchSet dev.overlord.zomboidforge.compat.b42.B42PatchSet
@@ -0,0 +1,158 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ATHROW;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class BackupStoragePatchTest
{
private static final String ZIP_BACKUP = "zombie/core/backup/ZipBackup";
private static final String TYPES = "zombie/core/backup/ZipBackup$BackupTypes";
private static final String DESC = "(Ljava/lang/String;L" + BackupStoragePatchTest.TYPES + ";)V";
private static final String CALLS = Type.getInternalName(BackupStoragePatchTest.Calls.class);
/** Stands in for {@code StorageHooks.backupRunning(boolean)} and records the calls. */
public static final class Calls
{
public static final List<String> LOG = new ArrayList<>();
private Calls() {}
public static void record(String call) { Calls.LOG.add(call); }
public static void backupRunning(boolean running) { Calls.LOG.add("backupRunning " + running); }
}
/**
* {@code ZipBackup} with the vanilla method's shape:
*
* <pre>{@code
* private static void makeBackupFile(String serverName, BackupTypes type)
* {
* if (serverName.equals("fail")) throw new IllegalStateException("zip failed");
* Calls.record("backup " + serverName);
* }
* }</pre>
*/
private static ClassNode zipBackup()
{
ClassNode node = BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.ZIP_BACKUP);
MethodVisitor method = node.visitMethod(ACC_PRIVATE | ACC_STATIC, "makeBackupFile", BackupStoragePatchTest.DESC, null, null);
Label normal = new Label();
method.visitVarInsn(ALOAD, 0);
method.visitLdcInsn("fail");
method.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z", false);
method.visitJumpInsn(IFEQ, normal);
method.visitTypeInsn(NEW, "java/lang/IllegalStateException");
method.visitInsn(DUP);
method.visitLdcInsn("zip failed");
method.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalStateException", "<init>", "(Ljava/lang/String;)V", false);
method.visitInsn(ATHROW);
method.visitLabel(normal);
method.visitVarInsn(ALOAD, 0);
method.visitMethodInsn(INVOKESTATIC, BackupStoragePatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
method.visitInsn(RETURN);
method.visitMaxs(0, 0);
return node;
}
private static ClassNode emptyClass(String name)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
/** Patches {@code ZipBackup}, points the hook at {@link Calls}, and returns {@code makeBackupFile}. */
private static Method patched() throws ReflectiveOperationException
{
BackupStoragePatch patch = new BackupStoragePatch();
ClassNode zipBackup = BackupStoragePatchTest.zipBackup();
patch.apply(zipBackup);
CallRedirect.redirect(zipBackup, patch.hook().owner(), patch.hook().name(), BackupStoragePatchTest.CALLS);
ClassDefiner definer = new ClassDefiner();
Class<?> types = definer.define(BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.TYPES));
Class<?> loaded = definer.define(zipBackup);
Method method = loaded.getDeclaredMethod("makeBackupFile", String.class, types);
method.setAccessible(true);
BackupStoragePatchTest.Calls.LOG.clear();
return method;
}
@Test
void anchorMatchesTheTarget()
{
new BackupStoragePatch().anchor().verify(BackupStoragePatchTest.zipBackup());
}
@Test
void callsTheHookAroundTheBackup() throws ReflectiveOperationException
{
BackupStoragePatchTest.patched().invoke(null, "server", null);
assertEquals(List.of("backupRunning true", "server", "backupRunning false"), BackupStoragePatchTest.Calls.LOG);
}
@Test
void callsTheHookAfterAFailedBackupToo() throws ReflectiveOperationException
{
Method method = BackupStoragePatchTest.patched();
InvocationTargetException e = assertThrows(InvocationTargetException.class, () -> method.invoke(null, "fail", null));
assertInstanceOf(IllegalStateException.class, e.getCause());
assertEquals(List.of("backupRunning true", "backupRunning false"), BackupStoragePatchTest.Calls.LOG);
}
@Test
void failsWhenTheRenamedMethodExists()
{
ClassNode zipBackup = BackupStoragePatchTest.zipBackup();
zipBackup.visitMethod(ACC_PRIVATE | ACC_STATIC, "zomboidForge$makeBackupFile", "()V", null, null);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BackupStoragePatch().apply(zipBackup));
assertEquals("'zombie/core/backup/ZipBackup' already has a method 'zomboidForge$makeBackupFile'.", e.getMessage());
}
}
@@ -0,0 +1,105 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.Hook;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The patcher does not check that a hook exists; a missing one fails only when the patched
* game code runs, with a {@code NoSuchMethodError}. The hook classes are read as class files
* because their signatures may mention game classes, which are not on this class path.
*/
class HookExistenceTest
{
@Test
void everyHookOfThePatchSetExistsAsPublicStaticMethod() throws IOException
{
List<String> problems = new ArrayList<>();
for (ClassPatch patch : new B42PatchSet().patches())
{
Hook hook = patch.hook();
if (hook == null) continue;
String problem = HookExistenceTest.problemWith(hook);
if (problem != null) problems.add("'" + patch.getClass().getSimpleName() + "': " + problem);
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
@Test
void acceptsAnExistingPublicStaticMethod() throws IOException
{
assertNull(HookExistenceTest.problemWith(new Hook("java/lang/String", "valueOf", "(I)Ljava/lang/String;")));
}
@Test
void reportsMissingClass() throws IOException
{
assertEquals(
"Hook class 't/Missing' not found on the class path",
HookExistenceTest.problemWith(new Hook("t/Missing", "hook", "()V"))
);
}
@Test
void reportsMissingMethodOrDescriptor() throws IOException
{
assertEquals(
"Hook method 'java/lang/String.nope()V' not found",
HookExistenceTest.problemWith(new Hook("java/lang/String", "nope", "()V"))
);
assertEquals(
"Hook method 'java/lang/String.valueOf(Z)V' not found",
HookExistenceTest.problemWith(new Hook("java/lang/String", "valueOf", "(Z)V"))
);
}
@Test
void reportsMethodThatIsNotPublicStatic() throws IOException
{
assertEquals(
"Hook method 'java/lang/String.length()I' is not public static",
HookExistenceTest.problemWith(new Hook("java/lang/String", "length", "()I"))
);
}
/** @return a description of what is wrong with {@code hook}, or {@code null} if it is usable */
private static String problemWith(Hook hook) throws IOException
{
try (InputStream in = ClassLoader.getSystemResourceAsStream(hook.owner() + ".class"))
{
if (in == null) return "Hook class '" + hook.owner() + "' not found on the class path";
ClassNode node = new ClassNode();
new ClassReader(in).accept(node, ClassReader.SKIP_CODE);
String description = "Hook method '" + hook.owner() + "." + hook.name() + hook.desc() + "'";
for (MethodNode method : node.methods)
{
if (!method.name.equals(hook.name()) || !method.desc.equals(hook.desc())) continue;
boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0;
return publicStatic ? null : description + " is not public static";
}
return description + " not found";
}
}
}
@@ -0,0 +1,80 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Structure rules for Build 42 patches and hooks. Class names end in {@code Patch} and
* {@code Hooks}, so a class is recognizable as one or the other from its name alone.
*/
class NamingRulesTest
{
private static final List<String> PATCH_PACKAGES = List.of(
"dev/overlord/zomboidforge/compat/b42/patches",
"dev/overlord/zomboidforge/compat/b42/perf"
);
private static final String HOOKS_PACKAGE = "dev/overlord/zomboidforge/compat/b42/hooks";
@Test
void patchClassesEndInPatch() throws Exception
{
List<String> problems = new ArrayList<>();
for (String patchPackage : NamingRulesTest.PATCH_PACKAGES)
{
List<String> names = PackageScan.topLevelClassNames(patchPackage);
assertFalse(names.isEmpty(), "No classes found in '" + patchPackage + "'.");
for (String name : names)
{
if (!name.endsWith("Patch")) problems.add("'" + patchPackage + "/" + name + "' must end in 'Patch'.");
}
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
@Test
void hookClassesEndInHooksAndExposeOnlyPublicStaticMethods() throws Exception
{
List<String> problems = new ArrayList<>();
List<String> names = PackageScan.topLevelClassNames(NamingRulesTest.HOOKS_PACKAGE);
assertFalse(names.isEmpty(), "No classes found in '" + NamingRulesTest.HOOKS_PACKAGE + "'");
for (String name : names)
{
if (!name.endsWith("Hooks")) problems.add("'" + name + "' must end in 'Hooks'");
ClassNode node = PackageScan.read(NamingRulesTest.HOOKS_PACKAGE + "/" + name);
if ((node.access & Opcodes.ACC_FINAL) == 0) problems.add("'" + name + "' must be final");
for (MethodNode method : node.methods)
{
if ((method.access & Opcodes.ACC_SYNTHETIC) != 0 || method.name.equals("<clinit>")) continue;
if (method.name.equals("<init>"))
{
if ((method.access & Opcodes.ACC_PRIVATE) == 0) problems.add("'" + name + "' constructor must be private");
continue;
}
boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0;
if (!publicStatic) problems.add("'" + name + "." + method.name + method.desc + "' must be public static");
}
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
}
@@ -0,0 +1,54 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Opcodes;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A patch class that is not in {@link B42PatchSet} is never applied. Patches are switched off
* for debug builds with the {@code zf.disabledPatches} Gradle property, not by removing them
* from the patch set.
*/
class PatchSetRegistrationTest
{
private static final List<String> PATCH_PACKAGES = List.of(
"dev/overlord/zomboidforge/compat/b42/patches",
"dev/overlord/zomboidforge/compat/b42/perf"
);
@Test
void everyPatchClassIsRegisteredExactlyOnce() throws Exception
{
List<String> problems = new ArrayList<>();
Set<String> registered = new TreeSet<>();
for (ClassPatch patch : new B42PatchSet().patches())
{
String name = patch.getClass().getSimpleName();
if (!registered.add(name)) problems.add("'" + name + "' is registered more than once.");
}
for (String patchPackage : PatchSetRegistrationTest.PATCH_PACKAGES)
{
for (String name : PackageScan.topLevelClassNames(patchPackage))
{
boolean abstractClass = (PackageScan.read(patchPackage + "/" + name).access & Opcodes.ACC_ABSTRACT) != 0;
if (name.endsWith("Patch") && !abstractClass && !registered.contains(name)) {
problems.add("'" + name + "' is not registered in 'B42PatchSet'.");
}
}
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
}
@@ -0,0 +1,204 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ServerLoadPatchTest
{
private static final String GAME_SERVER = "zombie/network/GameServer";
private static final String SERVER_OPTIONS = "zombie/network/ServerOptions";
private static final String CALLS = Type.getInternalName(ServerLoadPatchTest.Calls.class);
/** Stands in for {@code ServerHooks.onLoad()} and {@code System.exit}, and records the calls. */
public static final class Calls
{
public static final List<String> LOG = new ArrayList<>();
public static boolean loaded;
private Calls() {}
public static void record(String call) { Calls.LOG.add(call); }
public static boolean onLoad()
{
Calls.LOG.add("onLoad");
return Calls.loaded;
}
public static void exit(int status) { Calls.LOG.add("exit " + status); }
}
private record Run(List<String> calls, Thread shutdownHook) {}
/**
* {@code GameServer} with the parts of {@code main} the patch depends on:
*
* <pre>{@code
* private static Thread shutdownHook = new Thread(); // only with withShutdownHook
*
* static { Runtime.getRuntime().addShutdownHook(shutdownHook); }
*
* public static void main(String[] args)
* {
* ServerOptions.instance.init();
* Calls.record("after");
* }
* }</pre>
*/
private static ClassNode gameServer(boolean withShutdownHook)
{
ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.GAME_SERVER);
if (withShutdownHook) {
node.visitField(ACC_PRIVATE | ACC_STATIC, "shutdownHook", "Ljava/lang/Thread;", null, null);
MethodVisitor init = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
init.visitTypeInsn(NEW, "java/lang/Thread");
init.visitInsn(DUP);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Thread", "<init>", "()V", false);
init.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;");
init.visitMethodInsn(INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false);
init.visitFieldInsn(GETSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;");
init.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Runtime", "addShutdownHook", "(Ljava/lang/Thread;)V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
}
MethodVisitor main = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
main.visitFieldInsn(GETSTATIC, ServerLoadPatchTest.SERVER_OPTIONS, "instance", "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";");
main.visitMethodInsn(INVOKEVIRTUAL, ServerLoadPatchTest.SERVER_OPTIONS, "init", "()V", false);
main.visitLdcInsn("after");
main.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
main.visitInsn(RETURN);
main.visitMaxs(0, 0);
return node;
}
/** {@code ServerOptions} with {@code public static ServerOptions instance} and {@code init()} recording {@code "init"}. */
private static ClassNode serverOptions()
{
ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.SERVER_OPTIONS);
String desc = "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";";
node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null);
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
clinit.visitTypeInsn(NEW, ServerLoadPatchTest.SERVER_OPTIONS);
clinit.visitInsn(DUP);
clinit.visitMethodInsn(INVOKESPECIAL, ServerLoadPatchTest.SERVER_OPTIONS, "<init>", "()V", false);
clinit.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.SERVER_OPTIONS, "instance", desc);
clinit.visitInsn(RETURN);
clinit.visitMaxs(0, 0);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "init", "()V", null, null);
init.visitLdcInsn("init");
init.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
/** Patches {@code GameServer}, points the hook and {@code System.exit} at {@link Calls}, and runs {@code main}. */
private static Run run(boolean loaded) throws ReflectiveOperationException
{
ServerLoadPatch patch = new ServerLoadPatch();
ClassNode gameServer = ServerLoadPatchTest.gameServer(true);
patch.apply(gameServer);
CallRedirect.redirect(gameServer, patch.hook().owner(), patch.hook().name(), ServerLoadPatchTest.CALLS);
CallRedirect.redirect(gameServer, "java/lang/System", "exit", ServerLoadPatchTest.CALLS);
ClassDefiner definer = new ClassDefiner();
definer.define(ServerLoadPatchTest.serverOptions());
Class<?> loadedClass = definer.define(gameServer);
ServerLoadPatchTest.Calls.LOG.clear();
ServerLoadPatchTest.Calls.loaded = loaded;
loadedClass.getMethod("main", String[].class).invoke(null, (Object) new String[0]);
Field shutdownHook = loadedClass.getDeclaredField("shutdownHook");
shutdownHook.setAccessible(true);
return new Run(List.copyOf(ServerLoadPatchTest.Calls.LOG), (Thread) shutdownHook.get(null));
}
@Test
void anchorMatchesTheTarget()
{
new ServerLoadPatch().anchor().verify(ServerLoadPatchTest.gameServer(true));
}
@Test
void continuesWhenTheHookReturnsTrue() throws ReflectiveOperationException
{
Run run = ServerLoadPatchTest.run(true);
assertEquals(List.of("init", "onLoad", "after"), run.calls());
assertTrue(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook is still registered.");
}
@Test
void removesTheShutdownHookAndExitsWhenTheHookReturnsFalse() throws ReflectiveOperationException
{
Run run = ServerLoadPatchTest.run(false);
// The test double for System.exit returns, so "after" still runs.
assertEquals(List.of("init", "onLoad", "exit 1", "after"), run.calls());
assertFalse(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook was not removed.");
}
@Test
void failsWithoutTheShutdownHookField()
{
ClassNode gameServer = ServerLoadPatchTest.gameServer(false);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerLoadPatch().apply(gameServer));
assertEquals("Expected the static field 'zombie/network/GameServer.shutdownHook Ljava/lang/Thread;'.", e.getMessage());
}
}
@@ -0,0 +1,173 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ServerStoppingPatchTest
{
private static final String GAME_SERVER = "zombie/network/GameServer";
private static final String SHUTDOWN_HOOK = "zombie/network/GameServer$1";
private static final String SERVER_MAP = "zombie/network/ServerMap";
private static final String CALLS = Type.getInternalName(ServerStoppingPatchTest.Calls.class);
/** Stands in for {@code ServerHooks.onStopping()} and records the calls. */
public static final class Calls
{
public static final List<String> LOG = new ArrayList<>();
/** {@code GameServer.done} of the class under test. */
public static Field done;
private Calls() {}
public static void record(String call) { Calls.LOG.add(call); }
public static void onStopping() throws IllegalAccessException { Calls.LOG.add("onStopping done=" + Calls.done.getBoolean(null)); }
}
/** {@code GameServer} with {@code public static boolean done} and {@code other}. */
private static ClassNode gameServer()
{
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.GAME_SERVER);
node.visitField(ACC_PUBLIC | ACC_STATIC, "done", "Z", null, null);
node.visitField(ACC_PUBLIC | ACC_STATIC, "other", "Z", null, null);
return node;
}
/** {@code ServerMap} with {@code public static ServerMap instance} and {@code QueuedQuit()} recording {@code "QueuedQuit"}. */
private static ClassNode serverMap()
{
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SERVER_MAP);
String desc = "L" + ServerStoppingPatchTest.SERVER_MAP + ";";
node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null);
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
clinit.visitTypeInsn(NEW, ServerStoppingPatchTest.SERVER_MAP);
clinit.visitInsn(DUP);
clinit.visitMethodInsn(INVOKESPECIAL, ServerStoppingPatchTest.SERVER_MAP, "<init>", "()V", false);
clinit.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", desc);
clinit.visitInsn(RETURN);
clinit.visitMaxs(0, 0);
MethodVisitor quit = node.visitMethod(ACC_PUBLIC, "QueuedQuit", "()V", null, null);
quit.visitLdcInsn("QueuedQuit");
quit.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
quit.visitInsn(RETURN);
quit.visitMaxs(0, 0);
return node;
}
/**
* {@code GameServer$1} with the part of {@code run()} the patch depends on:
*
* <pre>{@code
* public void run()
* {
* GameServer.<field> = true;
* ServerMap.instance.QueuedQuit();
* Calls.record("after");
* }
* }</pre>
*/
private static ClassNode shutdownHook(String field)
{
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SHUTDOWN_HOOK);
MethodVisitor run = node.visitMethod(ACC_PUBLIC, "run", "()V", null, null);
run.visitInsn(ICONST_1);
run.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.GAME_SERVER, field, "Z");
run.visitFieldInsn(GETSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", "L" + ServerStoppingPatchTest.SERVER_MAP + ";");
run.visitMethodInsn(INVOKEVIRTUAL, ServerStoppingPatchTest.SERVER_MAP, "QueuedQuit", "()V", false);
run.visitLdcInsn("after");
run.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
run.visitInsn(RETURN);
run.visitMaxs(0, 0);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
@Test
void anchorMatchesTheTarget()
{
new ServerStoppingPatch().anchor().verify(ServerStoppingPatchTest.shutdownHook("done"));
}
@Test
void callsTheHookAfterDoneIsSetAndBeforeTheSave() throws ReflectiveOperationException
{
ServerStoppingPatch patch = new ServerStoppingPatch();
ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("done");
patch.apply(shutdownHook);
CallRedirect.redirect(shutdownHook, patch.hook().owner(), patch.hook().name(), ServerStoppingPatchTest.CALLS);
ClassDefiner definer = new ClassDefiner();
definer.define(ServerStoppingPatchTest.serverMap());
Class<?> gameServer = definer.define(ServerStoppingPatchTest.gameServer());
Class<?> loaded = definer.define(shutdownHook);
ServerStoppingPatchTest.Calls.LOG.clear();
ServerStoppingPatchTest.Calls.done = gameServer.getField("done");
loaded.getMethod("run").invoke(loaded.getConstructor().newInstance());
assertEquals(List.of("onStopping done=true", "QueuedQuit", "after"), ServerStoppingPatchTest.Calls.LOG);
}
@Test
void failsWhenAnotherFieldIsSetBeforeTheSave()
{
ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("other");
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerStoppingPatch().apply(shutdownHook));
assertEquals(
"'zombie/network/GameServer$1.run()V' sets 'zombie/network/GameServer.other' before 'QueuedQuit()', expected 'zombie/network/GameServer.done'.",
e.getMessage()
);
}
}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Points calls in a patched test class at a test double, e.g. a hook or {@code System.exit}, so
* the patched code can run inside a test.
*/
public final class CallRedirect
{
private CallRedirect() {}
/**
* Changes the owner of every call to {@code owner.name} in {@code node} to {@code newOwner}.
* Fails when {@code node} contains no such call.
*/
public static void redirect(ClassNode node, String owner, String name, String newOwner)
{
int redirected = 0;
for (MethodNode method : node.methods) {
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call && call.owner.equals(owner) && call.name.equals(name)) {
call.owner = newOwner;
redirected++;
}
}
}
if (redirected == 0) throw new IllegalStateException("No call to '" + owner + "." + name + "' in '" + node.name + "'.");
}
}
@@ -0,0 +1,30 @@
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
/**
* Class loader that defines classes from {@link ClassNode}s, so patched test classes can be loaded
* and run. Lives in a subpackage so that the scanned packages do not contain it.
*/
public final class ClassDefiner extends ClassLoader
{
public ClassDefiner() { super(ClassDefiner.class.getClassLoader()); }
/**
* Writes {@code node} with computed frames and defines it. Classes that the frame computation
* needs (common superclasses) must be defined first.
*/
public Class<?> define(ClassNode node)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES)
{
@Override
protected ClassLoader getClassLoader() { return ClassDefiner.this; }
};
node.accept(writer);
byte[] bytes = writer.toByteArray();
return this.defineClass(node.name.replace('/', '.'), bytes, 0, bytes.length);
}
}
@@ -0,0 +1,68 @@
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
/**
* Lists and reads the classes of a package on the test class path, without loading them. Lives in
* a subpackage so that the scanned packages do not contain it.
*/
public final class PackageScan
{
private PackageScan() {}
/** Simple names of the top-level non-test classes in {@code packagePath}, from a directory or a jar on the class path. */
public static List<String> topLevelClassNames(String packagePath) throws IOException, URISyntaxException
{
List<String> names = new ArrayList<>();
for (URL url : Collections.list(ClassLoader.getSystemResources(packagePath)))
{
if (url.getProtocol().equals("file"))
{
try (Stream<Path> files = Files.list(Path.of(url.toURI()))) {
files.map(file -> file.getFileName().toString()).forEach(names::add);
}
}
else if (url.getProtocol().equals("jar"))
{
JarURLConnection connection = (JarURLConnection) url.openConnection();
connection.getJarFile().stream()
.map(entry -> entry.getName())
.filter(entry -> entry.startsWith(packagePath + "/") && entry.indexOf('/', packagePath.length() + 1) < 0)
.map(entry -> entry.substring(packagePath.length() + 1))
.forEach(names::add);
}
}
return names.stream()
.filter(file -> file.endsWith(".class") && !file.contains("$") && !file.equals("package-info.class"))
.filter(file -> !file.endsWith("Test.class"))
.map(file -> file.substring(0, file.length() - ".class".length()))
.sorted()
.toList();
}
public static ClassNode read(String internalName) throws IOException
{
try (InputStream in = ClassLoader.getSystemResourceAsStream(internalName + ".class"))
{
ClassNode node = new ClassNode();
new ClassReader(in).accept(node, ClassReader.SKIP_CODE);
return node;
}
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,252 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodNode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.IADD;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NOP;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoGameCharacterStateMachinePerformancePatchTest
{
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
private static final String ECS_ENTITY = "zombie/characters/ecs/ECSEntity";
private Class<?> characterClass = Object.class;
private Class<?> componentClass = Object.class;
/**
* {@code IsoGameCharacter} whose lookup counts its calls and returns the field {@code current}:
*
* <pre>{@code
* public static int lookups;
* public ECSComponent current;
*
* public ECSComponent getECSComponent(Class type) { lookups++; return this.current; }
*
* public final StateMachineComponent getStateMachineComponent() {
* return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);
* }
* }</pre>
*/
private static ClassNode character()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "java/lang/Object", IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY
);
String component = "L" + IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT + ";";
String ecsComponent = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT + ";";
node.visitField(ACC_PUBLIC | ACC_STATIC, "lookups", "I", null, null);
node.visitField(ACC_PUBLIC, "current", ecsComponent, null, null);
MethodVisitor lookup = node.visitMethod(ACC_PUBLIC, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, null, null);
lookup.visitFieldInsn(GETSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
lookup.visitInsn(ICONST_1);
lookup.visitInsn(IADD);
lookup.visitFieldInsn(PUTSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
lookup.visitVarInsn(ALOAD, 0);
lookup.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "current", ecsComponent);
lookup.visitInsn(ARETURN);
lookup.visitMaxs(0, 0);
MethodVisitor getter = node.visitMethod(ACC_PUBLIC | ACC_FINAL, "getStateMachineComponent", "()" + component, null, null);
getter.visitVarInsn(ALOAD, 0);
getter.visitLdcInsn(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT));
getter.visitMethodInsn(INVOKEVIRTUAL, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, false);
getter.visitTypeInsn(CHECKCAST, IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT);
getter.visitInsn(ARETURN);
getter.visitMaxs(0, 0);
return node;
}
/** {@code ECSComponent} with a public field {@code owner} that {@code getECSOwnerEntity()} returns. */
private static ClassNode ecsComponent()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "java/lang/Object", null);
String owner = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY + ";";
node.visitField(ACC_PUBLIC, "owner", owner, null, null);
MethodVisitor getter = node.visitMethod(ACC_PUBLIC, "getECSOwnerEntity", "()" + owner, null, null);
getter.visitVarInsn(ALOAD, 0);
getter.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "owner", owner);
getter.visitInsn(ARETURN);
getter.visitMaxs(0, 0);
return node;
}
private static ClassNode ecsEntity()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY, null, "java/lang/Object", null);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name, String superName, @Nullable String interfaceName)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, superName, interfaceName == null ? null : new String[] { interfaceName });
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, superName, "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
private static ClassNode patched()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
new IsoGameCharacterStateMachinePerformancePatch().apply(node);
return node;
}
@BeforeEach
void loadPatchedClasses()
{
ClassDefiner definer = new ClassDefiner();
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsEntity());
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsComponent());
this.componentClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, null
));
this.characterClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.patched());
}
private Object newCharacter() throws ReflectiveOperationException { return this.characterClass.getConstructor().newInstance(); }
/** A component owned by {@code owner} and registered as its {@code current} component. */
private Object addComponent(Object owner) throws ReflectiveOperationException
{
Object component = this.componentClass.getConstructor().newInstance();
this.componentClass.getField("owner").set(component, owner);
this.characterClass.getField("current").set(owner, component);
return component;
}
private Object stateMachineComponent(Object character) throws ReflectiveOperationException
{
return this.characterClass.getMethod("getStateMachineComponent").invoke(character);
}
private int lookups() throws ReflectiveOperationException { return this.characterClass.getField("lookups").getInt(null); }
@Test
void anchorMatchesTheTarget()
{
new IsoGameCharacterStateMachinePerformancePatch().anchor().verify(IsoGameCharacterStateMachinePerformancePatchTest.character());
}
@Test
void returnsTheStoredComponentWithoutALookup() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object component = this.addComponent(character);
assertSame(component, this.stateMachineComponent(character));
assertSame(component, this.stateMachineComponent(character));
assertEquals(1, this.lookups());
}
@Test
void looksUpAgainAfterTheComponentWasReplaced() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object first = this.addComponent(character);
assertSame(first, this.stateMachineComponent(character));
// ECSEntity.setECSComponent removes the old component, which sets its owner to null.
this.componentClass.getField("owner").set(first, null);
Object second = this.addComponent(character);
assertSame(second, this.stateMachineComponent(character));
assertSame(second, this.stateMachineComponent(character));
assertEquals(2, this.lookups());
}
@Test
void looksUpAgainAfterTheComponentMovedToAnotherCharacter() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object component = this.addComponent(character);
assertSame(component, this.stateMachineComponent(character));
this.componentClass.getField("owner").set(component, this.newCharacter());
this.characterClass.getField("current").set(character, null);
assertNull(this.stateMachineComponent(character));
assertEquals(2, this.lookups());
}
@Test
void failsWhenTheGetterDoesMoreThanTheLookup()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
MethodNode getter = node.methods.stream().filter(method -> method.name.equals("getStateMachineComponent")).findFirst().orElseThrow();
getter.instructions.insert(new InsnNode(NOP));
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
}
@Test
void failsWhenTheGameClassAlreadyHasTheField()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.patched();
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoGameCharacterStateMachinePerformancePatch patch = new IsoGameCharacterStateMachinePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -0,0 +1,209 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieNetworkComponentPerformancePatchTest
{
private static final String ZOMBIE = "zombie/characters/IsoZombie";
private static final String COMPONENT = "zombie/characters/component/NetworkZombieComponent";
private static final String OTHER = "zombie/characters/component/OtherComponent";
private static final String LOOKUP = "(Ljava/lang/Class;)Lzombie/characters/ecs/ECSComponent;";
/** {@code this.tryGetECSComponent(component.class)} cast to {@code component}, result dropped. */
private static void lookup(MethodVisitor method, String component)
{
method.visitVarInsn(ALOAD, 0);
method.visitLdcInsn(Type.getObjectType(component));
method.visitMethodInsn(INVOKEVIRTUAL, IsoZombieNetworkComponentPerformancePatchTest.ZOMBIE, "tryGetECSComponent", IsoZombieNetworkComponentPerformancePatchTest.LOOKUP, false);
method.visitTypeInsn(CHECKCAST, component);
method.visitInsn(POP);
}
/**
* {@code IsoZombie} with {@code getOwner()} and {@code setOwner()}, each looking up the
* network component, and {@code other()}, which looks up an unrelated component.
*/
private static ClassNode target()
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, IsoZombieNetworkComponentPerformancePatchTest.ZOMBIE, null, "java/lang/Object", null);
MethodVisitor getOwner = cw.visitMethod(ACC_PUBLIC, "getOwner", "()Lzombie/core/raknet/UdpConnection;", null, null);
IsoZombieNetworkComponentPerformancePatchTest.lookup(getOwner, IsoZombieNetworkComponentPerformancePatchTest.COMPONENT);
getOwner.visitInsn(ACONST_NULL);
getOwner.visitInsn(ARETURN);
getOwner.visitMaxs(0, 0);
MethodVisitor setOwner = cw.visitMethod(ACC_PUBLIC, "setOwner", "()V", null, null);
IsoZombieNetworkComponentPerformancePatchTest.lookup(setOwner, IsoZombieNetworkComponentPerformancePatchTest.COMPONENT);
setOwner.visitInsn(RETURN);
setOwner.visitMaxs(0, 0);
MethodVisitor other = cw.visitMethod(ACC_PUBLIC, "other", "()V", null, null);
IsoZombieNetworkComponentPerformancePatchTest.lookup(other, IsoZombieNetworkComponentPerformancePatchTest.OTHER);
other.visitInsn(RETURN);
other.visitMaxs(0, 0);
cw.visitEnd();
ClassNode node = new ClassNode();
new ClassReader(cw.toByteArray()).accept(node, 0);
return node;
}
private static MethodNode method(ClassNode node, String name)
{
return node.methods.stream().filter(method -> method.name.equals(name)).findFirst().orElseThrow();
}
private static List<MethodInsnNode> calls(MethodNode method, String name)
{
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call && call.name.equals(name)) calls.add(call);
}
return calls;
}
private static ClassNode patched()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.target();
new IsoZombieNetworkComponentPerformancePatch().apply(node);
return node;
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieNetworkComponentPerformancePatch().anchor().verify(IsoZombieNetworkComponentPerformancePatchTest.target());
}
@Test
void addsAPrivateFieldAndAnAccessor()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
assertEquals(1, node.fields.size());
assertEquals("zomboidForge$networkComponent", node.fields.getFirst().name);
assertEquals("L" + IsoZombieNetworkComponentPerformancePatchTest.COMPONENT + ";", node.fields.getFirst().desc);
assertTrue((node.fields.getFirst().access & ACC_PRIVATE) != 0);
MethodNode accessor = IsoZombieNetworkComponentPerformancePatchTest.method(node, "zomboidForge$networkComponent");
assertTrue((accessor.access & ACC_PRIVATE) != 0);
assertEquals("()L" + IsoZombieNetworkComponentPerformancePatchTest.COMPONENT + ";", accessor.desc);
}
@Test
void accessorFillsTheFieldOnceFromTheLookup()
{
MethodNode accessor = IsoZombieNetworkComponentPerformancePatchTest.method(IsoZombieNetworkComponentPerformancePatchTest.patched(), "zomboidForge$networkComponent");
assertEquals(1, IsoZombieNetworkComponentPerformancePatchTest.calls(accessor, "tryGetECSComponent").size());
int reads = 0;
int writes = 0;
for (AbstractInsnNode instruction : accessor.instructions)
{
if (instruction instanceof FieldInsnNode field && field.getOpcode() == GETFIELD) reads++;
if (instruction instanceof FieldInsnNode field && field.getOpcode() == PUTFIELD) writes++;
}
assertEquals(1, reads);
assertEquals(1, writes);
}
@Test
void replacesEveryLookupOfTheNetworkComponentWithTheAccessor()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
for (String name : List.of("getOwner", "setOwner"))
{
MethodNode method = IsoZombieNetworkComponentPerformancePatchTest.method(node, name);
assertTrue(IsoZombieNetworkComponentPerformancePatchTest.calls(method, "tryGetECSComponent").isEmpty(), name);
List<MethodInsnNode> accessors = IsoZombieNetworkComponentPerformancePatchTest.calls(method, "zomboidForge$networkComponent");
assertEquals(1, accessors.size(), name);
assertEquals(INVOKESPECIAL, accessors.getFirst().getOpcode(), name);
// No class literal and no cast remain: the accessor returns the component itself.
for (AbstractInsnNode instruction : method.instructions)
{
assertFalse(instruction instanceof LdcInsnNode, name);
assertFalse(instruction.getOpcode() == CHECKCAST, name);
}
}
}
@Test
void leavesLookupsOfOtherComponentsAlone()
{
MethodNode other = IsoZombieNetworkComponentPerformancePatchTest.method(IsoZombieNetworkComponentPerformancePatchTest.patched(), "other");
assertEquals(1, IsoZombieNetworkComponentPerformancePatchTest.calls(other, "tryGetECSComponent").size());
assertTrue(IsoZombieNetworkComponentPerformancePatchTest.calls(other, "zomboidForge$networkComponent").isEmpty());
}
@Test
void patchedClassIsWrittenWithComputedFrames()
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
IsoZombieNetworkComponentPerformancePatchTest.patched().accept(writer);
assertTrue(writer.toByteArray().length > 0);
}
@Test
void failsWhenTheGameClassAlreadyHasTheMember()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
assertThrows(IllegalStateException.class, () -> new IsoZombieNetworkComponentPerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieNetworkComponentPerformancePatch patch = new IsoZombieNetworkComponentPerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -0,0 +1,191 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.F2I;
import static org.objectweb.asm.Opcodes.FLOAD;
import static org.objectweb.asm.Opcodes.FMUL;
import static org.objectweb.asm.Opcodes.FSTORE;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.I2F;
import static org.objectweb.asm.Opcodes.IADD;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieSpotChancePerformancePatchTest
{
private static final String ZOMBIE = "zombie/characters/IsoZombie";
private static final String MOVING = "zombie/iso/IsoMovingObject";
private static final String MATH = "zombie/core/math/PZMath";
private static final int CHANCE = 5;
private record Result(int modifierRuns, float rounded) {}
/**
* {@code IsoZombie} with the shape of {@code spottedNew} around the patched range:
*
* <pre>{@code
* public static float input;
* public static int modifierRuns;
* public static float rounded;
*
* public void spottedNew(IsoMovingObject other, boolean bForced)
* {
* float chance = input; // local 5
* if (bForced) chance = 1000000F;
* modifierRuns++; // stands for the modifiers
* chance *= 2F;
* chance = (float) PZMath.fastfloor(chance); // local roundingLocal
* rounded = chance;
* }
* }</pre>
*/
private static ClassNode zombie(int roundingLocal)
{
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.ZOMBIE);
node.visitField(ACC_PUBLIC | ACC_STATIC, "input", "F", null, null);
node.visitField(ACC_PUBLIC | ACC_STATIC, "modifierRuns", "I", null, null);
node.visitField(ACC_PUBLIC | ACC_STATIC, "rounded", "F", null, null);
MethodVisitor method = node.visitMethod(ACC_PUBLIC, "spottedNew", "(L" + IsoZombieSpotChancePerformancePatchTest.MOVING + ";Z)V", null, null);
Label notForced = new Label();
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "input", "F");
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitVarInsn(ILOAD, 2);
method.visitJumpInsn(IFEQ, notForced);
method.visitLdcInsn(1000000.0F);
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitLabel(notForced);
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
method.visitInsn(ICONST_1);
method.visitInsn(IADD);
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitLdcInsn(2.0F);
method.visitInsn(FMUL);
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitVarInsn(FLOAD, roundingLocal);
method.visitMethodInsn(INVOKESTATIC, IsoZombieSpotChancePerformancePatchTest.MATH, "fastfloor", "(F)I", false);
method.visitInsn(I2F);
method.visitVarInsn(FSTORE, roundingLocal);
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "rounded", "F");
method.visitInsn(RETURN);
method.visitMaxs(0, 0);
return node;
}
/** {@code PZMath} with {@code fastfloor} as {@code (int) value}, which equals it for the values used here. */
private static ClassNode math()
{
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MATH);
MethodVisitor fastfloor = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "fastfloor", "(F)I", null, null);
fastfloor.visitVarInsn(FLOAD, 0);
fastfloor.visitInsn(F2I);
fastfloor.visitInsn(IRETURN);
fastfloor.visitMaxs(0, 0);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
/** Loads the patched {@code IsoZombie} and runs {@code spottedNew(null, forced)} with {@code input} as the chance. */
private static Result run(float input, boolean forced) throws ReflectiveOperationException
{
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE);
new IsoZombieSpotChancePerformancePatch().apply(zombie);
ClassDefiner definer = new ClassDefiner();
definer.define(IsoZombieSpotChancePerformancePatchTest.math());
Class<?> moving = definer.define(IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MOVING));
Class<?> loaded = definer.define(zombie);
loaded.getField("input").setFloat(null, input);
loaded.getMethod("spottedNew", moving, boolean.class).invoke(loaded.getConstructor().newInstance(), null, forced);
return new Result(loaded.getField("modifierRuns").getInt(null), loaded.getField("rounded").getFloat(null));
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieSpotChancePerformancePatch().anchor().verify(IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE));
}
@Test
void zeroChanceSkipsTheModifiersAndStillRounds() throws ReflectiveOperationException
{
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, false));
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(-0.0F, false));
}
@Test
void otherChancesRunTheModifiers() throws ReflectiveOperationException
{
assertEquals(new Result(1, 6.0F), IsoZombieSpotChancePerformancePatchTest.run(3.0F, false));
assertEquals(new Result(1, 2000000.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, true));
assertEquals(1, IsoZombieSpotChancePerformancePatchTest.run(Float.NaN, false).modifierRuns());
}
@Test
void failsWhenTheRoundingUsesAnotherLocal()
{
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(6);
assertThrows(IllegalStateException.class, () -> new IsoZombieSpotChancePerformancePatch().apply(zombie));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieSpotChancePerformancePatch patch = new IsoZombieSpotChancePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -0,0 +1,162 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.ISTORE;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieVehiclePerformancePatchTest
{
private static final String VECTOR = "org/joml/Vector3f";
private static final String CALL = "(L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";";
/**
* {@code IsoZombie} with a reduced {@code isVehicleBetween}: one call to
* {@code BaseVehicle.getIntersectPoint}, result ignored, then {@code return intersect}.
*/
private static ClassNode target()
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, "zombie/characters/IsoZombie", null, "java/lang/Object", null);
MethodVisitor m = cw.visitMethod(ACC_PRIVATE, "isVehicleBetween", "(FFF)Z", null, null);
m.visitInsn(ICONST_0);
m.visitVarInsn(ISTORE, 4);
m.visitInsn(ACONST_NULL);
m.visitTypeInsn(CHECKCAST, "zombie/vehicles/BaseVehicle");
m.visitInsn(ACONST_NULL);
m.visitInsn(ACONST_NULL);
m.visitInsn(ACONST_NULL);
m.visitMethodInsn(INVOKEVIRTUAL, "zombie/vehicles/BaseVehicle", "getIntersectPoint", IsoZombieVehiclePerformancePatchTest.CALL, false);
m.visitInsn(POP);
m.visitVarInsn(ILOAD, 4);
m.visitInsn(IRETURN);
m.visitMaxs(0, 0);
cw.visitEnd();
ClassNode node = new ClassNode();
new ClassReader(cw.toByteArray()).accept(node, 0);
return node;
}
private static MethodNode isVehicleBetween(ClassNode node)
{
return node.methods.stream().filter(method -> method.name.equals("isVehicleBetween")).findFirst().orElseThrow();
}
/** Opcodes of the real instructions: no labels, line numbers, or frames. */
private static List<Integer> opcodes(MethodNode method)
{
List<Integer> opcodes = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) opcodes.add(instruction.getOpcode());
}
return opcodes;
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieVehiclePerformancePatch().anchor().verify(IsoZombieVehiclePerformancePatchTest.target());
}
@Test
void returnsFalseFirstWhenTheCellHasNoVehicles()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
List<Integer> opcodes = IsoZombieVehiclePerformancePatchTest.opcodes(IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node));
assertEquals(
List.of(GETSTATIC, GETFIELD, INVOKEVIRTUAL, INVOKEINTERFACE, IFEQ, ICONST_0, IRETURN),
opcodes.subList(0, 7)
);
}
@Test
void jumpsOverTheEarlyReturnToTheOriginalCode()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
MethodNode method = IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node);
JumpInsnNode jump = Arrays.stream(method.instructions.toArray())
.filter(JumpInsnNode.class::isInstance)
.map(JumpInsnNode.class::cast)
.findFirst()
.orElseThrow();
// The label sits directly before the original first instruction, iconst_0 of "intersectVision = false".
AbstractInsnNode firstOriginal = jump.label.getNext();
while (firstOriginal.getOpcode() == -1) firstOriginal = firstOriginal.getNext();
assertEquals(ICONST_0, firstOriginal.getOpcode());
assertEquals(ISTORE, firstOriginal.getNext().getOpcode());
}
@Test
void replacesTheVirtualCallWithTheHook()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node).instructions) {
if (instruction instanceof MethodInsnNode call && call.name.equals("getIntersectPoint")) calls.add(call);
}
assertEquals(1, calls.size());
MethodInsnNode call = calls.getFirst();
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", call.owner);
assertEquals("(Lzombie/vehicles/BaseVehicle;L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";", call.desc);
assertFalse(call.itf);
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieVehiclePerformancePatch patch = new IsoZombieVehiclePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
+4
View File
@@ -9,4 +9,8 @@ dependencies {
implementation(project(":core")) implementation(project(":core"))
implementation(project(":api")) implementation(project(":api"))
compileOnly(files(projectZomboid.serverJar)) compileOnly(files(projectZomboid.serverJar))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
} }
@@ -0,0 +1,11 @@
package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.core.Forge;
/** The one {@link Forge} of the server, shared by the hook classes. */
public final class ForgeInstance
{
public static final Forge FORGE = Forge.fromSystemProperties();
private ForgeInstance() {}
}
@@ -0,0 +1,110 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.ZomboidForge;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.core.storage.StorageDatabase;
import dev.overlord.zomboidforge.core.mods.ModLoadException;
import zombie.ZomboidFileSystem;
import zombie.core.Core;
import zombie.network.GameServer;
import java.nio.file.Path;
/**
* Hooks called by patched {@code zombie.network.GameServer} code and its shutdown hook
* {@code GameServer$1}. Exceptions are caught here: the main loop logs repeated exceptions only
* a limited number of times, and an exception in the shutdown hook would skip the world save.
*/
@SuppressWarnings("CallToPrintStackTrace")
public final class ServerHooks
{
private ServerHooks() {}
/**
* Called once on the main thread in {@code GameServer.main}, directly after
* {@code ServerOptions.instance.init()}: logging is set up, and the server name and cache
* directory are known. The Workshop download, the server database, Lua, and the world come
* later. Loads the mods.
*
* @return {@code false} to stop the server; the patched code then removes the vanilla
* shutdown hook and exits with code 1
*/
public static boolean onLoad()
{
try
{
System.out.println("[ZomboidForge] " + ZomboidForge.VERSION + " loading mods.");
GameVersion game = GameVersion.parse(Core.getInstance().getGameAndBuildVersion());
Path gameJar = Path.of(Core.class.getProtectionDomain().getCodeSource().getLocation().toURI());
// The save folder ZipBackup zips. getCurrentSaveDir() depends on Core.gameMode, which GameServer.main sets to "Multiplayer" only later.
Path storage = Path.of(ZomboidFileSystem.instance.getCacheDir(), "Saves", "Multiplayer", GameServer.serverName, StorageDatabase.FILE);
ForgeInstance.FORGE.load(game, gameJar, ServerHooks.class.getClassLoader(), storage);
return true;
}
catch (ModLoadException e)
{
System.out.println("[ZomboidForge] Cannot load the mods, stopping the server:");
e.problems().forEach(problem -> System.out.println("[ZomboidForge] " + problem));
if (e.getCause() != null) e.getCause().printStackTrace();
return false;
}
catch (Throwable t)
{
System.out.println("[ZomboidForge] Startup failed, stopping the server.");
t.printStackTrace();
return false;
}
}
/**
* Called once on the main thread, after the world is loaded, the network port is open, and
* RCON is initialized; directly before the main loop starts.
*/
public static void onServerStarted()
{
try
{
ForgeInstance.FORGE.started();
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
}
catch (Throwable t) { t.printStackTrace(); }
}
/**
* Called on the main thread for every frame of the main loop, directly after
* {@code ServerMap.instance.preupdate()}, inside the {@code frameStep} profiling probe. Not
* called while the update limiter skips a frame. Posts the tick event and runs the mods'
* queued main-thread tasks.
*/
public static void onTick()
{
try { ForgeInstance.FORGE.tick(); }
catch (Throwable t) { t.printStackTrace(); }
}
/**
* Called once on the shutdown hook thread ({@code GameServer$1}), after
* {@code GameServer.done = true} and before {@code ServerMap.instance.QueuedQuit()} saves the
* world. Both ways the server stops lead here: the {@code quit} command makes
* {@code ServerMap.preupdate()} call {@code System.exit(0)}, and SIGTERM or SIGINT start the
* JVM shutdown directly. In the second case the main thread may still be inside a frame. Not
* called in soft-reset mode.
*/
public static void onStopping()
{
try
{
System.out.println("[ZomboidForge] Server stopping.");
ForgeInstance.FORGE.stopping();
}
catch (Throwable t) { t.printStackTrace(); }
}
}
@@ -0,0 +1,25 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
@SuppressWarnings("CallToPrintStackTrace")
public final class StorageHooks
{
private StorageHooks() {}
/**
* Called by the patched {@code ZipBackup.makeBackupFile} on the thread that makes the backup:
* with {@code true} before the vanilla method, with {@code false} after it, also when it threw.
* Storage writes wait in between, so the zipped {@code zomboidforge.db} is complete.
*/
public static void backupRunning(boolean running)
{
try
{
if (running) ForgeInstance.FORGE.backupStarted();
else ForgeInstance.FORGE.backupFinished();
}
catch (Throwable t) { t.printStackTrace(); }
}
}
@@ -0,0 +1,57 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.SegmentReach;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
import zombie.core.physics.WorldSimulation;
import zombie.scripting.objects.VehicleScript;
import zombie.vehicles.BaseVehicle;
/** Hooks called by patched {@code zombie.characters.IsoZombie} code. */
public final class ZombieVehicleHooks
{
/**
* World units added to the bounding radius. Float resolution near the world coordinates
* (about 10000) is 0.001, so this covers rounding differences to the vanilla test.
*/
private static final float MARGIN = 0.1F;
private ZombieVehicleHooks() {}
/**
* Replaces the call {@code vehicle.getIntersectPoint(start, end, result)} in
* {@code IsoZombie.isVehicleBetween}. Returns what that call returns.
*
* <p>The vanilla test is 2-dimensional: {@code getLocalPos} drops the height of both
* points, and the vehicle's box is centered on its physics origin with the half extents
* {@code extents * 0.5 + centerOfMassOffset}. Whatever its rotation, the box lies inside
* the circle around that origin with the radius of its half diagonal. A segment that stays
* outside the circle cannot hit the box, so the vanilla call returns {@code null} for it
* and is skipped here.
*/
public static @Nullable Vector3f getIntersectPoint(
@NotNull BaseVehicle vehicle,
@NotNull Vector3f start,
@NotNull Vector3f end,
@Nullable Vector3f result
) {
VehicleScript script = vehicle.getScript();
Vector3f extents = script.getExtents();
Vector3f centerOfMass = script.getCenterOfMassOffset();
float halfX = extents.x * 0.5F + centerOfMass.x;
float halfZ = extents.z * 0.5F + centerOfMass.z;
float radius = (float) Math.sqrt(halfX * halfX + halfZ * halfZ) + ZombieVehicleHooks.MARGIN;
// Same position that BaseVehicle.getWorldPos and getLocalPos use for the physics origin.
float centerX = vehicle.jniTransform.origin.x + WorldSimulation.instance.offsetX;
float centerY = vehicle.jniTransform.origin.z + WorldSimulation.instance.offsetY;
if (SegmentReach.missesCircle(start.x, start.y, end.x, end.y, centerX, centerY, radius)) return null;
return vehicle.getIntersectPoint(start, end, result);
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1,5 +1,10 @@
/** /**
* Build 42 runtime code: hooks that patched game classes call, and adapters between * Build 42 runtime code: hooks that patched game classes call, and adapters between
* game classes and the version-independent {@code core} and {@code api}. * game classes and the version-independent {@code core} and {@code api}.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/ */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42; package dev.overlord.zomboidforge.compat.b42;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,38 @@
package dev.overlord.zomboidforge.compat.b42.util;
/** Distance checks in the XY plane. Uses no game classes, so it can be tested on its own. */
public final class SegmentReach
{
private SegmentReach() {}
/**
* Whether every point of the segment from ({@code startX}, {@code startY}) to
* ({@code endX}, {@code endY}) is farther than {@code radius} from
* ({@code centerX}, {@code centerY}).
*
* <p>False when any input is NaN. A caller that skips work only on {@code true} therefore
* still runs the full computation for such input.
*/
public static boolean missesCircle(
float startX, float startY, float endX, float endY,
float centerX, float centerY, float radius
) {
float directionX = endX - startX;
float directionY = endY - startY;
float lengthSquared = directionX * directionX + directionY * directionY;
// Position of the point on the segment closest to the center, from 0 (start) to 1 (end).
// A segment of length 0 is its start. NaN passes through every comparison unchanged.
float along = lengthSquared == 0.0F
? 0.0F
: ((centerX - startX) * directionX + (centerY - startY) * directionY) / lengthSquared;
if (along < 0.0F) along = 0.0F;
else if (along > 1.0F) along = 1.0F;
float offsetX = startX + along * directionX - centerX;
float offsetY = startY + along * directionY - centerY;
return offsetX * offsetX + offsetY * offsetY > radius * radius;
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.util;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,88 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SegmentReachTest
{
@Test
void segmentFarFromTheCircleMisses()
{
assertTrue(SegmentReach.missesCircle(0, 10, 20, 10, 10, 0, 5));
}
@Test
void segmentThroughTheCenterDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 0, 1));
}
@Test
void segmentThatEndsBeforeTheCircleMissesEvenWhenItsLineWouldHit()
{
// The line y = 0 passes through the circle at (10, 0); the segment stops at x = 5.
assertTrue(SegmentReach.missesCircle(0, 0, 5, 0, 10, 0, 2));
}
@Test
void segmentThatStartsAfterTheCircleMissesEvenWhenItsLineWouldHit()
{
assertTrue(SegmentReach.missesCircle(15, 0, 30, 0, 10, 0, 2));
}
@Test
void segmentThatTouchesTheCircleEdgeDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(0, 5, 20, 5, 10, 0, 5));
}
@Test
void segmentJustOutsideTheCircleMisses()
{
assertTrue(SegmentReach.missesCircle(0, 5.001F, 20, 5.001F, 10, 0, 5));
}
@Test
void segmentStartingInsideTheCircleDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(10, 1, 100, 100, 10, 0, 2));
}
@Test
void segmentOfLengthZeroIsItsStart()
{
assertFalse(SegmentReach.missesCircle(10, 1, 10, 1, 10, 0, 2));
assertTrue(SegmentReach.missesCircle(50, 50, 50, 50, 10, 0, 2));
}
@Test
void diagonalSegmentIsMeasuredToItsClosestPoint()
{
// Closest point of (0,0)-(10,10) to (10,0) is (5,5), distance sqrt(50) = 7.07.
assertTrue(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.0F));
assertFalse(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.2F));
}
@Test
void worksAtWorldCoordinates()
{
assertFalse(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10196, 2));
assertTrue(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10210, 2));
}
@Test
void neverMissesOnNaN()
{
float nan = Float.NaN;
assertFalse(SegmentReach.missesCircle(nan, 0, 20, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, nan, 20, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, nan, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, nan, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, nan, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, nan, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 100, nan));
}
}
+14
View File
@@ -6,4 +6,18 @@ plugins {
dependencies { dependencies {
implementation(project(":api")) implementation(project(":api"))
implementation(libs.night.config.toml)
implementation(libs.asm)
testImplementation(libs.bundles.asm)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
// At runtime the game jar provides the driver.
testRuntimeOnly(libs.sqlite.jdbc)
}
tasks.test {
// The SQLite JDBC driver loads a native library; the server runs with the same flag.
jvmArgs("--enable-native-access=ALL-UNNAMED")
} }
@@ -0,0 +1,50 @@
package dev.overlord.zomboidforge.core;
import org.jetbrains.annotations.Nullable;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* {@link System.Logger} that prints {@code [<name>] message} to standard output, which the
* Project Zomboid log captures. Levels below {@code INFO} are dropped; other levels than
* {@code INFO} are written before the message.
*/
@SuppressWarnings("CallToPrintStackTrace")
public final class ConsoleLogger implements System.Logger
{
private final String name;
public ConsoleLogger(String name) { this.name = name; }
@Override
public String getName() { return this.name; }
@Override
public boolean isLoggable(Level level) { return level != Level.OFF && level.getSeverity() >= Level.INFO.getSeverity(); }
@Override
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String message, @Nullable Throwable thrown)
{
if (!this.isLoggable(level)) return;
String prefix = level == Level.INFO ? "" : level.getName() + ": ";
System.out.println("[" + this.name + "] " + prefix + message);
if (thrown != null) thrown.printStackTrace();
}
@Override
public void log(
Level level,
@Nullable ResourceBundle bundle,
@Nullable String format,
@Nullable Object @Nullable ... parameters
) {
String message = format == null || parameters == null || parameters.length == 0
? format
: MessageFormat.format(format, parameters);
this.log(level, bundle, message, (Throwable) null);
}
}
@@ -0,0 +1,266 @@
package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.ZomboidForge;
import dev.overlord.zomboidforge.api.storage.StorageException;
import dev.overlord.zomboidforge.core.config.ForgeSettings;
import dev.overlord.zomboidforge.core.mods.GameClasses;
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
import dev.overlord.zomboidforge.core.mods.ModLoadException;
import dev.overlord.zomboidforge.core.mods.ModLoader;
import dev.overlord.zomboidforge.core.mods.ModResolver;
import dev.overlord.zomboidforge.core.mods.ModServices;
import dev.overlord.zomboidforge.core.mods.ModVerifier;
import dev.overlord.zomboidforge.core.mods.ModVersion;
import dev.overlord.zomboidforge.core.runtime.EventBus;
import dev.overlord.zomboidforge.core.runtime.MainThreadQueue;
import dev.overlord.zomboidforge.core.runtime.ModThreads;
import dev.overlord.zomboidforge.core.storage.ModTables;
import dev.overlord.zomboidforge.core.storage.StorageDatabase;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* ZomboidForge inside a running server: the lifecycle phase, the loaded mods, and their threads
* and events. The compat hooks call {@link #load}, {@link #started()}, {@link #tick()}, and
* {@link #stopping()}.
*/
public final class Forge
{
/** System property with the ZomboidForge directory, which contains {@code mods/}. */
public static final String DIRECTORY_PROPERTY = "zomboidforge.dir";
public static final String DEFAULT_DIRECTORY = "/forge";
private static final String MODS = "mods";
private final Lifecycle lifecycle = new Lifecycle();
private final System.Logger logger = new ConsoleLogger("ZomboidForge");
private final MainThreadQueue queue = new MainThreadQueue(ForgeSettings.DEFAULTS.mainThreadBudget());
private final EventBus events = new EventBus();
private final ModThreads threads = new ModThreads();
private final Path directory;
private final @Nullable ModVersion api;
private volatile List<ModLoader.LoadedMod> mods = List.of();
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
private volatile @Nullable StorageDatabase storage;
/**
* @param directory the ZomboidForge directory
* @param api the API version mods are checked against, or {@code null} to skip the
* check
*/
public Forge(Path directory, @Nullable ModVersion api)
{
this.directory = directory;
this.api = api;
}
/**
* Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API
* version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev},
* {@code 0.0.0-...}) skip the API check.
*/
public static Forge fromSystemProperties()
{
Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY));
ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION)
.filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0)
.orElse(null);
return new Forge(directory, api);
}
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
public List<ModLoader.LoadedMod> mods() { return this.mods; }
/**
* Reads {@code forge.toml}, then discovers, checks, and loads every mod in
* {@code <directory>/mods}. Called once on the main thread, which becomes the thread of
* {@code main()}. When a mod fails, the threads of the mods created so far are stopped.
*
* @param gameJar the Project Zomboid jar the server runs
* @param parent parent of the mods' class loaders; loads the game, the API, and ZomboidForge
* @param storageFile the world's {@code zomboidforge.db}; created when a mod first uses storage
* @throws ModLoadException listing every problem found
*/
public void load(GameVersion game, Path gameJar, ClassLoader parent, Path storageFile) throws ModLoadException
{
Path modsDirectory = this.directory.resolve(Forge.MODS);
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)); }
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "': " + e.getMessage(), e); }
this.queue.budget(this.settings.mainThreadBudget());
this.queue.bindToCurrentThread();
if (this.api == null) this.logger.log(System.Logger.Level.WARNING, "ZomboidForge " + ZomboidForge.VERSION + " is not a release; the API versions of mods are not checked.");
List<ModDiscovery.Candidate> candidates = Files.isDirectory(modsDirectory)
? ModDiscovery.discover(modsDirectory, this.logger)
: List.of();
List<String> disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).toList();
if (!disabled.isEmpty()) this.logger.log(System.Logger.Level.INFO, "Disabled in config.toml: " + String.join(", ", disabled) + ".");
List<ModDiscovery.Candidate> ordered = ModResolver.resolve(candidates, game, this.api);
List<String> installed = candidates.stream().map(ModDiscovery.Candidate::id).toList();
StorageDatabase storage = new StorageDatabase(storageFile, this::storageForbidden);
this.storage = storage;
try (GameClasses gameClasses = GameClasses.open(gameJar))
{
ModVerifier.verify(ordered, gameClasses, game);
for (ModDiscovery.Candidate candidate : ordered) ModTables.adoptPreviousIds(storage, candidate.id(), candidate.descriptor().previousIds(), installed);
this.mods = ModLoader.load(ordered, game, parent, gameClasses, this::services);
}
catch (IOException e)
{
this.stopMods(Duration.ZERO);
throw new ModLoadException("Cannot read the Project Zomboid jar '" + gameJar + "': " + e.getMessage(), e);
}
catch (StorageException e)
{
this.stopMods(Duration.ZERO);
throw new ModLoadException(e.getMessage() == null ? e.toString() : e.getMessage(), e);
}
catch (ModLoadException | RuntimeException e)
{
this.stopMods(Duration.ZERO);
throw e;
}
this.lifecycle.loaded();
this.logger.log(System.Logger.Level.INFO, this.mods.isEmpty()
? "No mods in '" + modsDirectory + "'."
: "Loaded " + this.mods.size() + " mod(s): " + this.mods.stream().map(mod -> mod.descriptor().id() + " " + mod.descriptor().version()).collect(Collectors.joining(", ")) + "."
);
}
/**
* Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. Anything a
* mod throws is logged, and the next mod is called.
*/
public void started()
{
this.lifecycle.started();
for (ModLoader.LoadedMod mod : this.mods) {
try { mod.mod().onServerStarted(); }
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); }
}
}
/**
* Posts {@link TickEvent} (only when a listener exists), then runs queued main-thread tasks
* within the budget. Main thread, once per frame of the main loop.
*/
public void tick()
{
if (this.events.hasListeners(TickEvent.class)) this.events.post(new TickEvent(this.queue.tick() + 1));
this.queue.drain();
}
/**
* Delivers {@code event} to the mods' listeners: main listeners run now on the calling
* thread, which must be the main thread; mod-thread listeners get a task on their mod's
* thread.
*/
public void post(Event event) { this.events.post(event); }
/**
* Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}).
* Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup.
*/
public void backupStarted()
{
StorageDatabase storage = this.storage;
if (storage == null) return;
String problem = storage.backupStarted();
if (problem != null) this.logger.log(System.Logger.Level.WARNING, problem);
}
/** Resumes storage after {@link #backupStarted()}; same thread. */
public void backupFinished()
{
StorageDatabase storage = this.storage;
if (storage != null) storage.backupFinished();
}
/**
* Once: calls {@link Mod#onStopping()} of every mod in reverse load order, then stops the
* mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread,
* before the world is saved, so nothing a mod throws leaves this method.
*/
public void stopping()
{
if (!this.lifecycle.stopping()) return;
try
{
for (ModLoader.LoadedMod mod : this.mods.reversed()) {
try { mod.mod().onStopping(); }
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", t); }
}
}
finally
{
this.stopMods(this.settings.shutdownTimeout());
}
}
/**
* Rejects further main-thread tasks and cancels the queued ones, stops event delivery, gives
* the mods' threads {@code timeout} to finish before they are interrupted, and closes the
* storage.
*/
private void stopMods(Duration timeout)
{
this.queue.close();
this.events.close();
this.threads.shutdown(timeout, this.logger);
StorageDatabase storage = this.storage;
if (storage == null) return;
try { storage.close(); }
catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); }
}
/** The main thread may use storage only before the main loop runs. */
private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; }
private ModServices services(String id, System.Logger logger)
{
ModThreads.ModExecutors executors = this.threads.create(id, logger);
StorageDatabase storage = Objects.requireNonNull(this.storage, "storage");
return new ModServices(
this.events.forMod(id, executors.modThread(), logger),
this.queue.forMod(id, logger),
executors.modThread(),
executors.async(),
new ModTables(id, storage, logger)
);
}
}
@@ -0,0 +1,47 @@
package dev.overlord.zomboidforge.core;
import java.util.concurrent.atomic.AtomicReference;
/**
* Phase of a server run, advanced by the hooks in the patched game code. {@link #loaded()} and
* {@link #started()} each happen once and in this order; {@link #stopping()} can follow any phase,
* because the JVM can be stopped at any time.
*/
public final class Lifecycle
{
public enum Phase
{
/** The JVM runs; mods are not loaded yet. */
BOOTING,
/** Mods are loaded; the game still loads the world and opens the network port. */
LOADED,
/** The main loop runs. */
RUNNING,
/** The shutdown started; the world is about to be saved. */
STOPPING
}
private final AtomicReference<Phase> phase = new AtomicReference<>(Phase.BOOTING);
public Phase phase() { return this.phase.get(); }
/** {@link Phase#BOOTING} to {@link Phase#LOADED}. */
public void loaded() { this.advance(Phase.BOOTING, Phase.LOADED); }
/** {@link Phase#LOADED} to {@link Phase#RUNNING}. */
public void started() { this.advance(Phase.LOADED, Phase.RUNNING); }
/**
* Any phase to {@link Phase#STOPPING}.
*
* @return {@code false} when the phase already was {@link Phase#STOPPING}
*/
public boolean stopping() { return this.phase.getAndSet(Phase.STOPPING) != Phase.STOPPING; }
private void advance(Phase from, Phase to)
{
Phase current = this.phase.compareAndExchange(from, to);
if (current != from) throw new IllegalStateException("Cannot enter phase '" + to + "' from '" + current + "', only from '" + from + "'.");
}
}
@@ -0,0 +1,70 @@
package dev.overlord.zomboidforge.core.config;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Global settings from {@code <forge>/forge.toml}. Every key is optional:
*
* <pre>
* [main_thread]
* budget_ms = 2 # time per tick for tasks that mods hand to the main thread
*
* [shutdown]
* timeout_s = 10 # how long mod threads get to finish when the server stops
* </pre>
*
* @param mainThreadBudget at least 1 ms
* @param shutdownTimeout 0 or more
*/
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
{
public static final String FILE = "forge.toml";
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10));
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown) {}
private record MainThread(Optional<Long> budgetMs) {}
private record Shutdown(Optional<Long> timeoutS) {}
/**
* The settings in {@code file}, or {@link #DEFAULTS} when it does not exist.
*
* @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values
* of the wrong type or out of range
*/
public static ForgeSettings read(Path file)
{
if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS;
Map<String, Object> values;
try { values = TomlTree.parse(Files.readString(file)); }
catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); }
RecordBinder binder = new RecordBinder();
@Nullable Document document = binder.record(values, Document.class, "");
List<String> problems = new ArrayList<>(binder.problems());
for (String key : binder.unknownKeys()) problems.add("Unknown key '" + key + "'.");
if (document == null || !problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
long budget = document.mainThread().flatMap(MainThread::budgetMs).orElse(ForgeSettings.DEFAULTS.mainThreadBudget().toMillis());
long timeout = document.shutdown().flatMap(Shutdown::timeoutS).orElse(ForgeSettings.DEFAULTS.shutdownTimeout().toSeconds());
if (budget < 1) problems.add("'main_thread.budget_ms' must be at least 1, found " + budget + ".");
if (timeout < 0) problems.add("'shutdown.timeout_s' must not be negative, found " + timeout + ".");
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout));
}
}
@@ -0,0 +1,212 @@
package dev.overlord.zomboidforge.core.config;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.RecordComponent;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* Converts {@link TomlTree} values to records and other Java types. Collects every problem
* instead of stopping at the first one, and records the keys no component reads.
*/
public final class RecordBinder
{
private final List<String> problems = new ArrayList<>();
private final Set<String> unknownKeys = new TreeSet<>();
public List<String> problems() { return List.copyOf(this.problems); }
/** Dotted paths of keys that no record component reads, sorted. */
public List<String> unknownKeys() { return List.copyOf(this.unknownKeys); }
/** Record component name to TOML key: {@code maxBalance} to {@code max_balance}, {@code httpPort} to {@code http_port}. */
public static String key(String component)
{
StringBuilder key = new StringBuilder(component.length() + 4);
for (int i = 0; i < component.length(); i++)
{
char c = component.charAt(i);
boolean upper = Character.isUpperCase(c);
boolean afterLower = i > 0 && !Character.isUpperCase(component.charAt(i - 1));
boolean wordStart = i > 0 && i + 1 < component.length() && Character.isUpperCase(component.charAt(i - 1)) && Character.isLowerCase(component.charAt(i + 1));
if (upper && (afterLower || wordStart)) key.append('_');
key.append(Character.toLowerCase(c));
}
return key.toString();
}
/** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */
public <T extends Record> @Nullable T record(Map<String, Object> table, Class<T> type, String path)
{
RecordComponent[] components = type.getRecordComponents();
@Nullable Object[] arguments = new Object[components.length];
Set<String> keys = new TreeSet<>(table.keySet());
int before = this.problems.size();
for (int i = 0; i < components.length; i++)
{
String key = RecordBinder.key(components[i].getName());
keys.remove(key);
arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key));
}
for (String key : keys) this.unknownKeys.add(RecordBinder.join(path, key));
// value() returns null only after recording a problem, so past this check no argument is null.
if (this.problems.size() > before) return null;
try
{
Constructor<T> constructor = type.getDeclaredConstructor(Arrays.stream(components).map(RecordComponent::getType).toArray(Class<?>[]::new));
constructor.setAccessible(true);
return constructor.newInstance(arguments);
}
catch (InvocationTargetException e)
{
this.problems.add("'" + (path.isEmpty() ? "<root>" : path) + "': " + type.getSimpleName() + " rejected the values: " + e.getCause() + ".");
return null;
}
catch (ReflectiveOperationException e)
{
throw new IllegalStateException("Cannot create record '" + type.getName() + "'.", e);
}
}
/**
* {@code raw} converted to {@code target}, or {@code null} after recording a problem.
* {@code raw == null} means the key is missing.
*/
public @Nullable Object value(@Nullable Object raw, Type target, String path)
{
Class<?> type = RecordBinder.rawType(target);
if (type == Optional.class)
{
if (raw == null) return Optional.empty();
Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path);
return element == null ? null : Optional.of(element);
}
if (raw == null) return this.problem(path, "is missing");
if (type == String.class) return raw instanceof String ? raw : this.mistyped(path, "a string", raw);
if (type == boolean.class || type == Boolean.class) return raw instanceof Boolean ? raw : this.mistyped(path, "true or false", raw);
if (type == long.class || type == Long.class) return raw instanceof Long ? raw : this.mistyped(path, "an integer", raw);
if (type == int.class || type == Integer.class) return this.integer(raw, path);
if (type == double.class || type == Double.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw);
if (type == float.class || type == Float.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw);
if (type.isEnum()) return this.constant(raw, type, path);
if (type.isRecord()) return raw instanceof Map<?, ?> table ? this.record(TomlTree.cast(table), type.asSubclass(Record.class), path) : this.mistyped(path, "a table", raw);
if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path);
if (type == Map.class) return this.map(raw, target, path);
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "', which configuration values cannot have.");
}
private @Nullable Object integer(Object raw, String path)
{
if (!(raw instanceof Long number)) return this.mistyped(path, "an integer", raw);
if (number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) return this.problem(path, "must be between " + Integer.MIN_VALUE + " and " + Integer.MAX_VALUE + ", found " + number);
return number.intValue();
}
private @Nullable Object constant(Object raw, Class<?> type, String path)
{
Object[] constants = type.getEnumConstants();
if (raw instanceof String name) {
for (Object constant : constants) {
if (((Enum<?>) constant).name().equalsIgnoreCase(name)) return constant;
}
}
String allowed = Arrays.stream(constants).map(constant -> "\"" + ((Enum<?>) constant).name().toLowerCase(Locale.ROOT) + "\"").collect(Collectors.joining(", "));
return this.mistyped(path, "one of " + allowed, raw);
}
private @Nullable Object list(Object raw, Type element, String path)
{
if (!(raw instanceof List<?> list)) return this.mistyped(path, "a list", raw);
List<Object> values = new ArrayList<>(list.size());
int before = this.problems.size();
for (int i = 0; i < list.size(); i++)
{
Object value = this.value(list.get(i), element, path + "[" + i + "]");
if (value != null) values.add(value);
}
return this.problems.size() > before ? null : List.copyOf(values);
}
private @Nullable Object map(Object raw, Type target, String path)
{
if (RecordBinder.typeArgument(target, 0) != String.class)
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "'; configuration maps need String keys.");
if (!(raw instanceof Map<?, ?> table)) return this.mistyped(path, "a table", raw);
Map<String, Object> values = new LinkedHashMap<>();
int before = this.problems.size();
for (Map.Entry<String, Object> entry : TomlTree.cast(table).entrySet())
{
Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey()));
if (value != null) values.put(entry.getKey(), value);
}
return this.problems.size() > before ? null : Map.copyOf(values);
}
private @Nullable Object mistyped(String path, String expected, Object raw)
{
String found = raw instanceof Map<?, ?> ? "a table" : raw instanceof List<?> ? "a list" : raw instanceof String text ? "\"" + text + "\"" : String.valueOf(raw);
return this.problem(path, "must be " + expected + ", found " + found);
}
private @Nullable Object problem(String path, String message)
{
this.problems.add("'" + path + "' " + message + ".");
return null;
}
private static Class<?> rawType(Type type)
{
return switch (type)
{
case Class<?> clazz -> clazz;
case ParameterizedType parameters -> (Class<?>) parameters.getRawType();
default -> throw new IllegalArgumentException("Configuration values cannot have the type '" + type.getTypeName() + "'.");
};
}
private static Type typeArgument(Type type, int index)
{
if (type instanceof ParameterizedType parameters) return parameters.getActualTypeArguments()[index];
throw new IllegalArgumentException("'" + type.getTypeName() + "' needs type arguments in configuration records.");
}
private static String join(String path, String key) { return path.isEmpty() ? key : path + "." + key; }
}
@@ -0,0 +1,58 @@
package dev.overlord.zomboidforge.core.config;
import dev.overlord.zomboidforge.api.ModConfig;
import java.util.Map;
import java.util.Optional;
/** {@link ModConfig} over the merged {@link TomlTree} of a mod's {@code config.toml}. */
public final class TomlModConfig implements ModConfig
{
private final Map<String, Object> values;
private final System.Logger logger;
/**
* @param values the settings without the {@code [forge]} table
* @param logger receives warnings about keys no record component reads
*/
public TomlModConfig(Map<String, Object> values, System.Logger logger)
{
this.values = Map.copyOf(values);
this.logger = logger;
}
@Override
public <T extends Record> T bind(Class<T> type)
{
RecordBinder binder = new RecordBinder();
T record = binder.record(this.values, type, "");
if (record == null || !binder.problems().isEmpty())
throw new IllegalStateException("config.toml does not match '" + type.getSimpleName() + "': " + String.join(" ", binder.problems()));
for (String key : binder.unknownKeys()) this.logger.log(System.Logger.Level.WARNING, "config.toml: unknown key '" + key + "'.");
return record;
}
@Override
public <T> Optional<T> get(String path, Class<T> type)
{
Object value = this.values;
for (String key : path.split("\\."))
{
if (!(value instanceof Map<?, ?> table)) return Optional.empty();
value = table.get(key);
if (value == null) return Optional.empty();
}
RecordBinder binder = new RecordBinder();
Object converted = binder.value(value, type, path);
if (converted == null) throw new IllegalStateException("config.toml: " + String.join(" ", binder.problems()));
return Optional.of(type.cast(converted));
}
}
@@ -0,0 +1,81 @@
package dev.overlord.zomboidforge.core.config;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import com.electronwill.nightconfig.core.io.ParsingException;
import com.electronwill.nightconfig.toml.TomlParser;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* TOML documents as plain Java values: tables become {@code Map<String, Object>}, arrays
* {@code List<Object>}, integers {@code Long}, floats {@code Double}; strings and booleans stay
* as they are. Dates and times keep the types of the parser.
*/
public final class TomlTree
{
private TomlTree() {}
/** @throws IllegalArgumentException when {@code toml} is not valid TOML */
public static Map<String, Object> parse(String toml)
{
try { return TomlTree.table(new TomlParser().parse(toml)); }
catch (ParsingException e) { throw new IllegalArgumentException("Not valid TOML: " + e.getMessage(), e); }
}
/**
* {@code overrides} over {@code defaults}: tables are merged key by key, every other value of
* {@code overrides} replaces the default.
*/
public static Map<String, Object> merge(Map<String, Object> defaults, Map<String, Object> overrides)
{
Map<String, Object> merged = new LinkedHashMap<>(defaults);
for (Map.Entry<String, Object> entry : overrides.entrySet())
{
Object defaultValue = merged.get(entry.getKey());
if (defaultValue instanceof Map<?, ?> defaultTable && entry.getValue() instanceof Map<?, ?> table)
merged.put(entry.getKey(), TomlTree.merge(TomlTree.cast(defaultTable), TomlTree.cast(table)));
else
merged.put(entry.getKey(), entry.getValue());
}
return merged;
}
private static Map<String, Object> table(UnmodifiableConfig config)
{
Map<String, Object> table = new LinkedHashMap<>();
for (UnmodifiableConfig.Entry entry : config.entrySet()) table.put(entry.getKey(), TomlTree.value(entry.getRawValue()));
return table;
}
private static Object value(Object raw)
{
return switch (raw)
{
case UnmodifiableConfig config -> TomlTree.table(config);
case List<?> list -> TomlTree.list(list);
case Integer number -> number.longValue();
case Float number -> number.doubleValue();
default -> raw;
};
}
private static List<Object> list(List<?> raw)
{
List<Object> list = new ArrayList<>(raw.size());
for (Object element : raw) list.add(TomlTree.value(element));
return list;
}
@SuppressWarnings("unchecked")
static Map<String, Object> cast(Map<?, ?> table) { return (Map<String, Object>) table; }
}
@@ -0,0 +1,9 @@
/**
* TOML configuration: parsing into plain maps, merging over defaults, and binding to records.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.core.config;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,92 @@
package dev.overlord.zomboidforge.core.mods;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipFile;
/**
* The classes of the Project Zomboid jar (game code and the libraries it bundles). The names
* stay available after {@link #close()}; the class files can be read until then.
*/
public final class GameClasses implements AutoCloseable
{
private static final String CLASS_SUFFIX = ".class";
private static final Pattern VERSIONED = Pattern.compile("META-INF/versions/\\d+/(.+)");
private final @Nullable JarFile file;
private final Set<String> classes;
private final Set<String> packages;
private GameClasses(@Nullable JarFile file, Set<String> classes, Set<String> packages)
{
this.file = file;
this.classes = Set.copyOf(classes);
this.packages = Set.copyOf(packages);
}
/** Indexes {@code jar}; multi-release entries count for their base name. */
public static GameClasses open(Path jar) throws IOException
{
JarFile file = new JarFile(jar.toFile(), true, ZipFile.OPEN_READ, Runtime.version());
Set<String> classes = new HashSet<>();
Set<String> packages = new HashSet<>();
for (JarEntry entry : file.stream().toList())
{
String name = entry.getName();
Matcher versioned = GameClasses.VERSIONED.matcher(name);
if (versioned.matches()) name = versioned.group(1);
if (!name.endsWith(GameClasses.CLASS_SUFFIX) || name.startsWith("META-INF/")) continue;
String internalName = name.substring(0, name.length() - GameClasses.CLASS_SUFFIX.length());
classes.add(internalName);
packages.add(GameClasses.packageOf(internalName));
}
return new GameClasses(file, classes, packages);
}
/** No game classes, for checking a mod that declares no {@code game} versions without a game jar. */
public static GameClasses none() { return new GameClasses(null, Set.of(), Set.of()); }
/** Whether the jar contains the class with this internal name, e.g. {@code zombie/core/Core}. */
public boolean contains(String internalName) { return this.classes.contains(internalName); }
/** Whether the jar contains classes in the package of this internal class name. */
public boolean containsPackageOf(String internalName) { return this.packages.contains(GameClasses.packageOf(internalName)); }
/** The class file for the running Java version, or {@code null} when the jar has none. */
byte @Nullable [] read(String internalName) throws IOException
{
JarFile file = this.file;
if (file == null) return null;
JarEntry entry = file.getJarEntry(internalName + GameClasses.CLASS_SUFFIX);
if (entry == null) return null;
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
}
@Override
public void close() throws IOException
{
JarFile file = this.file;
if (file != null) file.close();
}
static String packageOf(String internalName)
{
int slash = internalName.lastIndexOf('/');
return slash < 0 ? "" : internalName.substring(0, slash);
}
}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.core.mods;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
/** Packages of the modules in the boot layer (the JDK), with the class loader of each. */
final class JdkPackages
{
private static final Map<String, ClassLoader> LOADERS = JdkPackages.loaders();
private JdkPackages() {}
/** The loader for a class of the JDK package {@code dottedPackage}, or {@code null} for other packages. */
static @Nullable ClassLoader loader(String dottedPackage) { return JdkPackages.LOADERS.get(dottedPackage); }
/** Whether the class with this internal name, e.g. {@code java/util/List}, is in a JDK package. */
static boolean contains(String internalName) { return JdkPackages.LOADERS.containsKey(GameClasses.packageOf(internalName).replace('/', '.')); }
private static Map<String, ClassLoader> loaders()
{
Map<String, ClassLoader> loaders = new HashMap<>();
for (Module module : ModuleLayer.boot().modules())
{
// Modules of the boot loader report null; the platform loader delegates to it.
ClassLoader loader = module.getClassLoader() == null ? ClassLoader.getPlatformClassLoader() : module.getClassLoader();
for (String name : module.getPackages()) loaders.put(name, loader);
}
return Map.copyOf(loaders);
}
}
@@ -0,0 +1,132 @@
package dev.overlord.zomboidforge.core.mods;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
/**
* Class loader of one mod, over its jar and its {@code lib/} jars. Lookup order:
*
* <ol>
* <li>JDK classes, from the loader of their module;</li>
* <li>the ZomboidForge API ({@code dev.overlord.zomboidforge.api}, without {@code .internal}),
* from the parent;</li>
* <li>the mod's own jar and libraries;</li>
* <li>the own jars (not the libraries) of the mod's declared dependencies;</li>
* <li>classes of the Project Zomboid jar, from the parent, only for mods that declare
* {@code game} versions.</li>
* </ol>
*
* Everything else on the parent's class path, such as ZomboidForge's own classes and libraries,
* is not visible. A mod's own copy of a library that the game also bundles takes precedence.
*
* <p>The lookup order prevents accidental linkage only. It is not a security boundary: mod code
* can still reach other classes through reflection or {@link ClassLoader#getSystemClassLoader()}.
*/
final class ModClassLoader extends URLClassLoader
{
private static final String API = "dev.overlord.zomboidforge.api.";
private static final String API_INTERNAL = "dev.overlord.zomboidforge.api.internal.";
static { ClassLoader.registerAsParallelCapable(); }
private final String id;
private final Set<String> ownClasses;
private final List<ModClassLoader> dependencies;
private final @Nullable GameClasses game;
/** @param game the game's classes, or {@code null} when the mod declares no {@code game} versions */
ModClassLoader(String id, Path jar, List<Path> libraries, ClassLoader parent, List<ModClassLoader> dependencies, @Nullable GameClasses game)
{
super("mod:" + id, ModClassLoader.urls(jar, libraries), parent);
this.id = id;
this.ownClasses = ModClassLoader.classNames(jar);
this.dependencies = List.copyOf(dependencies);
this.game = game;
}
/** Whether a class with this binary name is part of the mod API. */
static boolean isApi(String name) { return name.startsWith(ModClassLoader.API) && !name.startsWith(ModClassLoader.API_INTERNAL); }
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
{
synchronized (this.getClassLoadingLock(name))
{
Class<?> type = this.findLoadedClass(name);
if (type == null) type = this.lookUp(name);
if (resolve) this.resolveClass(type);
return type;
}
}
/** Resources of the mod's own jars first, then the parent's. */
@Override
public @Nullable URL getResource(String name)
{
URL own = this.findResource(name);
return own != null ? own : super.getResource(name);
}
private Class<?> lookUp(String name) throws ClassNotFoundException
{
int dot = name.lastIndexOf('.');
ClassLoader jdk = JdkPackages.loader(dot < 0 ? "" : name.substring(0, dot));
if (jdk != null) return jdk.loadClass(name);
if (ModClassLoader.isApi(name)) return this.getParent().loadClass(name);
try { return this.findClass(name); }
catch (ClassNotFoundException e) { /* not in the mod's own jars */ }
for (ModClassLoader dependency : this.dependencies) {
if (dependency.ownClasses.contains(name)) return dependency.loadClass(name);
}
if (this.game != null && this.game.contains(name.replace('.', '/'))) return this.getParent().loadClass(name);
throw new ClassNotFoundException(name + " (not visible to mod '" + this.id + "')");
}
private static URL[] urls(Path jar, List<Path> libraries)
{
URL[] urls = new URL[libraries.size() + 1];
urls[0] = ModClassLoader.url(jar);
for (int i = 0; i < libraries.size(); i++) urls[i + 1] = ModClassLoader.url(libraries.get(i));
return urls;
}
private static URL url(Path path)
{
try { return path.toUri().toURL(); }
catch (MalformedURLException e) { throw new IllegalArgumentException("'" + path + "' has no URL.", e); }
}
/** Binary names of the classes in {@code jar}, e.g. {@code com.example.Mod$Inner}. */
private static Set<String> classNames(Path jar)
{
try (JarFile file = new JarFile(jar.toFile()))
{
return file.stream()
.map(JarEntry::getName)
.filter(name -> name.endsWith(".class") && !name.startsWith("META-INF/"))
.map(name -> name.substring(0, name.length() - ".class".length()).replace('/', '.'))
.collect(Collectors.toUnmodifiableSet());
}
catch (IOException e) { throw new UncheckedIOException("Cannot read '" + jar + "'.", e); }
}
}
@@ -0,0 +1,187 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.GameVersion;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import com.electronwill.nightconfig.core.io.ParsingException;
import com.electronwill.nightconfig.toml.TomlParser;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Contents of {@code META-INF/zomboidforge/mod.toml} in a mod's jar, written by the mod's author.
*
* @param game version prefixes of Project Zomboid the mod supports; empty when the mod
* uses no game classes
* @param previousIds earlier ids of the mod, whose storage moves to {@code id}
* @param dependencies mod id to minimum version
*/
public record ModDescriptor(
String id,
String name,
ModVersion version,
String entrypoint,
ModVersion api,
List<String> game,
List<String> previousIds,
Map<String, ModVersion> dependencies
)
{
/** Location of the descriptor inside a mod's jar. */
public static final String PATH = "META-INF/zomboidforge/mod.toml";
/** No {@code __} and no trailing {@code _}: storage tables are named {@code <id>__<table>}. */
private static final Pattern ID = Pattern.compile("[a-z][a-z0-9]*(_[a-z0-9]+)*");
private static final int ID_MAX_LENGTH = 32;
private static final Pattern CLASS_NAME = Pattern.compile("[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
private static final Set<String> RESERVED_IDS = Set.of("forge", "zomboidforge", "core", "api", "game");
private static final Set<String> KEYS = Set.of("id", "name", "version", "entrypoint", "api", "game", "previous_ids", "dependencies");
public ModDescriptor
{
game = List.copyOf(game);
previousIds = List.copyOf(previousIds);
dependencies = Map.copyOf(dependencies);
}
/** Whether {@code id} is a valid mod id that is not reserved. */
public static boolean isValidId(String id)
{
return id.length() <= ModDescriptor.ID_MAX_LENGTH
&& ModDescriptor.ID.matcher(id).matches()
&& !ModDescriptor.RESERVED_IDS.contains(id);
}
/** @throws ModLoadException listing every problem of the descriptor */
public static ModDescriptor parse(String toml) throws ModLoadException
{
UnmodifiableConfig config;
try { config = new TomlParser().parse(toml); }
catch (ParsingException e) { throw new ModLoadException("Not valid TOML: " + e.getMessage(), e); }
Reader reader = new Reader(config);
for (UnmodifiableConfig.Entry entry : config.entrySet()) {
if (!ModDescriptor.KEYS.contains(entry.getKey())) reader.problems.add("Unknown key '" + entry.getKey() + "'.");
}
String id = reader.string("id", true);
String name = reader.string("name", false);
ModVersion version = reader.version("version");
String entrypoint = reader.string("entrypoint", true);
ModVersion api = reader.version("api");
List<String> game = reader.stringList("game");
List<String> previousIds = reader.stringList("previous_ids");
Map<String, ModVersion> dependencies = reader.dependencies();
if (id != null && !ModDescriptor.isValidId(id)) reader.problems.add("'id' = '" + id + "' is not a valid mod id (" + ModDescriptor.ID.pattern() + ", at most " + ModDescriptor.ID_MAX_LENGTH + " characters, not one of " + ModDescriptor.RESERVED_IDS + ").");
if (entrypoint != null && !ModDescriptor.CLASS_NAME.matcher(entrypoint).matches()) reader.problems.add("'entrypoint' = '" + entrypoint + "' is not a class name.");
if (reader.has("game") && game.isEmpty()) reader.problems.add("'game' is empty; leave it out when the mod uses no game classes.");
for (String prefix : game) {
if (!GameVersion.isPrefix(prefix)) reader.problems.add("'game' contains '" + prefix + "', which is not a version prefix such as '42' or '42.21'.");
}
for (String previousId : previousIds) {
if (!ModDescriptor.isValidId(previousId) || previousId.equals(id)) reader.problems.add("'previous_ids' contains '" + previousId + "', which is not a valid earlier mod id.");
}
if (id != null && dependencies.containsKey(id)) reader.problems.add("'dependencies' contains the mod itself.");
if (!reader.problems.isEmpty() || id == null || version == null || entrypoint == null || api == null)
throw new ModLoadException(reader.problems);
return new ModDescriptor(id, name == null ? id : name, version, entrypoint, api, game, previousIds, dependencies);
}
/** Reads typed values and collects a problem for each missing or mistyped one. */
private static final class Reader
{
private final UnmodifiableConfig config;
private final List<String> problems = new ArrayList<>();
private Reader(UnmodifiableConfig config) { this.config = config; }
private boolean has(String key) { return this.config.contains(key); }
private @Nullable String string(String key, boolean required)
{
Object value = this.config.get(key);
if (value == null) {
if (required) this.problems.add("'" + key + "' is missing.");
return null;
}
if (value instanceof String text && !text.isBlank()) return text.trim();
this.problems.add("'" + key + "' must be a non-empty string.");
return null;
}
private @Nullable ModVersion version(String key)
{
String text = this.string(key, true);
if (text == null) return null;
ModVersion version = ModVersion.tryParse(text).orElse(null);
if (version == null) this.problems.add("'" + key + "' = '" + text + "' is not a version such as '1.2.0'.");
return version;
}
private List<String> stringList(String key)
{
Object value = this.config.get(key);
if (value == null) return List.of();
List<String> strings = new ArrayList<>();
if (value instanceof List<?> list)
{
for (Object element : list) {
if (element instanceof String text) strings.add(text.trim());
else this.problems.add("'" + key + "' must contain only strings.");
}
}
else this.problems.add("'" + key + "' must be a list of strings, e.g. [\"a\", \"b\"].");
return strings;
}
private Map<String, ModVersion> dependencies()
{
Object value = this.config.get("dependencies");
if (value == null) return Map.of();
if (!(value instanceof UnmodifiableConfig table)) {
this.problems.add("'dependencies' must be a table of mod id = minimum version.");
return Map.of();
}
Map<String, ModVersion> dependencies = new LinkedHashMap<>();
for (UnmodifiableConfig.Entry entry : table.entrySet())
{
String dependency = entry.getKey();
ModVersion minimum = entry.getRawValue() instanceof String text ? ModVersion.tryParse(text).orElse(null) : null;
if (!ModDescriptor.isValidId(dependency)) this.problems.add("'dependencies' contains '" + dependency + "', which is not a valid mod id.");
if (minimum == null) this.problems.add("'dependencies." + dependency + "' must be a version string such as \"1.2\".");
else dependencies.put(dependency, minimum);
}
return dependencies;
}
}
}
@@ -0,0 +1,228 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.core.config.TomlTree;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
/**
* Finds the mods in {@code <forge>/mods}. Every mod is a folder named after its id:
*
* <pre>
* mods/&lt;id&gt;/
* &lt;id&gt;.jar the mod, with META-INF/zomboidforge/mod.toml
* lib/*.jar libraries of the mod (optional)
* config.toml settings of the mod (optional)
* </pre>
*/
public final class ModDiscovery
{
/** Location of the default settings inside a mod's jar. */
public static final String DEFAULT_CONFIG = "META-INF/zomboidforge/config.toml";
public static final String CONFIG = "config.toml";
private static final String JAR_SUFFIX = ".jar";
private static final String LIBRARIES = "lib";
private static final String FORGE_TABLE = "forge";
private static final String ENABLED = "enabled";
/**
* A mod folder whose descriptor and settings were read.
*
* @param enabled {@code [forge] enabled} from the settings; {@code true} when missing
* @param config the settings over the defaults from the jar, without the {@code [forge]} table
*/
public record Candidate(Path directory, Path jar, List<Path> libraries, ModDescriptor descriptor, boolean enabled, Map<String, Object> config)
{
public Candidate
{
libraries = List.copyOf(libraries);
config = Map.copyOf(config);
}
public String id() { return this.descriptor.id(); }
}
private record JarContents(String descriptor, byte @Nullable [] defaultConfig) {}
private ModDiscovery() {}
/**
* Reads every mod folder in {@code modsDirectory}, sorted by folder name. Writes the default
* settings of a mod to {@code config.toml} when the folder has none and is writable.
*
* @param logger receives notes about written or unwritable default settings
* @throws ModLoadException listing the problems of every folder
*/
public static List<Candidate> discover(Path modsDirectory, System.Logger logger) throws ModLoadException
{
List<Candidate> candidates = new ArrayList<>();
List<String> problems = new ArrayList<>();
for (Path entry : ModDiscovery.sortedEntries(modsDirectory))
{
String name = entry.getFileName().toString();
if (name.startsWith(".")) continue;
if (!Files.isDirectory(entry)) {
problems.add("'" + name + "': not a folder; every mod is a folder 'mods/<id>/' with '<id>.jar' inside.");
continue;
}
try { candidates.add(ModDiscovery.read(entry, logger)); }
catch (ModLoadException e) { e.problems().forEach(problem -> problems.add("'" + name + "': " + problem)); }
}
if (!problems.isEmpty()) throw new ModLoadException(problems);
return candidates;
}
private static Candidate read(Path directory, System.Logger logger) throws ModLoadException
{
String name = directory.getFileName().toString();
Path jar = directory.resolve(name + ModDiscovery.JAR_SUFFIX);
List<String> problems = new ArrayList<>();
for (Path entry : ModDiscovery.sortedEntries(directory)) {
if (ModDiscovery.isJar(entry) && !entry.equals(jar)) problems.add("'" + entry.getFileName() + "' is not '" + jar.getFileName() + "'; the folder may contain only the mod's own jar (libraries go into 'lib/').");
}
if (!Files.isRegularFile(jar)) problems.add("'" + jar.getFileName() + "' is missing.");
if (!problems.isEmpty()) throw new ModLoadException(problems);
JarContents contents = ModDiscovery.contents(jar);
ModDescriptor descriptor = ModDiscovery.descriptor(contents.descriptor());
if (!descriptor.id().equals(name)) throw new ModLoadException(List.of("The folder is named '" + name + "', but 'mod.toml' declares the id '" + descriptor.id() + "'."));
Path libraryDirectory = directory.resolve(ModDiscovery.LIBRARIES);
List<Path> libraries = Files.isDirectory(libraryDirectory)
? ModDiscovery.sortedEntries(libraryDirectory).stream().filter(ModDiscovery::isJar).toList()
: List.of();
Map<String, Object> config = ModDiscovery.config(directory, contents.defaultConfig(), logger, problems);
boolean enabled = ModDiscovery.enabled(config.remove(ModDiscovery.FORGE_TABLE), problems);
if (!problems.isEmpty()) throw new ModLoadException(problems);
return new Candidate(directory, jar, libraries, descriptor, enabled, config);
}
/** The folder's {@code config.toml} over the jar's defaults, as a mutable map. */
private static Map<String, Object> config(Path directory, byte @Nullable [] defaultConfig, System.Logger logger, List<String> problems)
{
Path file = directory.resolve(ModDiscovery.CONFIG);
Map<String, Object> defaults = Map.of();
Map<String, Object> settings = Map.of();
if (defaultConfig != null)
{
try
{
defaults = TomlTree.parse(new String(defaultConfig, StandardCharsets.UTF_8));
}
catch (IllegalArgumentException e)
{
// Invalid defaults are reported and never copied to the folder.
problems.add("'" + ModDiscovery.DEFAULT_CONFIG + "' in the jar: " + e.getMessage());
return new LinkedHashMap<>();
}
}
if (Files.isRegularFile(file))
{
try { settings = TomlTree.parse(Files.readString(file)); }
catch (IOException e) { problems.add("Cannot read '" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
catch (IllegalArgumentException e) { problems.add("'" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
}
else if (defaultConfig != null)
{
String id = directory.getFileName().toString();
try
{
Files.write(file, defaultConfig, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
logger.log(System.Logger.Level.INFO, "'" + id + "': wrote the default settings to '" + file + "'.");
}
catch (IOException | UnsupportedOperationException e)
{
logger.log(System.Logger.Level.INFO, "'" + id + "': cannot write the default settings to '" + file + "' (" + e + "); using them without a file.");
}
}
return TomlTree.merge(defaults, settings);
}
/** {@code [forge] enabled}; {@code true} without a {@code [forge]} table. */
private static boolean enabled(@Nullable Object forge, List<String> problems)
{
if (forge == null) return true;
if (!(forge instanceof Map<?, ?> table)) {
problems.add("'" + ModDiscovery.CONFIG + "': 'forge' must be a table ([forge]).");
return true;
}
boolean enabled = true;
for (Map.Entry<?, ?> entry : table.entrySet())
{
if (!ModDiscovery.ENABLED.equals(entry.getKey()))
problems.add("'" + ModDiscovery.CONFIG + "': unknown key 'forge." + entry.getKey() + "'; [forge] only has 'enabled'.");
else if (entry.getValue() instanceof Boolean value)
enabled = value;
else
problems.add("'" + ModDiscovery.CONFIG + "': 'forge.enabled' must be true or false.");
}
return enabled;
}
private static JarContents contents(Path jar) throws ModLoadException
{
try (JarFile file = new JarFile(jar.toFile()))
{
byte[] descriptor = ModDiscovery.entry(file, ModDescriptor.PATH);
if (descriptor == null) throw new ModLoadException(List.of("'" + jar.getFileName() + "' contains no '" + ModDescriptor.PATH + "'."));
return new JarContents(new String(descriptor, StandardCharsets.UTF_8), ModDiscovery.entry(file, ModDiscovery.DEFAULT_CONFIG));
}
catch (IOException e) { throw new ModLoadException("Cannot read '" + jar.getFileName() + "': " + e.getMessage(), e); }
}
private static byte @Nullable [] entry(JarFile file, String name) throws IOException
{
ZipEntry entry = file.getEntry(name);
if (entry == null) return null;
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
}
private static ModDescriptor descriptor(String toml) throws ModLoadException
{
try { return ModDescriptor.parse(toml); }
catch (ModLoadException e) { throw new ModLoadException(e.problems().stream().map(problem -> "mod.toml: " + problem).toList()); }
}
private static boolean isJar(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(ModDiscovery.JAR_SUFFIX); }
private static List<Path> sortedEntries(Path directory) throws ModLoadException
{
try (Stream<Path> entries = Files.list(directory)) { return entries.sorted().toList(); }
catch (IOException e) { throw new ModLoadException("Cannot list '" + directory + "': " + e.getMessage(), e); }
}
}
@@ -0,0 +1,32 @@
package dev.overlord.zomboidforge.core.mods;
import java.io.Serial;
import java.util.List;
/** The mods cannot be loaded; {@link #problems()} lists every problem found, one line each. */
public final class ModLoadException extends Exception
{
@Serial
private static final long serialVersionUID = 1L;
/** Not serialized; the exception is only used inside the server process. */
private final transient List<String> problems;
public ModLoadException(List<String> problems)
{
super(String.join("\n", problems));
if (problems.isEmpty()) throw new IllegalArgumentException("A ModLoadException needs at least one problem.");
this.problems = List.copyOf(problems);
}
public ModLoadException(String problem, Throwable cause)
{
super(problem, cause);
this.problems = List.of(problem);
}
public List<String> problems() { return this.problems; }
}
@@ -0,0 +1,169 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.ModConfig;
import dev.overlord.zomboidforge.api.ModContext;
import dev.overlord.zomboidforge.api.ModThread;
import dev.overlord.zomboidforge.api.internal.ModBinding;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import dev.overlord.zomboidforge.core.ConsoleLogger;
import dev.overlord.zomboidforge.core.config.TomlModConfig;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Creates the class loaders and entry points of resolved mods, in order, and calls
* {@link Mod#onLoad()} on each. Stops at the first mod that fails.
*/
public final class ModLoader
{
/** A mod whose entry point was created and whose {@link Mod#onLoad()} returned. */
public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {}
private record Context(
String id,
String version,
GameVersion gameVersion,
System.Logger logger,
Path directory,
ModConfig config,
Events events,
MainThread main,
ModThread modThread,
AsyncExecutor async,
ModStorage storage
) implements ModContext {}
private ModLoader() {}
/**
* @param ordered mods in load order, as returned by {@link ModResolver#resolve} and checked
* by {@link ModVerifier#verify}
* @param parent parent of every mod's class loader
* @param gameClasses classes of the Project Zomboid jar, visible to mods that declare
* {@code game} versions
* @param services creates each mod's threads and event registration
* @throws ModLoadException naming the mod that failed and why
*/
public static List<LoadedMod> load(List<ModDiscovery.Candidate> ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses, ModServices.Factory services) throws ModLoadException
{
Map<String, ModClassLoader> loaders = new HashMap<>();
List<LoadedMod> loaded = new ArrayList<>();
try
{
for (ModDiscovery.Candidate candidate : ordered)
{
ModDescriptor descriptor = candidate.descriptor();
List<ModClassLoader> dependencies = descriptor.dependencies().keySet().stream()
.sorted()
.map(dependency -> Objects.requireNonNull(loaders.get(dependency), "'" + dependency + "' is not loaded before '" + descriptor.id() + "'."))
.toList();
@Nullable GameClasses visible = descriptor.game().isEmpty() ? null : gameClasses;
ModClassLoader loader = new ModClassLoader(descriptor.id(), candidate.jar(), candidate.libraries(), parent, dependencies, visible);
loaders.put(descriptor.id(), loader);
System.Logger logger = new ConsoleLogger("ZomboidForge/" + descriptor.id());
ModServices provided = services.create(descriptor.id(), logger);
Context context = new Context(
descriptor.id(),
descriptor.version().toString(),
game,
logger,
candidate.directory(),
new TomlModConfig(candidate.config(), logger),
provided.events(),
provided.main(),
provided.modThread(),
provided.async(),
provided.storage()
);
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
}
return List.copyOf(loaded);
}
catch (ModLoadException | RuntimeException e)
{
ModLoader.close(loaders.values());
throw e;
}
}
private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context) throws ModLoadException
{
String id = descriptor.id();
Constructor<? extends Mod> constructor = ModLoader.constructor(descriptor, loader);
Mod mod;
try
{
mod = ScopedValue.where(ModBinding.CONTEXT, context).call(constructor::newInstance);
}
catch (InvocationTargetException e)
{
throw new ModLoadException(ModLoader.sentence("'" + id + "': the constructor of '" + descriptor.entrypoint() + "' threw " + e.getCause()), e.getCause());
}
catch (ReflectiveOperationException | LinkageError e)
{
throw new ModLoadException(ModLoader.sentence("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e), e);
}
try { mod.onLoad(); }
catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); }
catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); }
return mod;
}
private static Constructor<? extends Mod> constructor(ModDescriptor descriptor, ClassLoader loader) throws ModLoadException
{
String id = descriptor.id();
String entrypoint = descriptor.entrypoint();
Class<?> type;
try { type = Class.forName(entrypoint, false, loader); }
catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': entry point '" + entrypoint + "' cannot be loaded: " + e), e); }
if (!Mod.class.isAssignableFrom(type))
throw new ModLoadException(List.of("'" + id + "': entry point '" + entrypoint + "' does not extend '" + Mod.class.getName() + "'."));
if (Modifier.isAbstract(type.getModifiers()))
throw new ModLoadException(List.of("'" + id + "': entry point '" + entrypoint + "' is abstract."));
try { return type.asSubclass(Mod.class).getConstructor(); }
catch (NoSuchMethodException e) { throw new ModLoadException("'" + id + "': entry point '" + entrypoint + "' has no public constructor without parameters.", e); }
}
/** {@code text} ending with a period; exception messages often have one already. */
private static String sentence(String text) { return text.endsWith(".") ? text : text + "."; }
private static void close(Iterable<ModClassLoader> loaders)
{
for (ModClassLoader loader : loaders) {
try { loader.close(); }
catch (IOException e) { /* the server stops anyway */ }
}
}
}
@@ -0,0 +1,114 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.GameVersion;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Checks the API version, the game versions, and the dependencies of discovered mods, and orders
* them so that every mod comes after its dependencies (otherwise by id).
*/
public final class ModResolver
{
private ModResolver() {}
/**
* Returns the enabled mods in load order; disabled mods are left out.
*
* @param api the running ZomboidForge API version, or {@code null} to skip the API check
* (development builds)
* @throws ModLoadException listing every problem of every enabled mod
*/
public static List<ModDiscovery.Candidate> resolve(List<ModDiscovery.Candidate> candidates, GameVersion game, @Nullable ModVersion api) throws ModLoadException
{
Map<String, ModDiscovery.Candidate> byId = candidates.stream().filter(ModDiscovery.Candidate::enabled).collect(Collectors.toMap(ModDiscovery.Candidate::id, Function.identity(), (a, b) -> a, TreeMap::new));
Set<String> disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).collect(Collectors.toSet());
List<String> problems = new ArrayList<>();
for (ModDiscovery.Candidate candidate : byId.values())
{
ModDescriptor descriptor = candidate.descriptor();
String id = descriptor.id();
if (api != null && !api.providesApi(descriptor.api()))
problems.add("'" + id + "': built against ZomboidForge API " + descriptor.api() + ", the server provides " + api + ".");
for (String previous : descriptor.previousIds()) {
if (byId.containsKey(previous)) problems.add("'" + id + "': 'previous_ids' contains '" + previous + "', which is installed as a mod.");
}
if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(game::matches))
problems.add("'" + id + "': supports Project Zomboid " + descriptor.game() + ", the server runs " + game + ".");
for (Map.Entry<String, ModVersion> dependency : new TreeMap<>(descriptor.dependencies()).entrySet())
{
ModDiscovery.Candidate installed = byId.get(dependency.getKey());
if (installed == null && disabled.contains(dependency.getKey()))
problems.add("'" + id + "': requires '" + dependency.getKey() + "', which is disabled in its config.toml.");
else if (installed == null)
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, which is not installed.");
else if (installed.descriptor().version().compareTo(dependency.getValue()) < 0)
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, " + installed.descriptor().version() + " is installed.");
}
}
if (!problems.isEmpty()) throw new ModLoadException(problems);
return new Order(byId).sorted();
}
/** Depth-first ordering that reports dependency cycles. */
private static final class Order
{
private final Map<String, ModDiscovery.Candidate> byId;
private final Set<String> done = new HashSet<>();
private final LinkedHashSet<String> visiting = new LinkedHashSet<>();
private final List<ModDiscovery.Candidate> sorted = new ArrayList<>();
private final List<String> problems = new ArrayList<>();
private Order(Map<String, ModDiscovery.Candidate> byId) { this.byId = byId; }
private List<ModDiscovery.Candidate> sorted() throws ModLoadException
{
for (String id : this.byId.keySet()) this.visit(id);
if (!this.problems.isEmpty()) throw new ModLoadException(this.problems);
return List.copyOf(this.sorted);
}
private void visit(String id)
{
if (this.done.contains(id)) return;
if (!this.visiting.add(id))
{
List<String> path = new ArrayList<>(this.visiting);
List<String> cycle = new ArrayList<>(path.subList(path.indexOf(id), path.size()));
cycle.add(id);
this.problems.add("'" + id + "': dependency cycle " + cycle.stream().map(element -> "'" + element + "'").collect(Collectors.joining(" -> ")) + ".");
return;
}
ModDiscovery.Candidate candidate = Objects.requireNonNull(this.byId.get(id));
for (String dependency : new TreeMap<>(candidate.descriptor().dependencies()).keySet()) this.visit(dependency);
this.visiting.remove(id);
if (this.done.add(id)) this.sorted.add(candidate);
}
}
}
@@ -0,0 +1,18 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.ModThread;
import dev.overlord.zomboidforge.api.storage.ModStorage;
/** The threads, event registration, and storage of one mod, created before its entry point. */
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage)
{
/** Creates the services of one mod. */
@FunctionalInterface
public interface Factory
{
ModServices create(String id, System.Logger logger);
}
}
@@ -0,0 +1,384 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.GameVersion;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.RecordComponentVisitor;
import org.objectweb.asm.Type;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
/**
* Checks the classes of resolved mods before any of them is loaded:
*
* <ul>
* <li>no class in a ZomboidForge package, and no class in the mod's own jar with the name of a
* game class;</li>
* <li>no use of ZomboidForge classes outside the API;</li>
* <li>a mod that uses classes of the Project Zomboid jar declares {@code game} versions;</li>
* <li>every game class, field, and method such a mod uses exists in the running jar
* (members are looked up through superclasses and interfaces).</li>
* </ul>
*
* Annotations are not checked: the JVM does not load annotation types a class only carries.
*/
public final class ModVerifier
{
private static final String FORGE = "dev/overlord/zomboidforge/";
private static final String API = "dev/overlord/zomboidforge/api/";
private static final String API_INTERNAL = "dev/overlord/zomboidforge/api/internal/";
private static final int EXAMPLES = 5;
/** A field or method that a mod's code uses. */
private record Member(boolean method, String owner, String name, String desc) implements Comparable<Member>
{
@Override
public int compareTo(Member other) { return this.toString().compareTo(other.toString()); }
@Override
public String toString() { return this.owner.replace('/', '.') + "." + this.name + (this.method ? "" : ":") + this.desc; }
}
private ModVerifier() {}
/**
* @param ordered mods in load order, as returned by {@link ModResolver#resolve}
* @param version the version of {@code game}, for messages; {@code null} with {@link GameClasses#none()}
* @throws ModLoadException listing every problem of every mod
*/
public static void verify(List<ModDiscovery.Candidate> ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException
{
Hierarchy hierarchy = new Hierarchy(game);
Map<String, Set<String>> ownByMod = new HashMap<>();
List<String> problems = new ArrayList<>();
for (ModDiscovery.Candidate candidate : ordered)
{
String id = candidate.id();
Map<String, byte[]> own = ModVerifier.classes(candidate.jar());
Map<String, byte[]> libraries = new TreeMap<>();
for (Path library : candidate.libraries()) libraries.putAll(ModVerifier.classes(library));
ownByMod.put(id, own.keySet());
Set<String> provided = new HashSet<>(own.keySet());
provided.addAll(libraries.keySet());
for (String dependency : candidate.descriptor().dependencies().keySet()) provided.addAll(ownByMod.getOrDefault(dependency, Set.of()));
Set<String> contained = new TreeSet<>(own.keySet());
contained.addAll(libraries.keySet());
for (String name : contained) {
if (name.startsWith(ModVerifier.FORGE)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is in a ZomboidForge package.");
}
for (String name : new TreeSet<>(own.keySet())) {
if (game.contains(name)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is a class of Project Zomboid.");
}
References references = new References();
for (byte[] bytes : own.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
for (byte[] bytes : libraries.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
Set<String> gameTypes = new TreeSet<>();
Set<String> missingTypes = new TreeSet<>();
for (String type : references.types)
{
if (JdkPackages.contains(type) || provided.contains(type)) continue;
if (type.startsWith(ModVerifier.FORGE) && (!type.startsWith(ModVerifier.API) || type.startsWith(ModVerifier.API_INTERNAL)))
problems.add("'" + id + "': uses '" + ModVerifier.dotted(type) + "', which is internal to ZomboidForge.");
else if (game.contains(type))
gameTypes.add(type);
else if (!type.startsWith(ModVerifier.FORGE) && game.containsPackageOf(type))
missingTypes.add(type);
}
boolean declaresGame = !candidate.descriptor().game().isEmpty();
if (!declaresGame && !(gameTypes.isEmpty() && missingTypes.isEmpty()))
{
Set<String> used = new TreeSet<>(gameTypes);
used.addAll(missingTypes);
problems.add("'" + id + "': uses classes of the Project Zomboid jar (" + ModVerifier.examples(used) + ") but declares no 'game' versions in mod.toml.");
continue;
}
List<String> linkage = new ArrayList<>();
for (String type : missingTypes) linkage.add("'" + ModVerifier.dotted(type) + "'");
for (Member member : references.members) {
if (gameTypes.contains(member.owner()) && !hierarchy.has(member)) linkage.add("'" + member + "'");
}
if (!linkage.isEmpty())
problems.add("'" + id + "': uses " + ModVerifier.examples(linkage) + ", which " + (linkage.size() == 1 ? "does" : "do") + " not exist in " + (version == null ? "the game jar" : "Project Zomboid " + version) + ".");
}
if (!problems.isEmpty()) throw new ModLoadException(problems);
}
/** Internal class name to class file, for every class in {@code jar} outside {@code META-INF/}. */
private static Map<String, byte[]> classes(Path jar)
{
Map<String, byte[]> classes = new TreeMap<>();
try (JarFile file = new JarFile(jar.toFile()))
{
for (JarEntry entry : file.stream().toList())
{
String name = entry.getName();
if (!name.endsWith(".class") || name.startsWith("META-INF/") || name.endsWith("module-info.class")) continue;
try (InputStream in = file.getInputStream(entry)) { classes.put(name.substring(0, name.length() - ".class".length()), in.readAllBytes()); }
}
}
catch (IOException e) { throw new UncheckedIOException("Cannot read '" + jar + "'.", e); }
return classes;
}
/** The first {@value #EXAMPLES} elements, quoted unless already quoted, and how many more there are. */
private static String examples(Iterable<String> elements)
{
List<String> all = new ArrayList<>();
for (String element : elements) all.add(element.startsWith("'") ? element : "'" + ModVerifier.dotted(element) + "'");
String shown = all.stream().limit(ModVerifier.EXAMPLES).collect(Collectors.joining(", "));
return all.size() > ModVerifier.EXAMPLES ? shown + " and " + (all.size() - ModVerifier.EXAMPLES) + " more" : shown;
}
private static String dotted(String internalName) { return internalName.replace('/', '.'); }
/** Collects the classes and members that code uses; skips annotations and debug information. */
private static final class References extends ClassVisitor
{
private final Set<String> types = new TreeSet<>();
private final Set<Member> members = new TreeSet<>();
private References() { super(Opcodes.ASM9); }
@Override
public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String @Nullable [] interfaces)
{
if (superName != null) this.type(superName);
if (interfaces != null) for (String type : interfaces) this.type(type);
}
@Override
public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
{
this.descriptor(descriptor);
return null;
}
@Override
public @Nullable RecordComponentVisitor visitRecordComponent(String name, String descriptor, @Nullable String signature)
{
this.descriptor(descriptor);
return null;
}
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
{
this.descriptor(descriptor);
if (exceptions != null) for (String type : exceptions) this.type(type);
References references = this;
return new MethodVisitor(Opcodes.ASM9)
{
@Override
public void visitTypeInsn(int opcode, String type) { references.type(type); }
@Override
public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { references.member(false, owner, name, descriptor); }
@Override
public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) { references.member(true, owner, name, descriptor); }
@Override
public void visitInvokeDynamicInsn(String name, String descriptor, Handle bootstrap, Object... arguments)
{
references.descriptor(descriptor);
references.constant(bootstrap);
for (Object argument : arguments) references.constant(argument);
}
@Override
public void visitLdcInsn(Object value) { references.constant(value); }
@Override
public void visitMultiANewArrayInsn(String descriptor, int dimensions) { references.descriptor(descriptor); }
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, @Nullable String type)
{
if (type != null) references.type(type);
}
};
}
private void member(boolean method, String owner, String name, String descriptor)
{
this.type(owner);
this.descriptor(descriptor);
if (!owner.startsWith("[")) this.members.add(new Member(method, owner, name, descriptor));
}
private void constant(Object value)
{
switch (value)
{
case Handle handle -> this.member(handle.getTag() > Opcodes.H_PUTSTATIC, handle.getOwner(), handle.getName(), handle.getDesc());
case Type type -> this.descriptor(type.getDescriptor());
default -> { /* numbers, strings, dynamic constants */ }
}
}
/** An internal class name, or an array descriptor as used by {@code anewarray} and {@code checkcast}. */
private void type(String name)
{
if (name.startsWith("[")) this.descriptor(name);
else this.types.add(name);
}
private void descriptor(String descriptor)
{
Type type = Type.getType(descriptor);
if (type.getSort() == Type.METHOD)
{
for (Type argument : type.getArgumentTypes()) this.add(argument);
this.add(type.getReturnType());
}
else this.add(type);
}
private void add(Type type)
{
Type element = type.getSort() == Type.ARRAY ? type.getElementType() : type;
if (element.getSort() == Type.OBJECT) this.types.add(element.getInternalName());
}
}
/** Fields and methods of game and JDK classes, read from their class files. */
private static final class Hierarchy
{
private record Info(@Nullable String superName, List<String> interfaces, Set<String> fields, Set<String> methods) {}
private final GameClasses game;
private final Map<String, @Nullable Info> cache = new HashMap<>();
private Hierarchy(GameClasses game) { this.game = game; }
/**
* Whether {@code member} resolves in its owner, a superclass, or a superinterface.
* Constructors only count in the owner. Supertypes whose class files cannot be read
* count as having every member.
*/
private boolean has(Member member)
{
String key = member.name() + member.desc();
Deque<String> pending = new ArrayDeque<>(List.of(member.owner()));
Set<String> seen = new HashSet<>();
while (!pending.isEmpty())
{
String type = pending.pop();
if (!seen.add(type)) continue;
Info info = this.info(type);
if (info == null) return !type.equals(member.owner());
if ((member.method() ? info.methods() : info.fields()).contains(key)) return true;
if (member.method() && member.name().equals("<init>")) return false;
if (info.superName() != null) pending.add(info.superName());
pending.addAll(info.interfaces());
}
// Interface methods may also be declared by java.lang.Object.
return member.method() && !member.owner().equals("java/lang/Object") && this.has(new Member(true, "java/lang/Object", member.name(), member.desc()));
}
private @Nullable Info info(String type)
{
if (this.cache.containsKey(type)) return this.cache.get(type);
Info info = null;
try
{
byte[] bytes = this.game.contains(type) ? this.game.read(type) : JdkPackages.contains(type) ? Hierarchy.jdkClass(type) : null;
if (bytes != null) info = Hierarchy.read(bytes);
}
catch (IOException e) { throw new UncheckedIOException("Cannot read class '" + type + "'.", e); }
this.cache.put(type, info);
return info;
}
private static byte @Nullable [] jdkClass(String type) throws IOException
{
try (InputStream in = ClassLoader.getSystemResourceAsStream(type + ".class")) { return in == null ? null : in.readAllBytes(); }
}
private static Info read(byte[] bytes)
{
ClassReader reader = new ClassReader(bytes);
Set<String> fields = new HashSet<>();
Set<String> methods = new HashSet<>();
reader.accept(new ClassVisitor(Opcodes.ASM9)
{
@Override
public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
{
fields.add(name + descriptor);
return null;
}
@Override
public @Nullable MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
{
methods.add(name + descriptor);
return null;
}
}, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
return new Info(reader.getSuperName(), List.of(reader.getInterfaces()), fields, methods);
}
}
}
@@ -0,0 +1,66 @@
package dev.overlord.zomboidforge.core.mods;
import org.jetbrains.annotations.Nullable;
import java.util.Comparator;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Semantic version of a mod or of the ZomboidForge API: {@code major[.minor[.patch]][-pre-release]},
* missing parts are 0. A pre-release sorts before the release with the same numbers.
*/
public record ModVersion(int major, int minor, int patch, @Nullable String preRelease) implements Comparable<ModVersion>
{
// At most 9 digits per number, so every number fits an int.
private static final Pattern FORMAT = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9}))?(?:\\.(\\d{1,9}))?(?:-([0-9A-Za-z.-]+))?");
private static final Comparator<ModVersion> ORDER = Comparator
.comparingInt(ModVersion::major)
.thenComparingInt(ModVersion::minor)
.thenComparingInt(ModVersion::patch)
.thenComparing(ModVersion::preRelease, Comparator.nullsLast(Comparator.naturalOrder()));
public static ModVersion parse(String text)
{
return ModVersion.tryParse(text).orElseThrow(() -> new IllegalArgumentException("Not a version: '" + text + "'."));
}
public static Optional<ModVersion> tryParse(String text)
{
Matcher matcher = ModVersion.FORMAT.matcher(text.trim());
if (!matcher.matches()) return Optional.empty();
return Optional.of(new ModVersion(
Integer.parseInt(matcher.group(1)),
ModVersion.partOrZero(matcher.group(2)),
ModVersion.partOrZero(matcher.group(3)),
matcher.group(4)
));
}
/**
* Whether a mod built against the API version {@code required} runs with this API version:
* same major version and this version not older. Before 1.0 the minor version must match
* as well, because 0.x releases may break the API.
*/
public boolean providesApi(ModVersion required)
{
if (this.major != required.major || this.compareTo(required) < 0) return false;
return this.major != 0 || this.minor == required.minor;
}
@Override
public int compareTo(ModVersion other) { return ModVersion.ORDER.compare(this, other); }
@Override
public String toString()
{
String numbers = this.major + "." + this.minor + "." + this.patch;
return this.preRelease == null ? numbers : numbers + "-" + this.preRelease;
}
private static int partOrZero(@Nullable String part) { return part == null ? 0 : Integer.parseInt(part); }
}
@@ -0,0 +1,9 @@
/**
* Mod discovery, validation, and loading from {@code <forge>/mods}.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.core.mods;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1,5 +1,10 @@
/** /**
* Version-independent runtime: mod loading, events, configuration. Contains no * Version-independent runtime: mod loading, events, configuration. Contains no
* references to game classes; game-specific code is in the compat modules. * references to game classes; game-specific code is in the compat modules.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/ */
@NotNullByDefault
package dev.overlord.zomboidforge.core; package dev.overlord.zomboidforge.core;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,173 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.MainThreadEvent;
import dev.overlord.zomboidforge.api.Subscription;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/**
* Event dispatch for every mod. Listeners are matched by the event's exact class and called in
* registration order. Registration replaces the listener array of a class, so {@link #post}
* iterates a snapshot without locks.
*/
public final class EventBus
{
/** Failures after which a listener is removed. */
static final int MAX_FAILURES = 10;
private final Map<Class<?>, Listener[]> listeners = new ConcurrentHashMap<>();
private volatile boolean closed;
/** Registration for one mod; its listeners are tagged with {@code id}. */
public Events forMod(String id, Executor modThread, System.Logger logger) { return new ModEvents(id, modThread, logger); }
/** Whether any listener is registered for exactly this class. */
public boolean hasListeners(Class<? extends Event> type) { return this.listeners.containsKey(type); }
/**
* Delivers {@code event}: main listeners run now, on the calling thread, which must be the
* main thread; mod-thread listeners get a task on their mod's thread. A listener's exception
* is logged and never reaches the caller.
*/
public void post(Event event)
{
if (this.closed) return;
Listener[] listeners = this.listeners.get(event.getClass());
if (listeners == null) return;
for (Listener listener : listeners) listener.deliver(event);
}
/** Stops delivering events. */
public void close() { this.closed = true; }
private synchronized void add(Listener listener)
{
Listener[] current = this.listeners.getOrDefault(listener.type, new Listener[0]);
Listener[] updated = Arrays.copyOf(current, current.length + 1);
updated[current.length] = listener;
this.listeners.put(listener.type, updated);
}
private synchronized void remove(Listener listener)
{
Listener[] current = this.listeners.get(listener.type);
if (current == null) return;
Listener[] updated = Arrays.stream(current).filter(other -> other != listener).toArray(Listener[]::new);
if (updated.length == 0) this.listeners.remove(listener.type);
else this.listeners.put(listener.type, updated);
}
private final class ModEvents implements Events
{
private final String id;
private final Executor modThread;
private final System.Logger logger;
private ModEvents(String id, Executor modThread, System.Logger logger)
{
this.id = id;
this.modThread = modThread;
this.logger = logger;
}
@Override
public <E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener) { return this.register(type, listener, null); }
@Override
public <E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener)
{
if (MainThreadEvent.class.isAssignableFrom(type))
throw new IllegalArgumentException("'" + type.getName() + "' is a main-thread event; listen with onMain().");
return this.register(type, listener, this.modThread);
}
private <E extends Event> Subscription register(Class<E> type, Consumer<? super E> listener, @Nullable Executor executor)
{
Objects.requireNonNull(type, "type");
Objects.requireNonNull(listener, "listener");
Listener registered = new Listener(this.id, type, event -> listener.accept(type.cast(event)), executor, this.logger);
EventBus.this.add(registered);
return registered;
}
}
private final class Listener implements Subscription
{
private final String mod;
private final Class<?> type;
private final String kind;
private final Consumer<Object> action;
private final @Nullable Executor executor;
private final System.Logger logger;
private final AtomicInteger failures = new AtomicInteger();
private volatile boolean active = true;
private Listener(String mod, Class<?> type, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
{
this.mod = mod;
this.type = type;
this.kind = "listener " + type.getSimpleName();
this.action = action;
this.executor = executor;
this.logger = logger;
}
@Override
public void cancel()
{
this.active = false;
EventBus.this.remove(this);
}
private void deliver(Event event)
{
if (!this.active) return;
if (this.executor == null) {
this.invoke(event);
return;
}
try { this.executor.execute(() -> this.invoke(event)); }
catch (RejectedExecutionException e) { /* the mod's thread has been shut down */ }
}
private void invoke(Event event)
{
if (!this.active) return;
Throwable failure = ModTaskEvent.run(this.mod, this.kind, () -> this.action.accept(event));
if (failure == null) return;
int count = this.failures.incrementAndGet();
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure);
if (count >= EventBus.MAX_FAILURES)
{
this.cancel();
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' removed after " + EventBus.MAX_FAILURES + " failures.");
}
}
}
}
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more