35 Commits
Author SHA1 Message Date
Overlord 07dc3f0fad Add BackupHooks and ParallelZip for Build 42.21. Implement optimized backup file creation with parallel processing. Include hooks, utilities, and unit tests for validation.
ci / image (42, public) (push) Successful in 3m38s
2026-10-05 13:38:08 +02:00
Overlord 7ffcbdbb06 Add @SuppressWarnings("unused") to hooks. 2026-10-05 12:25:37 +02:00
Overlord 9b721bfd45 Refactor Patches package to patches for consistency across project structure. Update imports in all related classes and tests. 2026-10-05 12:23:50 +02:00
Overlord 88cd68b5cb Add ThreadSleepPerformancePatch variants for Build 42.21 to optimize waiting loops. Replace Thread.sleep calls with hook-based alternatives. Include hooks, utility and tests. 2026-10-05 12:22:38 +02:00
Overlord 529e48ed5a Add RolesSavePerformancePatch to optimize role saving in Build 42.21. Use single SQLite transaction to reduce redundant database operations. Include hooks, tests, and integrate the patch into the performance patch set. 2026-10-05 11:24:59 +02:00
Overlord dd113961e6 Add IsoChunkSaveDirectoryPerformancePatch to remove redundant folder checks during chunk saves in Build 42.21. Include tests and integrate the patch into the performance patch set. 2026-10-05 01:20:10 +02:00
Overlord eb09a77941 Add BitHeaderPoolPerformancePatch for chunk serialization improvements in Build 42.21. Introduce PerThreadDeque for thread-local pooling with reduced contention and memory overhead. Include unit tests and integrate patch into the performance patch set. 2026-10-05 00:47:01 +02:00
Overlord 2081235433 Add MethodBody implementation for method delegation and TileRules utility for optimised tile rule matching and caching. Include patches for WorldGenChunk performance and corresponding tests. 2026-10-04 23:19:08 +02:00
Overlord e932c7401a qol: fix formatting 2026-10-04 20:16:59 +02:00
Overlord 56e01c5cbe Introduce FrameBudget utility and ServerMapCellBudgetPerformancePatch for frame-based workload distribution. 2026-10-04 20:16:38 +02:00
Overlord 38a15db299 Add performance improvements for ZomboidFileSystem.init: implement MediaScan and ZomboidFileSystemHooks for efficient file system traversal, and replace directory checks with a single-pass approach. Integrate new patch into the performance patch set, and include unit tests for behavior validation. 2026-10-04 19:34:09 +02:00
Overlord 05a4b9dbd9 Moved VoronoiNoise and its tests to vanilla package for improved organisation. 2026-10-04 19:30:37 +02:00
Overlord 900f65b591 Optimize ZombieVoronoi.evaluateNoise with a hook-based implementation for Build 42.21. Replace distance calculations with a single-pass method, avoiding boxed sorting. Add associated tests and integrate new patch into the performance patch set. 2026-10-04 16:45:31 +02:00
Overlord 05eed7e205 Updated server configuration; add UPnP and JVM memory options, and enhance startup behaviour with dynamic memory allocation and ZUncommitDelay settings. 2026-10-04 15:17:38 +02:00
Overlord 151e1d459f Merge tag 'v0.4.0' into develop
ci / image (42, public) (push) Successful in 3m13s
Tagging version v0.4.0 v0.4.0
2026-10-03 13:40:26 +02:00
Overlord a0cd30a0d7 Merge branch 'release/v0.4.0'
publish / maven (push) Successful in 2m59s
ci / image (42, public) (push) Successful in 16s
2026-10-03 13:40:26 +02:00
Overlord a351fc237c Add client command integration for Build 42: define APIs, event system, hooks, patches, and Lua table converters. Include tests, documentation, and mod support. 2026-10-03 13:22:47 +02:00
Overlord af7174e128 Add mod command integration for Build 42: command hooks, lookup extensions, registry, and validation mechanisms. Include corresponding tests and documentation. 2026-10-03 11:27:06 +02:00
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 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 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 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 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
230 changed files with 20265 additions and 286 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/
+3 -3
View File
@@ -15,12 +15,12 @@ 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: with:
# release.sh derives the version from the newest v* tag # release.sh derives the version from the v* tags
fetch-depth: 0 fetch-depth: 0
- name: Build and verify - name: Build and verify
+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
+15 -6
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,13 +20,13 @@ 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: with:
# release.sh derives the version from the newest v* tag # release.sh derives the version from the v* tags
fetch-depth: 0 fetch-depth: 0
- name: Log in to the registry - name: Log in to the registry
@@ -39,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/
+49 -9
View File
@@ -6,6 +6,10 @@
# 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
@@ -14,7 +18,8 @@
# files with steamcmd's newer copies # files with steamcmd's newer copies
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh. # FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
# Default: 0.0.0-prerelease # Default: 0.0.0-prerelease
# STEAM_BUILDID Image label only; set by ci/release.sh # 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 # DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
# (debug builds only; ci/release.sh never sets it) # (debug builds only; ci/release.sh never sets it)
@@ -24,8 +29,11 @@ ARG STEAMCLIENT=bundled
ARG FORGE_VERSION="0.0.0-prerelease" 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.
@@ -36,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.
@@ -51,6 +59,37 @@ 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. FORGE_VERSION always has a # An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
@@ -63,10 +102,10 @@ RUN ./gradlew --no-daemon \
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \ ${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \ ${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \ ${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
build :patcher:patchServerJar 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.
@@ -76,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
+416
View File
@@ -0,0 +1,416 @@
# 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, and 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` |
| `commands()` | `Commands` | admin commands for chat, the server console, and RCON |
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
## 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.
## Commands
Admin commands work wherever Project Zomboid's own commands work: in the in-game chat
(`/zfhello`), the server console, and RCON. They use Project Zomboid's command framework, so the
mod declares `game` versions. In Build 42 a command is a subclass of
`zombie.commands.CommandBase`:
```java
@CommandName(name = "zfhello")
@CommandArgs(optional = "(.+)")
@CommandHelp(helpText = "zfhello [name]: greets", shouldTranslated = false)
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
public class HelloCommand extends CommandBase
{
public HelloCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
@Override
protected String Command()
{
String name = this.getCommandArg(0);
return "Hello " + (name == null ? this.getExecutorUsername() : name);
}
}
```
```java
@Override
public void onLoad() { this.commands().register(HelloCommand.class); }
```
- **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw.
`register` checks the class and throws `IllegalArgumentException` listing every problem,
which stops the server like any other exception in `onLoad()`.
- **The class** is public and not abstract, with one public constructor
`(String, Role, String, UdpConnection)`.
- **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and
differ, ignoring case, from the names of Project Zomboid's commands and other mods' commands.
A name matches when it is the first word of the input, ignoring case.
- **`@RequiredCapability`** is required: Project Zomboid refuses to run a command without one.
RCON and the server console run commands with the default admin role.
- **`@CommandArgs`** (regular expressions for the arguments; the capture groups become
`getCommandArg(n)`) and **`@CommandHelp`** (`help zfhello` and the `help` list; with
`shouldTranslated = false` the text is used as written) are optional.
- **`Command()`** runs on the main thread, for every use on a new instance; its return value
is the reply. Long work belongs on `modThread()` or `async()`; the reply then only confirms
that the work started.
- Project Zomboid's commands are looked up first; mods' commands follow in load order.
## Client commands
A Java mod on the server and a Lua mod on the client (for example from the Workshop) talk
through Project Zomboid's command channel, so players keep the official client.
Client to server: the Lua mod calls `sendClientCommand`, and the server posts
`ClientCommandEvent` on the main thread.
```lua
sendClientCommand(getPlayer(), "Shop", "buy", { item = "Base.Axe", count = 2 })
```
```java
this.events().onMain(ClientCommandEvent.class, event ->
{
if (!event.module().equals("Shop")) return;
event.cancel(); // Lua's OnClientCommand does not see it
String item = (String) event.args().get("item");
int count = ((Double) event.args().get("count")).intValue();
// ...
this.clientCommands().send(event.player(), "Shop", "bought", Map.of("item", item, "count", count));
});
```
Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod
receives them in `Events.OnServerCommand`.
```lua
Events.OnServerCommand.Add(function(module, command, args)
if module == "Shop" and command == "bought" then print(args.item, args.count) end
end)
```
- **Every** client command is posted, including those of Project Zomboid (`vehicle`,
`player`, ...) and of other mods; filter by `module()`. The event is a `MainThreadEvent`.
- **`cancel()`** stops Project Zomboid from passing the command to Lua's `OnClientCommand`.
Every listener still runs; `isCancelled()` tells whether another one cancelled.
- **`args()`** is the Lua table as an unmodifiable map: keys are `String` or `Double` (Lua
arrays have the keys `1.0`, `2.0`, ...); values are `String`, `Double` (every Lua number),
`Boolean`, nested maps, or game objects (inventory items, directions, dead bodies). It is
empty when the client sent no table.
- **`player()`** is a `PlayerRef` (online id and username), a value that stays valid on other
threads and after the player left. Sending to a player who left sends nothing.
- **Sending** works from any thread. The arguments are copied and checked at once
(`IllegalArgumentException` for unsupported types, `null`, or cycles); numbers become Lua
numbers, lists become Lua arrays. The command is sent on the main thread: at once when
called there, otherwise as one of the mod's queued main-thread tasks.
- Client commands come from players and can be forged by a modified client. Check every
argument and the player's rights before acting on it.
## 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).
+106 -32
View File
@@ -14,16 +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 | | `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` | | `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), > [!NOTE]
`<forge>-pz<pz>`, and `latest`. > Published images are tagged `<forge>-pz<major.minor.build>`, `<forge>-pz<major.minor>`, and `latest`. <br>
> A new image is built for every ZomboidForge release and every Project Zomboid version,
> hotfixes included, as the server only admits client with the exact same version.
## Running ## Running
@@ -36,24 +38,26 @@ 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 | | `UPNP` | | `true`/`false`: UPnP port mapping on the router (`.ini` `UPnP`); `false` recommended (see below) |
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards | | `ADMIN_USERNAME` | `admin` | First start only |
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` | | `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` | | `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` | | `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it | | `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
| `JVM_MIN_HEAP` | | `-Xms` | | `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
| `JVM_MAX_HEAP` | `8g` | `-Xmx` | | `JVM_MIN_HEAP` | JVM default | `-Xms`; unused heap memory is returned to the system only down to this size |
| `STEAM` | `1` | `0` runs the server without Steam | | `JVM_MAX_HEAP` | 75 % of the memory limit | `-Xmx`; `8g` when the container has no memory limit |
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards | | `JVM_UNCOMMIT_DELAY` | `60` | Seconds after which unused heap memory is returned to the system (`-XX:ZUncommitDelay`) |
| `STEAM` | `1` | `0` runs the server without Steam |
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
Notes: Notes:
@@ -64,10 +68,74 @@ Notes:
items (`/data/steamapps`). The server runs as UID 1000. A bind-mounted host directory items (`/data/steamapps`). The server runs as UID 1000. A bind-mounted host directory
must be writable by UID 1000 (`chown 1000:1000 <dir>`); with rootless Podman, use must be writable by UID 1000 (`chown 1000:1000 <dir>`); with rootless Podman, use
`--userns=keep-id:uid=1000,gid=1000` to map it to your own user. `--userns=keep-id:uid=1000,gid=1000` to map it to your own user.
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large - **UPnP:** the game enables UPnP by default. In a container the server sees only its own
worlds (`podman stop -t 120`, `stop_grace_period` in compose). container address and cannot map the host's ports, and the router search delays every start
by about 12 s; set `UPNP=false` and publish the ports instead.
- **Memory:** with a memory limit (`--memory`, `mem_limit`), the heap gets 75 % of it and the
rest stays for native memory. The startup briefly needs a large heap; with 8 players
exploring, the heap held up to 4.4 GB of live data in tests. A limit below about 6 GB is
not recommended. Without a limit the heap is `8g`, as in vanilla.
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large worlds.
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`). For local testing use `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
```
> [!WARNING]
> Mods are trusted code. <br>
> They run inside the server process with its full privileges, which means they can
> read and write any file the server can, open network connections, and stop the server. <br>
> The class loader isolation and the startup checks catch mistakes; they do not contain
> or restrict a malicious mod.
>
> Install only mods whose authors you trust, or whose code you can verify yourself!
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. For example, 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
@@ -79,5 +147,11 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
./gradlew :patcher:patchServerJar # -> patcher/build/server/projectzomboid.jar ./gradlew :patcher:patchServerJar # -> patcher/build/server/projectzomboid.jar
``` ```
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent. > [!IMPORTANT]
`pz.version` in `gradle.properties` selects the targeted version. > Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent. <br>
> `pz.version` in `gradle.properties` selects the targeted version. <br>
> `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
} }
+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,14 @@
package dev.overlord.zomboidforge.api;
/**
* An event whose default action, what Project Zomboid does after the event, can be prevented.
* Only listeners on the main thread can cancel: the default action runs once every main-thread
* listener returned. Every listener is called, also after one cancelled.
*/
public interface Cancellable
{
/** Prevents the default action. */
void cancel();
boolean isCancelled();
}
@@ -0,0 +1,55 @@
package dev.overlord.zomboidforge.api;
import java.util.Map;
import java.util.Objects;
/**
* A client command arrived: a client called Lua's {@code sendClientCommand(module, command, args)}.
* Posted on the main thread for every client command, including those of Project Zomboid and of
* Lua mods, so listeners filter by {@link #module()}.
*
* <p>Default action: Project Zomboid passes the command to Lua's {@code Events.OnClientCommand}.
* {@link #cancel()} prevents that, for example when a Java mod handles the module itself.
*
* <p>{@link #args()} is the Lua table converted to Java: keys are {@code String} or
* {@code Double} (Lua arrays have the keys {@code 1.0}, {@code 2.0}, ...), values are
* {@code String}, {@code Double}, {@code Boolean}, a nested {@code Map} of the same kind, or a
* game object that Project Zomboid sends with commands (in Build 42 an inventory item, an
* {@code IsoDirections}, or a dead body). The maps cannot be modified.
*/
public final class ClientCommandEvent implements MainThreadEvent, Cancellable
{
private final PlayerRef player;
private final String module;
private final String command;
private final Map<Object, Object> args;
private boolean cancelled;
/** @param args the converted arguments; empty when the client sent none */
public ClientCommandEvent(PlayerRef player, String module, String command, Map<Object, Object> args)
{
this.player = Objects.requireNonNull(player, "player");
this.module = Objects.requireNonNull(module, "module");
this.command = Objects.requireNonNull(command, "command");
this.args = Objects.requireNonNull(args, "args");
}
/** The player who sent the command. */
public PlayerRef player() { return this.player; }
public String module() { return this.module; }
public String command() { return this.command; }
public Map<Object, Object> args() { return this.args; }
@Override
public void cancel() { this.cancelled = true; }
@Override
public boolean isCancelled() { return this.cancelled; }
@Override
public String toString() { return "ClientCommandEvent[" + this.player + ", " + this.module + "." + this.command + ", " + this.args + (this.cancelled ? ", cancelled" : "") + "]"; }
}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.api;
import java.util.Map;
/**
* Server commands to clients, the reply channel to {@link ClientCommandEvent}: a client receives
* them in Lua's {@code Events.OnServerCommand(module, command, args)}. Together, a Java mod on the
* server and a Lua mod on the client exchange commands while players keep the official client.
*
* <p>{@code args} becomes a Lua table: keys are {@code String} or a {@code Number} (sent as a
* Lua number), values are {@code String}, {@code Number}, {@code Boolean}, a nested {@code Map}, a
* {@code List} (a Lua array, indexed from 1), or a game object that Project Zomboid sends with
* commands (see {@link ClientCommandEvent}). {@code null} keys or values, and cycles, are not
* allowed. An empty map sends no arguments; the client then receives {@code nil}.
*
* <p>The methods can be called on any thread. The arguments are checked at once; the command is
* sent on the main thread, at once when called there, otherwise with the mod's queued
* main-thread tasks.
*/
public interface ClientCommands
{
/**
* Sends a command to {@code player}. Nothing is sent when the player is no longer connected.
*
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
*/
void send(PlayerRef player, String module, String command, Map<?, ?> args);
/**
* Sends a command to every connected client.
*
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
*/
void sendToAll(String module, String command, Map<?, ?> args);
}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.api;
/**
* Registration of admin commands. A registered command works wherever Project Zomboid's own
* admin commands work: in the in-game chat ({@code /name}), the server console, and RCON. It
* is looked up after the commands of Project Zomboid and runs on the main thread.
*
* <p>A command is a class of the running Project Zomboid version's command framework, so a mod
* that registers commands declares {@code game} versions in {@code mod.toml}. In Build 42 it is
* a public, non-abstract subclass of {@code zombie.commands.CommandBase} with:
* <ul>
* <li>one public constructor {@code (String username, Role role, String command, UdpConnection connection)},
* which passes its arguments to {@code super};</li>
* <li>at least one {@code @CommandName}; names consist of letters, digits, and {@code _}, and
* differ (ignoring case) from every name of Project Zomboid and of other mods;</li>
* <li>at least one {@code @RequiredCapability}; Project Zomboid refuses to run a command
* without one;</li>
* <li>optionally {@code @CommandArgs} (argument patterns) and {@code @CommandHelp}
* ({@code help <name>} and the {@code help} list).</li>
* </ul>
* Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose
* result is the reply.
*/
public interface Commands
{
/**
* Registers {@code command}. Only on the main thread while the mod loads: in the entry point's
* constructor or {@link Mod#onLoad()}.
*
* @throws IllegalArgumentException when {@code command} does not meet the rules above, or is
* registered already
* @throws IllegalStateException when called later or on another thread
*/
void register(Class<?> command);
}
@@ -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,93 @@
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(); }
/** Admin command registration. */
protected final Commands commands() { return this.context.commands(); }
/** Server commands to clients, received by their Lua mods. */
protected final ClientCommands clientCommands() { return this.context.clientCommands(); }
}
@@ -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,51 @@
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();
/** Admin command registration. */
Commands commands();
/** Server commands to clients, received by their Lua mods. */
ClientCommands clientCommands();
}
@@ -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,19 @@
package dev.overlord.zomboidforge.api;
import java.util.Objects;
/**
* A connected player, by value: usable on any thread and after the player left. Project
* Zomboid reuses online ids of players who left, so ZomboidForge matches both the id and the
* username before it acts on a player.
*
* @param onlineId the player's online id while connected
* @param username the player's account name
*/
public record PlayerRef(int onlineId, String username)
{
public PlayerRef
{
Objects.requireNonNull(username, "username");
}
}
@@ -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,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));
@@ -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 "$@"
+61 -26
View File
@@ -1,22 +1,29 @@
#!/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
# #
# <forge> is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0). # <major.minor.build> is the version the branch's server jar reports, read before the full
# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never # build (Dockerfile stage game-version, which downloads only the jar).
# published. Without any v* tag the version is "0.0.0-prerelease".
# #
# Nothing is built when the immutable tag already exists in the registry. # <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).
# Default: pz.version in gradle.properties
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only) # 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
@@ -63,12 +70,15 @@ gradle_property() {
exit 1 exit 1
} }
# Prints the forge version: the newest v* tag reachable from HEAD without its "v", # Prints the forge version without the "v": the v* tag on HEAD, else the git describe version
# or nothing when the repository has no such tag. # 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() { release_tag_version() {
local tag local tag
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then 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}" echo "${tag#v}"
fi fi
} }
@@ -78,6 +88,22 @@ image_exists() {
"$(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"
@@ -119,8 +145,9 @@ push_as() {
main() { main() {
local forge_version local forge_version
local publish="${REQUESTED_PUBLISH}" local publish="${REQUESTED_PUBLISH}"
local pz_version local pz_prefix
local build_id local build_id
local game_version
forge_version="$(release_tag_version)" forge_version="$(release_tag_version)"
if [[ -z "${forge_version}" ]]; then if [[ -z "${forge_version}" ]]; then
@@ -132,31 +159,39 @@ main() {
log "${forge_version} is a pre-release version; nothing will be published." log "${forge_version} is a pre-release version; nothing will be published."
fi fi
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}" 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} (not published)" 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"
+1
View File
@@ -5,6 +5,7 @@ plugins {
} }
dependencies { dependencies {
implementation(project(":api"))
implementation(project(":patcher")) implementation(project(":patcher"))
implementation(libs.bundles.asm) implementation(libs.bundles.asm)
@@ -1,10 +1,7 @@
package dev.overlord.zomboidforge.compat.b42; package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.compat.b42.patches.ServerStartedPatch; import dev.overlord.zomboidforge.compat.b42.patches.*;
import dev.overlord.zomboidforge.compat.b42.perf.IsoGameCharacterStateMachinePerformancePatch; import dev.overlord.zomboidforge.compat.b42.perf.*;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieNetworkComponentPerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieSpotChancePerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieVehiclePerformancePatch;
import dev.overlord.zomboidforge.patcher.ClassPatch; import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.PatchSet; import dev.overlord.zomboidforge.patcher.PatchSet;
@@ -16,11 +13,32 @@ import java.util.List;
public final class B42PatchSet implements PatchSet public final class B42PatchSet implements PatchSet
{ {
private static final List<ClassPatch> PATCHES = List.of( private static final List<ClassPatch> PATCHES = List.of(
new ServerLoadPatch(),
new ServerStartedPatch(), new ServerStartedPatch(),
new ServerTickPatch(),
new ServerStoppingPatch(),
new ZipBackupSinglePassPerformancePatch(),
new BackupStoragePatch(),
new CommandLookupPatch(),
new CommandListPatch(),
new ClientCommandPatch(),
new IsoZombieVehiclePerformancePatch(), new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(), new IsoZombieSpotChancePerformancePatch(),
new IsoGameCharacterStateMachinePerformancePatch() new IsoGameCharacterStateMachinePerformancePatch(),
new ZombieVoronoiPerformancePatch(),
new ZomboidFileSystemInitPerformancePatch(),
new ServerMapCellBudgetPerformancePatch(),
new WorldGenUtilsPlacementPerformancePatch(),
new WorldGenChunkRulesPerformancePatch(),
new BitHeaderPoolPerformancePatch(),
new IsoChunkSaveDirectoryPerformancePatch(),
new RolesSavePerformancePatch(),
new ServerChunkLoaderQuitPerformancePatch(),
new ZipBackupWaitPerformancePatch(),
new ServerPlayersVehiclesRoundPerformancePatch(),
new ServerPlayersVehiclesStopPerformancePatch(),
new ServerPlayerDBSaveWaitPerformancePatch()
); );
@Override @Override
@@ -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,43 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.HookArgument;
import dev.overlord.zomboidforge.patcher.patches.CancellableHookPatch;
import java.util.List;
/**
* Makes the Lua event {@code OnClientCommand} in {@code GameServer.receiveClientCommand} depend on
* {@code ClientCommandHooks.onClientCommand(module, command, player, tbl)}:
*
* <pre>{@code
* if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
* LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
* }</pre>
*
* The arguments are the method's local variables of these names.
*/
public final class ClientCommandPatch extends CancellableHookPatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("receiveClientCommand", "(Lzombie/core/network/ByteBufferReader;Lzombie/core/raknet/UdpConnection;S)V"),
"zombie/Lua/LuaEventManager", "triggerEvent", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks", "onClientCommand",
"(Ljava/lang/String;Ljava/lang/String;Lzombie/characters/IsoPlayer;Lse/krka/kahlua/vm/KahluaTable;)Z"
);
private static final List<HookArgument> ARGUMENTS = List.of(
new HookArgument.Local("module"),
new HookArgument.Local("command"),
new HookArgument.Local("player"),
new HookArgument.Local("tbl")
);
public ClientCommandPatch() {
super("zombie/network/GameServer", ClientCommandPatch.ANCHOR, ClientCommandPatch.HOOK, ClientCommandPatch.ARGUMENTS);
}
}
@@ -0,0 +1,32 @@
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.ReturnHookPatch;
import org.objectweb.asm.Opcodes;
import java.util.List;
/**
* Makes {@code CommandBase.getSubClasses()} return
* {@code CommandHooks.listCommands(childrenClasses)}: Project Zomboid's command classes followed
* by the mods'. The {@code help} command lists commands through this method.
*/
public final class CommandListPatch extends ReturnHookPatch
{
/** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"),
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "listCommands", "([Ljava/lang/Class;)[Ljava/lang/Class;"
);
public CommandListPatch() {
super("zombie/commands/CommandBase", CommandListPatch.ANCHOR, CommandListPatch.HOOK, List.of());
}
}
@@ -0,0 +1,33 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.HookArgument;
import dev.overlord.zomboidforge.patcher.patches.ReturnHookPatch;
import org.objectweb.asm.Opcodes;
import java.util.List;
/**
* Makes {@code CommandBase.findCommandCls(command)} return
* {@code CommandHooks.findCommand(null, command)} where it returns {@code null}: when no command
* of Project Zomboid matches, the mods' commands are searched. The server console, RCON, chat
* commands, and {@code help <name>} look commands up through this method.
*/
public final class CommandLookupPatch extends ReturnHookPatch
{
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
new Anchor.Method("findCommandCls", "(Ljava/lang/String;)Ljava/lang/Class;"),
new Anchor.Instruction.Opcode(Opcodes.ACONST_NULL),
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "findCommand", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Class;"
);
public CommandLookupPatch() {
super("zombie/commands/CommandBase", CommandLookupPatch.ANCHOR, CommandLookupPatch.HOOK, List.of(new HookArgument.Parameter(0)));
}
}
@@ -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;
}
}
@@ -2,7 +2,7 @@ package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor; import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook; import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch; import dev.overlord.zomboidforge.patcher.patches.HookInjectionPatch;
/** /**
* Calls {@code ServerHooks.onServerStarted()} in {@code GameServer.main}, directly after * Calls {@code ServerHooks.onServerStarted()} in {@code GameServer.main}, directly after
@@ -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,93 @@
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.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Creates the four header pools of {@code zombie.util.io.BitHeader} as {@code PerThreadDeque}s
* instead of {@code ConcurrentLinkedDeque}s:
*
* <pre>{@code
* // and short, int, long
* private static final ConcurrentLinkedDeque pool_byte = new PerThreadDeque();
* }</pre>
*
* Every square and object a chunk save writes takes a header from a pool and returns it, from the
* save worker threads at once; the shared deques were about a third of chunk serialization.
* {@code PerThreadDeque} answers {@code poll}, {@code offer} and {@code size}, the only methods
* {@code BitHeader} calls on the pools, from a pool per thread. A header is reset when it is
* returned and gets its buffer and mode when it is taken, so which header a thread gets does not
* change what is written.
*/
public final class BitHeaderPoolPerformancePatch extends PerformancePatch
{
private static final String DEQUE = "java/util/concurrent/ConcurrentLinkedDeque";
private static final String POOL = "dev/overlord/zomboidforge/compat/b42/util/PerThreadDeque";
private static final Set<String> POOL_FIELDS = Set.of("pool_byte", "pool_short", "pool_int", "pool_long");
private static final Anchor.Method ANCHOR = new Anchor.Method("<clinit>", "()V");
public BitHeaderPoolPerformancePatch() {
super("zombie/util/io/BitHeader", BitHeaderPoolPerformancePatch.ANCHOR, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = BitHeaderPoolPerformancePatch.ANCHOR.resolve(node);
Set<String> replaced = new TreeSet<>();
for (AbstractInsnNode instruction : method.instructions)
{
if (!(instruction instanceof TypeInsnNode creation) || creation.getOpcode() != Opcodes.NEW || !creation.desc.equals(BitHeaderPoolPerformancePatch.DEQUE)) continue;
// new ConcurrentLinkedDeque; dup; invokespecial <init>()V; putstatic pool_*
List<AbstractInsnNode> next = BitHeaderPoolPerformancePatch.following(creation, 3);
if (!(next.get(1) instanceof MethodInsnNode constructor) || constructor.getOpcode() != Opcodes.INVOKESPECIAL || !constructor.owner.equals(BitHeaderPoolPerformancePatch.DEQUE) || !constructor.desc.equals("()V"))
throw new IllegalStateException("'" + node.name + ".<clinit>': a 'ConcurrentLinkedDeque' is not created with its no-argument constructor.");
if (!(next.get(2) instanceof FieldInsnNode store) || store.getOpcode() != Opcodes.PUTSTATIC || !BitHeaderPoolPerformancePatch.POOL_FIELDS.contains(store.name))
throw new IllegalStateException("'" + node.name + ".<clinit>': a 'ConcurrentLinkedDeque' is created for something other than a header pool.");
creation.desc = BitHeaderPoolPerformancePatch.POOL;
constructor.owner = BitHeaderPoolPerformancePatch.POOL;
replaced.add(store.name);
}
if (!replaced.equals(BitHeaderPoolPerformancePatch.POOL_FIELDS))
throw new IllegalStateException("'" + node.name + ".<clinit>' creates the pools " + replaced + ", expected " + new TreeSet<>(BitHeaderPoolPerformancePatch.POOL_FIELDS) + ".");
}
/** The {@code count} real instructions after {@code instruction}: no labels, line numbers, or frames. */
private static List<AbstractInsnNode> following(AbstractInsnNode instruction, int count)
{
List<AbstractInsnNode> following = new ArrayList<>();
for (AbstractInsnNode next = instruction.getNext(); next != null && following.size() < count; next = next.getNext()) {
if (next.getOpcode() != -1) following.add(next);
}
if (following.size() < count) throw new IllegalStateException("'BitHeader.<clinit>' ends after a 'new ConcurrentLinkedDeque'.");
return following;
}
}
@@ -0,0 +1,85 @@
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.JumpInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.List;
/**
* Removes the folder check before every chunk save in {@code IsoChunk.Save(boolean)}:
*
* <pre>{@code
* File testDir = ChunkMapFilenames.instance.getDir(Core.gameSaveWorld);
* if (!testDir.exists()) { // removed
* testDir.mkdir();
* }
* }</pre>
*
* {@code getDir} returns {@code <cache>/map/<world>}, which nothing reads or writes; chunk files
* are saved under {@code <cache>/<world>/map/<x>/}, whose folders {@code getFilename} creates.
* {@code <cache>/map} does not exist, so the {@code mkdir} fails on every save: one {@code stat}
* and one failed {@code mkdir} per chunk. The {@code getDir} call stays; it initializes the cache
* folder of {@code ChunkMapFilenames} on first use.
*/
public final class IsoChunkSaveDirectoryPerformancePatch extends PerformancePatch
{
/** {@code testDir = ...getDir(world); if (!testDir.exists()) testDir.mkdir();} */
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
new Anchor.Method("Save", "(Z)V"),
new Anchor.Instruction.Invoke("zombie/ChunkMapFilenames", "getDir", "(Ljava/lang/String;)Ljava/io/File;"),
new Anchor.Instruction.Opcode(Opcodes.ASTORE),
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
new Anchor.Instruction.Invoke("java/io/File", "exists", "()Z"),
new Anchor.Instruction.Opcode(Opcodes.IFNE),
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
new Anchor.Instruction.Invoke("java/io/File", "mkdir", "()Z"),
new Anchor.Instruction.Opcode(Opcodes.POP)
);
public IsoChunkSaveDirectoryPerformancePatch() {
super("zombie/iso/IsoChunk", IsoChunkSaveDirectoryPerformancePatch.ANCHOR, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoChunkSaveDirectoryPerformancePatch.ANCHOR.in().resolve(node);
List<AbstractInsnNode> matched = IsoChunkSaveDirectoryPerformancePatch.ANCHOR.resolve(node);
int testDir = ((VarInsnNode) matched.get(1)).var;
JumpInsnNode skip = (JumpInsnNode) matched.get(4);
if (((VarInsnNode) matched.get(2)).var != testDir || ((VarInsnNode) matched.get(5)).var != testDir)
throw new IllegalStateException("'" + node.name + ".Save': the check does not use the folder that 'getDir' returned.");
if (IsoChunkSaveDirectoryPerformancePatch.nextInstruction(skip.label) != IsoChunkSaveDirectoryPerformancePatch.nextInstruction(matched.getLast()))
throw new IllegalStateException("'" + node.name + ".Save': the folder check does not jump to the end of its block.");
// The if-block: from loading testDir for exists() to the pop after mkdir(). Labels stay,
// so the jump target and the local variable table remain valid.
for (AbstractInsnNode instruction : matched.subList(2, matched.size())) method.instructions.remove(instruction);
}
/** 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("'IsoChunk.Save' ends after the folder check.");
return next;
}
}
@@ -1,8 +1,8 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor; import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion; import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
@@ -1,8 +1,8 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor; import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion; import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -1,8 +1,8 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor; import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion; import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.AbstractInsnNode;
@@ -1,9 +1,9 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.patcher.Anchor; import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Hook; import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch; import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
@@ -0,0 +1,58 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Saves the roles in one SQLite transaction. {@code Roles.save()} is renamed to
* {@code zomboidForge$save} and wrapped:
*
* <pre>{@code
* public static void save()
* {
* RolesHooks.beginSave();
* try { zomboidForge$save(); }
* finally { RolesHooks.endSave(); }
* }
* }</pre>
*
* The vanilla method writes every role and capability with its own autocommitted statement
* ({@code ServerWorldDatabase.saveRole}, {@code saveDefaultRole}): about 250 transactions and
* 1,000 {@code fsync}s, 1.3 s of every shutdown on a fast disk.
*/
public final class RolesSavePerformancePatch extends PerformancePatch
{
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
private static final String RENAMED = "zomboidForge$save";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("save", "()V"),
"zombie/network/ServerWorldDatabase", "saveRole", "(Lzombie/characters/Role;)V"
);
private static final Hook HOOK = new Hook(RolesSavePerformancePatch.HOOKS, "beginSave", "()V");
private static final Hook END = new Hook(RolesSavePerformancePatch.HOOKS, "endSave", "()V");
public RolesSavePerformancePatch() {
super("zombie/characters/Roles", RolesSavePerformancePatch.ANCHOR, RolesSavePerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode save = RolesSavePerformancePatch.ANCHOR.in().resolve(node);
MethodBody.wrap(node, save, RolesSavePerformancePatch.RENAMED, RolesSavePerformancePatch.HOOK, RolesSavePerformancePatch.END);
}
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ServerChunkLoader.quit()} waits for the chunk loading thread, then for the chunk saving
* thread, each with {@code while (thread.isAlive()) Thread.sleep(500);}: at least 1 s of every
* shutdown although both threads end within milliseconds. The sleeps become
* {@code WaitHooks.pollSleep} (at most 5 ms).
*/
public final class ServerChunkLoaderQuitPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "pollSleep", "(J)V");
public ServerChunkLoaderQuitPerformancePatch() {
super("zombie/network/ServerChunkLoader", new Anchor.Method("quit", "()V"), 2, ServerChunkLoaderQuitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,90 @@
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.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Spreads the integration of finished cells in {@code ServerMap.preupdate} over frames:
*
* <pre>{@code
* // was ServerLOS.instance.suspend()
* ServerMapHooks.beginIntegration(ServerLOS.instance);
*
* for (int x = 0; x < ServerCell.loaded2.size(); ++x)
* {
* ServerCell cell = ServerCell.loaded2.get(x);
*
* if (ServerMapHooks.integrate(cell)) {
* // was cell.Load2()
* --x; this.toLoad.remove(cell);
* }
* }
* }</pre>
*
* Vanilla integrates every cell that finished loading since the last frame (70 to 300 ms each
* on new terrain), so cells that finish together make one long frame. The hooks integrate cells
* until 40 ms are used, at least one per frame; the others stay in {@code loaded2} for the next
* frames. The work per cell is the same; only the frame it runs in changes, which the
* asynchronous loader already varies.
*/
public final class ServerMapCellBudgetPerformancePatch extends PerformancePatch
{
private static final String OWNER = "zombie/network/ServerMap";
private static final String CELL = "zombie/network/ServerMap$ServerCell";
private static final String LOS = "zombie/network/ServerLOS";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ServerMapHooks";
private static final Anchor.Method PREUPDATE = new Anchor.Method("preupdate", "()V");
private static final Anchor.Call ANCHOR = new Anchor.Call(
ServerMapCellBudgetPerformancePatch.PREUPDATE, ServerMapCellBudgetPerformancePatch.CELL, "Load2", "()Z"
);
/** {@code ServerLOS.instance.suspend()} before the integration loop. */
private static final Anchor.Call SUSPEND = new Anchor.Call(
ServerMapCellBudgetPerformancePatch.PREUPDATE, ServerMapCellBudgetPerformancePatch.LOS, "suspend", "()V"
);
private static final Hook HOOK = new Hook(
ServerMapCellBudgetPerformancePatch.HOOKS, "integrate", "(L" + ServerMapCellBudgetPerformancePatch.CELL + ";)Z"
);
private static final Hook BEGIN = new Hook(
ServerMapCellBudgetPerformancePatch.HOOKS, "beginIntegration", "(L" + ServerMapCellBudgetPerformancePatch.LOS + ";)V"
);
public ServerMapCellBudgetPerformancePatch() {
super(ServerMapCellBudgetPerformancePatch.OWNER, ServerMapCellBudgetPerformancePatch.ANCHOR, ServerMapCellBudgetPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ServerMapCellBudgetPerformancePatch.PREUPDATE.resolve(node);
MethodInsnNode load2 = ServerMapCellBudgetPerformancePatch.ANCHOR.resolve(node);
MethodInsnNode suspend = ServerMapCellBudgetPerformancePatch.SUSPEND.resolve(node);
if (method.instructions.indexOf(suspend) > method.instructions.indexOf(load2))
throw new IllegalStateException("'" + node.name + ".preupdate': 'ServerLOS.suspend' comes after 'ServerCell.Load2'.");
// Both hooks take the receiver of the virtual call as their argument: the stack is unchanged.
method.instructions.set(suspend, ServerMapCellBudgetPerformancePatch.call(ServerMapCellBudgetPerformancePatch.BEGIN));
method.instructions.set(load2, ServerMapCellBudgetPerformancePatch.call(ServerMapCellBudgetPerformancePatch.HOOK));
}
private static MethodInsnNode call(Hook hook)
{
return new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false);
}
}
@@ -0,0 +1,27 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ServerPlayerDB.saveFinishWait()} waits until the {@code ServerPlayersVehicles} thread
* has saved the queued players: {@code while (!charactersToSave.isEmpty()) Thread.sleep(100);}.
* The thread saves them at the start of its next round, up to 500 ms later. The sleep becomes
* {@code WaitHooks.wakeVehiclesAndPoll}: it starts that round now
* ({@link ServerPlayersVehiclesRoundPerformancePatch}) and polls every 5 ms.
*/
public final class ServerPlayerDBSaveWaitPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "wakeVehiclesAndPoll", "(J)V");
public ServerPlayerDBSaveWaitPerformancePatch() {
super("zombie/savefile/ServerPlayerDB", new Anchor.Method("saveFinishWait", "()V"), 1, ServerPlayerDBSaveWaitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* The {@code ServerPlayersVehicles} thread saves queued players and streams vehicles, then sleeps
* 500 ms ({@code SPVThread.runInner}). The sleep becomes {@code WaitHooks.vehicleRoundSleep}: the
* same 500 ms, but {@link ServerPlayersVehiclesStopPerformancePatch} and
* {@link ServerPlayerDBSaveWaitPerformancePatch} can end it early.
*/
public final class ServerPlayersVehiclesRoundPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "vehicleRoundSleep", "(J)V");
public ServerPlayersVehiclesRoundPerformancePatch() {
super("zombie/network/ServerPlayersVehicles$SPVThread", new Anchor.Method("runInner", "()V"), 1, ServerPlayersVehiclesRoundPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ServerPlayersVehicles.stop()} sets the thread's stop flag and waits with
* {@code while (thread.isAlive()) Thread.sleep(100);}, while the thread may sleep up to 500 ms
* before it sees the flag. The sleep becomes {@code WaitHooks.wakeVehiclesAndPoll}: it ends the
* thread's round sleep ({@link ServerPlayersVehiclesRoundPerformancePatch}) and polls every 5 ms.
*/
public final class ServerPlayersVehiclesStopPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "wakeVehiclesAndPoll", "(J)V");
public ServerPlayersVehiclesStopPerformancePatch() {
super("zombie/network/ServerPlayersVehicles", new Anchor.Method("stop", "()V"), 1, ServerPlayersVehiclesStopPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,76 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* The tile rules of {@code WorldGenChunk} with cached compiled patterns, like
* {@link WorldGenUtilsPlacementPerformancePatch}:
*
* <ul>
* <li>the body of {@code isProtected(List, String)} becomes
* {@code return WorldGenHooks.isProtected(protectedTiles, tile);}</li>
* <li>in {@code cleanChunk(IsoChunk, String, String)}, {@code floorMaterial.matches(mat)}
* becomes {@code WorldGenHooks.matches(floorMaterial, mat)}.</li>
* </ul>
*/
public final class WorldGenChunkRulesPerformancePatch extends PerformancePatch
{
private static final String STRING = "java/lang/String";
private static final String MATCHES = "(Ljava/lang/String;)Z";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("isProtected", "(Ljava/util/List;Ljava/lang/String;)Z"),
WorldGenChunkRulesPerformancePatch.STRING, "matches", WorldGenChunkRulesPerformancePatch.MATCHES
);
private static final Anchor.Call CLEAN_CHUNK = new Anchor.Call(
new Anchor.Method("cleanChunk", "(Lzombie/iso/IsoChunk;Ljava/lang/String;Ljava/lang/String;)V"),
WorldGenChunkRulesPerformancePatch.STRING, "matches", WorldGenChunkRulesPerformancePatch.MATCHES
);
private static final Hook HOOK = new Hook(
WorldGenChunkRulesPerformancePatch.HOOKS, "isProtected", "(Ljava/util/List;Ljava/lang/String;)Z"
);
private static final Hook MATCHES_HOOK = new Hook(
WorldGenChunkRulesPerformancePatch.HOOKS, "matches", "(Ljava/lang/String;Ljava/lang/String;)Z"
);
public WorldGenChunkRulesPerformancePatch() {
super("zombie/iso/worldgen/WorldGenChunk", WorldGenChunkRulesPerformancePatch.ANCHOR, WorldGenChunkRulesPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode isProtected = WorldGenChunkRulesPerformancePatch.ANCHOR.in().resolve(node);
MethodNode cleanChunk = WorldGenChunkRulesPerformancePatch.CLEAN_CHUNK.in().resolve(node);
MethodInsnNode matches = WorldGenChunkRulesPerformancePatch.CLEAN_CHUNK.resolve(node);
MethodBody.delegate(node, isProtected, WorldGenChunkRulesPerformancePatch.HOOK);
// The hook takes the receiver as its first argument: the stack is unchanged.
cleanChunk.instructions.set(matches, new MethodInsnNode(
Opcodes.INVOKESTATIC,
WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.owner(),
WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.name(),
WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.desc(),
false
));
}
}
@@ -0,0 +1,56 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Replaces the body of {@code WorldGenUtils.canPlace(List, String)} with a call to
* {@code WorldGenHooks.canPlace}, which caches the compiled rules:
*
* <pre>{@code
* public boolean canPlace(List placement, String floorName)
* {
* return WorldGenHooks.canPlace(placement, floorName);
* }
* }</pre>
*
* Vanilla builds and compiles a regular expression per rule per call, for every square of a new
* chunk, on the chunk loader thread. Together with {@link WorldGenChunkRulesPerformancePatch}
* this halves the time to create a new chunk and removes most of the garbage the server
* produces while players explore; {@link ServerMapCellBudgetPerformancePatch} keeps the faster
* cells from bunching up on the main thread.
*/
public final class WorldGenUtilsPlacementPerformancePatch extends PerformancePatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("canPlace", "(Ljava/util/List;Ljava/lang/String;)Z"),
"java/lang/String", "matches", "(Ljava/lang/String;)Z"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks", "canPlace", "(Ljava/util/List;Ljava/lang/String;)Z"
);
public WorldGenUtilsPlacementPerformancePatch() {
super("zombie/iso/worldgen/WorldGenUtils", WorldGenUtilsPlacementPerformancePatch.ANCHOR, WorldGenUtilsPlacementPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = WorldGenUtilsPlacementPerformancePatch.ANCHOR.in().resolve(node);
MethodBody.delegate(node, method, WorldGenUtilsPlacementPerformancePatch.HOOK);
}
}
@@ -0,0 +1,60 @@
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.MethodBody;
import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Replaces the body of {@code ZipBackup.makeBackupFile(String, BackupTypes)} with a call to
* {@code BackupHooks.makeBackupFile}, which writes the same zip in one pass:
*
* <pre>{@code
* private static void makeBackupFile(String serverName, BackupTypes type)
* {
* BackupHooks.makeBackupFile(serverName, type);
* }
* }</pre>
*
* Vanilla's {@code ParallelScatterZipCreator} copies every file into a temporary file per thread
* and then into the zip: about three times the size of the save written per backup. For an
* explored world of 880 MiB in 365,538 files, the startup backup takes 15.2 to 16.8 s and writes
* 2.9 GB; in one pass 7.5 s and 1.0 GB, with the same entries. The save folder is read under
* {@code IsoChunk.WriteLock}, as vanilla; chunk saves wait for it half as long.
*
* <p>Registered before {@code BackupStoragePatch}, which renames this method and wraps it: the
* anchor requires vanilla's body, and the storage hooks stay around the whole backup.
*/
public final class ZipBackupSinglePassPerformancePatch extends PerformancePatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("makeBackupFile", "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V"),
"org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator", "writeTo", "(Lorg/apache/commons/compress/archivers/zip/ZipArchiveOutputStream;)V"
);
// BackupTypes is private: the hook takes it as Object.
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks", "makeBackupFile", "(Ljava/lang/String;Ljava/lang/Object;)V"
);
public ZipBackupSinglePassPerformancePatch() {
super("zombie/core/backup/ZipBackup", ZipBackupSinglePassPerformancePatch.ANCHOR, ZipBackupSinglePassPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ZipBackupSinglePassPerformancePatch.ANCHOR.in().resolve(node);
MethodBody.delegate(node, method, ZipBackupSinglePassPerformancePatch.HOOK);
}
}
@@ -0,0 +1,26 @@
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.ThreadSleepPerformancePatch;
/**
* {@code ZipBackup.waitFinish()}, called at the start of the shutdown, waits for a running
* periodic backup with {@code while (backupThread.isAlive()) Thread.sleep(500);}. The sleep
* becomes {@code WaitHooks.pollSleep} (at most 5 ms), so the shutdown continues when the backup
* ends instead of up to 500 ms later.
*/
public final class ZipBackupWaitPerformancePatch extends ThreadSleepPerformancePatch
{
private static final Hook HOOK = new Hook("dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks", "pollSleep", "(J)V");
public ZipBackupWaitPerformancePatch() {
super("zombie/core/backup/ZipBackup", new Anchor.Method("waitFinish", "()V"), 1, ZipBackupWaitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
}
@@ -0,0 +1,121 @@
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.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* Replaces the body of {@code ZombieVoronoi.evaluateNoise(double, double, Random, List)} with a
* call to {@code ZombieVoronoiHooks.evaluateNoise}, which returns the same values:
*
* <pre>{@code
* private double evaluateNoise(
* double x, double y, Random rng, List<Coord> points
* ) {
* return ZombieVoronoiHooks.evaluateNoise(
* this.closestPoint,
* this.seed,
* this.numberPoints,
* x, y, rng, points
* );
* }
* }</pre>
*
* The world generation evaluates it 1,024 times per cell at startup; each call creates 9
* {@code Coord}s and lets {@code ClosestSelectionType.getClosest} sort their boxed distances.
* The hook computes the distances in one pass.
*/
public final class ZombieVoronoiPerformancePatch extends PerformancePatch
{
private static final String SELECTION = "zombie/iso/worldgen/zombie/ClosestSelection";
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("evaluateNoise", "(DDLjava/util/Random;Ljava/util/List;)D"),
ZombieVoronoiPerformancePatch.SELECTION, "getClosest", "(DDLjava/util/List;)D"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks", "evaluateNoise",
"(L" + ZombieVoronoiPerformancePatch.SELECTION + ";JIDDLjava/util/Random;Ljava/util/List;)D"
);
public ZombieVoronoiPerformancePatch() {
super("zombie/iso/worldgen/zombie/ZombieVoronoi", ZombieVoronoiPerformancePatch.ANCHOR, ZombieVoronoiPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ZombieVoronoiPerformancePatch.ANCHOR.in().resolve(node);
if ((method.access & Opcodes.ACC_STATIC) != 0)
throw new IllegalStateException("'" + node.name + "." + method.name + method.desc + "' is static.");
ZombieVoronoiPerformancePatch.requireField(node, "closestPoint", "L" + ZombieVoronoiPerformancePatch.SELECTION + ";");
ZombieVoronoiPerformancePatch.requireField(node, "seed", "J");
ZombieVoronoiPerformancePatch.requireField(node, "numberPoints", "I");
// The local variable table and annotations refer to labels of the old body.
method.instructions.clear();
method.tryCatchBlocks.clear();
method.localVariables = null;
method.visibleLocalVariableAnnotations = null;
method.invisibleLocalVariableAnnotations = null;
method.instructions.add(ZombieVoronoiPerformancePatch.callHook(node.name));
}
/**
* {@code return hook(this.closestPoint, this.seed, this.numberPoints, x, y, rng, points);}.
* Locals: {@code this} 0, {@code x} 1-2, {@code y} 3-4, {@code rng} 5, {@code points} 6.
*/
private static InsnList callHook(String owner)
{
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "closestPoint", "L" + ZombieVoronoiPerformancePatch.SELECTION + ";"));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "seed", "J"));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "numberPoints", "I"));
code.add(new VarInsnNode(Opcodes.DLOAD, 1));
code.add(new VarInsnNode(Opcodes.DLOAD, 3));
code.add(new VarInsnNode(Opcodes.ALOAD, 5));
code.add(new VarInsnNode(Opcodes.ALOAD, 6));
code.add(new MethodInsnNode(
Opcodes.INVOKESTATIC,
ZombieVoronoiPerformancePatch.HOOK.owner(),
ZombieVoronoiPerformancePatch.HOOK.name(),
ZombieVoronoiPerformancePatch.HOOK.desc(),
false
));
code.add(new InsnNode(Opcodes.DRETURN));
return code;
}
private static void requireField(ClassNode node, String name, String desc)
{
for (FieldNode field : node.fields) {
if (field.name.equals(name) && field.desc.equals(desc) && (field.access & Opcodes.ACC_STATIC) == 0) return;
}
throw new IllegalStateException("Expected the instance field '" + node.name + "." + name + " " + desc + "'.");
}
}
@@ -0,0 +1,119 @@
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.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* Replaces the call {@code this.searchFolders(workdir)} in {@code ZomboidFileSystem.init} with
* {@code ZomboidFileSystemHooks.searchAndIndex}, which also does the work of the loop after it:
*
* <pre>{@code
* ZomboidFileSystemHooks.searchAndIndex(
* this, this.workdir.canonicalFile,
* this.loadList, this.allAbsolutePaths
* );
*
* // loadList is empty now
* for (int n = 0; n < this.loadList.size(); ++n) { ... }
*
* this.loadList.clear();
* }</pre>
*
* Vanilla checks each of the ~39,000 entries under {@code media/} for being a folder twice, and
* builds two URIs per entry for its relative path; the hook walks the folder once.
*/
public final class ZomboidFileSystemInitPerformancePatch extends PerformancePatch
{
private static final String OWNER = "zombie/ZomboidFileSystem";
private static final Anchor.Method INIT = new Anchor.Method("init", "()V");
private static final Anchor.Call ANCHOR = new Anchor.Call(
ZomboidFileSystemInitPerformancePatch.INIT,
ZomboidFileSystemInitPerformancePatch.OWNER, "searchFolders", "(Ljava/io/File;)V"
);
/** The loop the hook takes over: the relative path of each entry. */
private static final Anchor.Call RELATIVE_PATH = new Anchor.Call(
ZomboidFileSystemInitPerformancePatch.INIT,
ZomboidFileSystemInitPerformancePatch.OWNER, "getRelativeFile", "(Ljava/lang/String;)Ljava/lang/String;"
);
/** {@code this.loadList.clear()} after the loop. */
private static final Anchor.Call CLEAR = new Anchor.Call(
ZomboidFileSystemInitPerformancePatch.INIT,
"java/util/List", "clear", "()V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooks", "searchAndIndex",
"(L" + ZomboidFileSystemInitPerformancePatch.OWNER + ";Ljava/io/File;Ljava/util/List;Ljava/util/Set;)V"
);
public ZomboidFileSystemInitPerformancePatch() {
super(ZomboidFileSystemInitPerformancePatch.OWNER, ZomboidFileSystemInitPerformancePatch.ANCHOR, ZomboidFileSystemInitPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ZomboidFileSystemInitPerformancePatch.INIT.resolve(node);
MethodInsnNode call = ZomboidFileSystemInitPerformancePatch.ANCHOR.resolve(node);
ZomboidFileSystemInitPerformancePatch.RELATIVE_PATH.verify(node);
ZomboidFileSystemInitPerformancePatch.CLEAR.verify(node);
ZomboidFileSystemInitPerformancePatch.requireField(node, "loadList", "Ljava/util/List;");
ZomboidFileSystemInitPerformancePatch.requireField(node, "allAbsolutePaths", "Ljava/util/Set;");
int callIndex = method.instructions.indexOf(call);
if (callIndex > method.instructions.indexOf(ZomboidFileSystemInitPerformancePatch.RELATIVE_PATH.resolve(node)))
throw new IllegalStateException("'" + node.name + ".init': 'searchFolders' is called after 'getRelativeFile'.");
// The stack holds this and the folder for the virtual call; the hook takes both, then the two fields.
method.instructions.insertBefore(call, ZomboidFileSystemInitPerformancePatch.loadFields(node.name));
method.instructions.set(call, new MethodInsnNode(
Opcodes.INVOKESTATIC,
ZomboidFileSystemInitPerformancePatch.HOOK.owner(),
ZomboidFileSystemInitPerformancePatch.HOOK.name(),
ZomboidFileSystemInitPerformancePatch.HOOK.desc(),
false
));
}
/** {@code this.loadList, this.allAbsolutePaths}. */
private static InsnList loadFields(String owner)
{
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "loadList", "Ljava/util/List;"));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "allAbsolutePaths", "Ljava/util/Set;"));
return code;
}
private static void requireField(ClassNode node, String name, String desc)
{
for (FieldNode field : node.fields) {
if (field.name.equals(name) && field.desc.equals(desc) && (field.access & Opcodes.ACC_STATIC) == 0) return;
}
throw new IllegalStateException("Expected the instance field '" + node.name + "." + name + " " + desc + "'.");
}
}
@@ -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,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,138 @@
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.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;
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_FINAL;
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.DUP;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
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 BitHeaderPoolPerformancePatchTest
{
private static final String HEADER = "zombie/util/io/BitHeader";
private static final String DEQUE = "java/util/concurrent/ConcurrentLinkedDeque";
private static final String POOL = "dev/overlord/zomboidforge/compat/b42/util/PerThreadDeque";
/** {@code BitHeader} whose {@code <clinit>} creates a deque for each of {@code fields}. */
private static ClassNode bitHeader(List<String> fields)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ACC_FINAL, BitHeaderPoolPerformancePatchTest.HEADER, null, "java/lang/Object", null);
for (String field : fields) node.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, field, "L" + BitHeaderPoolPerformancePatchTest.DEQUE + ";", null, null);
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
for (String field : fields)
{
clinit.visitTypeInsn(NEW, BitHeaderPoolPerformancePatchTest.DEQUE);
clinit.visitInsn(DUP);
clinit.visitMethodInsn(INVOKESPECIAL, BitHeaderPoolPerformancePatchTest.DEQUE, "<init>", "()V", false);
clinit.visitFieldInsn(PUTSTATIC, BitHeaderPoolPerformancePatchTest.HEADER, field, "L" + BitHeaderPoolPerformancePatchTest.DEQUE + ";");
}
clinit.visitInsn(RETURN);
clinit.visitMaxs(0, 0);
return node;
}
private static ClassNode bitHeader()
{
return BitHeaderPoolPerformancePatchTest.bitHeader(List.of("pool_byte", "pool_short", "pool_int", "pool_long"));
}
@Test
void anchorMatchesTheTarget()
{
new BitHeaderPoolPerformancePatch().anchor().verify(BitHeaderPoolPerformancePatchTest.bitHeader());
}
@Test
void createsThePoolsAsPerThreadDeques()
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader();
new BitHeaderPoolPerformancePatch().apply(node);
int creations = 0;
for (AbstractInsnNode instruction : node.methods.getFirst().instructions)
{
if (instruction instanceof TypeInsnNode creation && creation.getOpcode() == NEW)
{
assertEquals(BitHeaderPoolPerformancePatchTest.POOL, creation.desc);
creations++;
}
if (instruction instanceof MethodInsnNode call) assertEquals(BitHeaderPoolPerformancePatchTest.POOL, call.owner);
}
assertEquals(4, creations);
}
@Test
void patchedPoolsAreConcurrentLinkedDeques() throws ReflectiveOperationException
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader();
new BitHeaderPoolPerformancePatch().apply(node);
// Initializing runs <clinit>, which creates the runtime module's PerThreadDeques.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class<?> loaded = Class.forName(node.name.replace('/', '.'), true, definer);
Field pool = loaded.getDeclaredField("pool_int");
pool.setAccessible(true);
Object value = pool.get(null);
assertTrue(value instanceof ConcurrentLinkedDeque<?>);
assertEquals(BitHeaderPoolPerformancePatchTest.POOL.replace('/', '.'), value.getClass().getName());
}
@Test
void failsWhenADequeIsForAnotherField()
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader(List.of("pool_byte", "pool_short", "pool_int", "pool_long", "other"));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BitHeaderPoolPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("other than a header pool"), e.getMessage());
}
@Test
void failsWhenAPoolIsMissing()
{
ClassNode node = BitHeaderPoolPerformancePatchTest.bitHeader(List.of("pool_byte", "pool_short", "pool_int"));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BitHeaderPoolPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("expected [pool_byte, pool_int, pool_long, pool_short]"), e.getMessage());
}
@Test
void appliesOnlyToVerifiedVersions()
{
BitHeaderPoolPerformancePatch patch = new BitHeaderPoolPerformancePatch();
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")));
}
}
@@ -0,0 +1,193 @@
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.junit.jupiter.api.io.TempDir;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import java.nio.file.Files;
import java.nio.file.Path;
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_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.ASTORE;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.IFNE;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoChunkSaveDirectoryPerformancePatchTest
{
private static final String CHUNK = "zombie/iso/IsoChunk";
private static final String FILENAMES = "zombie/ChunkMapFilenames";
/**
* {@code IsoChunk} with a reduced {@code Save(boolean)}:
*
* <pre>{@code
* public static String world;
*
* public void Save(boolean bPreventChunkReuse)
* {
* File testDir = new ChunkMapFilenames().getDir(world);
* if (!testDir.exists()) testDir.mkdir();
* }
* }</pre>
*/
private static ClassNode chunk()
{
return IsoChunkSaveDirectoryPerformancePatchTest.chunk(2);
}
/** {@link #chunk()} whose {@code mkdir} call uses the local {@code mkdirLocal} (the folder is in 2). */
private static ClassNode chunk(int mkdirLocal)
{
ClassNode node = IsoChunkSaveDirectoryPerformancePatchTest.emptyClass(IsoChunkSaveDirectoryPerformancePatchTest.CHUNK);
node.visitField(ACC_PUBLIC | ACC_STATIC, "world", "Ljava/lang/String;", null, null);
MethodVisitor save = node.visitMethod(ACC_PUBLIC, "Save", "(Z)V", null, null);
Label exists = new Label();
save.visitTypeInsn(NEW, IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES);
save.visitInsn(DUP);
save.visitMethodInsn(INVOKESPECIAL, IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES, "<init>", "()V", false);
save.visitFieldInsn(GETSTATIC, IsoChunkSaveDirectoryPerformancePatchTest.CHUNK, "world", "Ljava/lang/String;");
save.visitMethodInsn(INVOKEVIRTUAL, IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES, "getDir", "(Ljava/lang/String;)Ljava/io/File;", false);
save.visitVarInsn(ASTORE, 2);
save.visitVarInsn(ALOAD, 2);
save.visitMethodInsn(INVOKEVIRTUAL, "java/io/File", "exists", "()Z", false);
save.visitJumpInsn(IFNE, exists);
save.visitVarInsn(ALOAD, mkdirLocal);
save.visitMethodInsn(INVOKEVIRTUAL, "java/io/File", "mkdir", "()Z", false);
save.visitInsn(POP);
save.visitLabel(exists);
save.visitInsn(RETURN);
save.visitMaxs(0, 0);
return node;
}
/** {@code ChunkMapFilenames} whose {@code getDir(path)} is {@code new File(path)}. */
private static ClassNode filenames()
{
ClassNode node = IsoChunkSaveDirectoryPerformancePatchTest.emptyClass(IsoChunkSaveDirectoryPerformancePatchTest.FILENAMES);
MethodVisitor getDir = node.visitMethod(ACC_PUBLIC, "getDir", "(Ljava/lang/String;)Ljava/io/File;", null, null);
getDir.visitTypeInsn(NEW, "java/io/File");
getDir.visitInsn(DUP);
getDir.visitVarInsn(ALOAD, 1);
getDir.visitMethodInsn(INVOKESPECIAL, "java/io/File", "<init>", "(Ljava/lang/String;)V", false);
getDir.visitInsn(ARETURN);
getDir.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;
}
/** Runs {@code Save(false)} of {@code chunk} with {@code folder} as the checked folder. */
private static void save(ClassNode chunk, Path folder) throws ReflectiveOperationException
{
ClassDefiner definer = new ClassDefiner();
definer.define(IsoChunkSaveDirectoryPerformancePatchTest.filenames());
Class<?> loaded = definer.define(chunk);
loaded.getField("world").set(null, folder.toString());
loaded.getMethod("Save", boolean.class).invoke(loaded.getConstructor().newInstance(), false);
}
@Test
void anchorMatchesTheTarget()
{
new IsoChunkSaveDirectoryPerformancePatch().anchor().verify(IsoChunkSaveDirectoryPerformancePatchTest.chunk());
}
@Test
void vanillaCreatesTheFolder(@TempDir Path temp) throws ReflectiveOperationException
{
Path folder = temp.resolve("map");
IsoChunkSaveDirectoryPerformancePatchTest.save(IsoChunkSaveDirectoryPerformancePatchTest.chunk(), folder);
assertTrue(Files.isDirectory(folder));
}
@Test
void patchedSaveKeepsGetDirAndDropsTheCheck(@TempDir Path temp) throws ReflectiveOperationException
{
ClassNode chunk = IsoChunkSaveDirectoryPerformancePatchTest.chunk();
new IsoChunkSaveDirectoryPerformancePatch().apply(chunk);
List<String> calls = new ArrayList<>();
for (AbstractInsnNode instruction : chunk.methods.getLast().instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call.name);
}
assertEquals(List.of("<init>", "getDir"), calls);
Path folder = temp.resolve("map");
IsoChunkSaveDirectoryPerformancePatchTest.save(chunk, folder);
assertFalse(Files.exists(folder));
}
@Test
void failsWhenTheCheckUsesAnotherFolder()
{
ClassNode chunk = IsoChunkSaveDirectoryPerformancePatchTest.chunk(1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new IsoChunkSaveDirectoryPerformancePatch().apply(chunk));
assertTrue(e.getMessage().contains("does not use the folder"), e.getMessage());
}
@Test
void failsWithoutTheFolderCheck()
{
ClassNode chunk = IsoChunkSaveDirectoryPerformancePatchTest.emptyClass(IsoChunkSaveDirectoryPerformancePatchTest.CHUNK);
MethodVisitor save = chunk.visitMethod(ACC_PUBLIC, "Save", "(Z)V", null, null);
save.visitInsn(RETURN);
save.visitMaxs(0, 0);
assertThrows(IllegalStateException.class, () -> new IsoChunkSaveDirectoryPerformancePatch().apply(chunk));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoChunkSaveDirectoryPerformancePatch patch = new IsoChunkSaveDirectoryPerformancePatch();
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")));
}
}
@@ -1,7 +1,7 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@@ -1,6 +1,6 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.GameVersion; import dev.overlord.zomboidforge.api.GameVersion;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassReader;
@@ -1,7 +1,7 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.objectweb.asm.Label; import org.objectweb.asm.Label;
@@ -1,6 +1,6 @@
package dev.overlord.zomboidforge.compat.b42.perf; package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.GameVersion; import dev.overlord.zomboidforge.api.GameVersion;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassReader;
@@ -0,0 +1,119 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
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.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class RolesSavePerformancePatchTest
{
private static final String ROLES = "zombie/characters/Roles";
private static final String DATABASE = "zombie/network/ServerWorldDatabase";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
/** {@code Roles} with a reduced {@code save()}: {@code ((ServerWorldDatabase) null).saveRole(null);} */
private static ClassNode roles()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, RolesSavePerformancePatchTest.ROLES, null, "java/lang/Object", null);
MethodVisitor save = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "save", "()V", null, null);
save.visitInsn(ACONST_NULL);
save.visitTypeInsn(CHECKCAST, RolesSavePerformancePatchTest.DATABASE);
save.visitInsn(ACONST_NULL);
save.visitTypeInsn(CHECKCAST, "zombie/characters/Role");
save.visitMethodInsn(INVOKEVIRTUAL, RolesSavePerformancePatchTest.DATABASE, "saveRole", "(Lzombie/characters/Role;)V", false);
save.visitInsn(RETURN);
save.visitMaxs(0, 0);
return node;
}
private static List<String> calls(MethodNode method)
{
List<String> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new RolesSavePerformancePatch().anchor().verify(RolesSavePerformancePatchTest.roles());
}
@Test
void wrapsSaveBetweenTheTransactionHooks()
{
ClassNode node = RolesSavePerformancePatchTest.roles();
new RolesSavePerformancePatch().apply(node);
MethodNode save = node.methods.stream().filter(method -> method.name.equals("save")).findFirst().orElseThrow();
MethodNode original = node.methods.stream().filter(method -> method.name.equals("zomboidForge$save")).findFirst().orElseThrow();
// The normal path and the exception path each end the transaction.
assertEquals(List.of("RolesHooks.beginSave", "Roles.zomboidForge$save", "RolesHooks.endSave", "RolesHooks.endSave"), RolesSavePerformancePatchTest.calls(save));
assertEquals(1, save.tryCatchBlocks.size());
assertEquals(List.of("ServerWorldDatabase.saveRole"), RolesSavePerformancePatchTest.calls(original));
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = RolesSavePerformancePatchTest.roles();
new RolesSavePerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the wrapper.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
@Test
void endSaveHookExistsAsPublicStaticMethod() throws IOException
{
ClassNode hooks = PackageScan.read(RolesSavePerformancePatchTest.HOOKS);
assertTrue(hooks.methods.stream().anyMatch(method ->
method.name.equals("endSave") && method.desc.equals("()V")
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
));
}
@Test
void appliesOnlyToVerifiedVersions()
{
RolesSavePerformancePatch patch = new RolesSavePerformancePatch();
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")));
}
}
@@ -0,0 +1,181 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
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_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
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.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ServerMapCellBudgetPerformancePatchTest
{
private static final String MAP = "zombie/network/ServerMap";
private static final String CELL = "zombie/network/ServerMap$ServerCell";
private static final String LOS = "zombie/network/ServerLOS";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ServerMapHooks";
/**
* {@code ServerMap} with a reduced {@code preupdate}:
*
* <pre>{@code
* public void preupdate()
* {
* ServerLOS.instance.suspend(); // when suspendFirst
* ((ServerCell) null).Load2();
* ServerLOS.instance.suspend(); // when suspendLast
* }
* }</pre>
*/
private static ClassNode serverMap(boolean suspendFirst, boolean suspendLast)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, ServerMapCellBudgetPerformancePatchTest.MAP, null, "java/lang/Object", null);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor preupdate = node.visitMethod(ACC_PUBLIC, "preupdate", "()V", null, null);
if (suspendFirst) ServerMapCellBudgetPerformancePatchTest.suspend(preupdate);
preupdate.visitInsn(ACONST_NULL);
preupdate.visitTypeInsn(CHECKCAST, ServerMapCellBudgetPerformancePatchTest.CELL);
preupdate.visitMethodInsn(INVOKEVIRTUAL, ServerMapCellBudgetPerformancePatchTest.CELL, "Load2", "()Z", false);
preupdate.visitInsn(POP);
if (suspendLast) ServerMapCellBudgetPerformancePatchTest.suspend(preupdate);
preupdate.visitInsn(RETURN);
preupdate.visitMaxs(0, 0);
return node;
}
private static void suspend(MethodVisitor method)
{
method.visitFieldInsn(GETSTATIC, ServerMapCellBudgetPerformancePatchTest.LOS, "instance", "L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";");
method.visitMethodInsn(INVOKEVIRTUAL, ServerMapCellBudgetPerformancePatchTest.LOS, "suspend", "()V", false);
}
private static ClassNode serverMap()
{
return ServerMapCellBudgetPerformancePatchTest.serverMap(true, false);
}
private static List<MethodInsnNode> calls(ClassNode node)
{
MethodNode preupdate = node.methods.stream().filter(method -> method.name.equals("preupdate")).findFirst().orElseThrow();
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : preupdate.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new ServerMapCellBudgetPerformancePatch().anchor().verify(ServerMapCellBudgetPerformancePatchTest.serverMap());
}
@Test
void redirectsSuspendAndLoad2ToTheHooks()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap();
new ServerMapCellBudgetPerformancePatch().apply(node);
List<MethodInsnNode> calls = ServerMapCellBudgetPerformancePatchTest.calls(node);
assertEquals(2, calls.size());
for (MethodInsnNode call : calls)
{
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals(ServerMapCellBudgetPerformancePatchTest.HOOKS, call.owner);
assertFalse(call.itf);
}
assertEquals("beginIntegration", calls.get(0).name);
assertEquals("(L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";)V", calls.get(0).desc);
assertEquals("integrate", calls.get(1).name);
assertEquals("(L" + ServerMapCellBudgetPerformancePatchTest.CELL + ";)Z", calls.get(1).desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap();
new ServerMapCellBudgetPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the changed method.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutTheSuspend()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap(false, false);
assertThrows(IllegalStateException.class, () -> new ServerMapCellBudgetPerformancePatch().apply(node));
}
@Test
void failsWhenTheSuspendComesAfterLoad2()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap(false, true);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerMapCellBudgetPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("comes after"), e.getMessage());
}
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
@Test
void beginIntegrationHookExistsAsPublicStaticMethod() throws IOException
{
ClassNode hooks = PackageScan.read(ServerMapCellBudgetPerformancePatchTest.HOOKS);
assertTrue(hooks.methods.stream().anyMatch(method ->
method.name.equals("beginIntegration")
&& method.desc.equals("(L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";)V")
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
));
}
@Test
void appliesOnlyToVerifiedVersions()
{
ServerMapCellBudgetPerformancePatch patch = new ServerMapCellBudgetPerformancePatch();
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")));
}
}
@@ -0,0 +1,131 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.patches.ThreadSleepPerformancePatch;
import org.jspecify.annotations.NonNull;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
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.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.LCONST_1;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
/** The five Build 42 waiting-loop patches: each with its target, number of sleeps and hook. */
class ThreadSleepPatchesTest
{
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WaitHooks";
/** Each patch with its target method, number of sleeps and hook. */
private record Case(ThreadSleepPerformancePatch patch, String target, String method, int sleeps, String hook)
{
@Override
public @NonNull String toString() { return this.patch.getClass().getSimpleName(); }
}
private static Stream<Case> cases()
{
return Stream.of(
new Case(new ServerChunkLoaderQuitPerformancePatch(), "zombie/network/ServerChunkLoader", "quit", 2, "pollSleep"),
new Case(new ZipBackupWaitPerformancePatch(), "zombie/core/backup/ZipBackup", "waitFinish", 1, "pollSleep"),
new Case(new ServerPlayersVehiclesRoundPerformancePatch(), "zombie/network/ServerPlayersVehicles$SPVThread", "runInner", 1, "vehicleRoundSleep"),
new Case(new ServerPlayersVehiclesStopPerformancePatch(), "zombie/network/ServerPlayersVehicles", "stop", 1, "wakeVehiclesAndPoll"),
new Case(new ServerPlayerDBSaveWaitPerformancePatch(), "zombie/savefile/ServerPlayerDB", "saveFinishWait", 1, "wakeVehiclesAndPoll")
);
}
/** The target class with {@code method()} calling {@code Thread.sleep(1L)} {@code sleeps} times. */
private static ClassNode target(Case test, int sleeps)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, test.target(), null, "java/lang/Object", null);
MethodVisitor method = node.visitMethod(ACC_PUBLIC, test.method(), "()V", null, null);
for (int i = 0; i < sleeps; i++)
{
method.visitInsn(LCONST_1);
method.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "sleep", "(J)V", false);
}
method.visitInsn(RETURN);
method.visitMaxs(0, 0);
return node;
}
private static List<MethodInsnNode> calls(ClassNode node)
{
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : node.methods.getFirst().instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call);
}
return calls;
}
@ParameterizedTest
@MethodSource("cases")
void anchorMatchesTheTarget(Case test)
{
test.patch().anchor().verify(ThreadSleepPatchesTest.target(test, test.sleeps()));
}
@ParameterizedTest
@MethodSource("cases")
void redirectsEverySleepToItsHook(Case test) throws ClassNotFoundException
{
ClassNode node = ThreadSleepPatchesTest.target(test, test.sleeps());
test.patch().apply(node);
List<MethodInsnNode> calls = ThreadSleepPatchesTest.calls(node);
assertEquals(test.sleeps(), calls.size());
for (MethodInsnNode call : calls)
{
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals(ThreadSleepPatchesTest.HOOKS, call.owner);
assertEquals(test.hook(), call.name);
assertEquals("(J)V", call.desc);
}
assertEquals(test.hook(), test.patch().hook().name());
// Initializing links the class, which runs the bytecode verifier on the changed method.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@ParameterizedTest
@MethodSource("cases")
void failsForAnotherNumberOfSleeps(Case test)
{
ClassNode node = ThreadSleepPatchesTest.target(test, test.sleeps() + 1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> test.patch().apply(node));
assertTrue(e.getMessage().contains("found " + (test.sleeps() + 1)), e.getMessage());
}
@ParameterizedTest
@MethodSource("cases")
void appliesOnlyToVerifiedVersions(Case test)
{
assertTrue(test.patch().appliesTo(GameVersion.parse("42.21.0")));
assertTrue(test.patch().appliesTo(GameVersion.parse("42.21.3")));
assertFalse(test.patch().appliesTo(GameVersion.parse("42.20.3")));
assertFalse(test.patch().appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -0,0 +1,160 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
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_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
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.IRETURN;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class WorldGenChunkRulesPerformancePatchTest
{
private static final String CHUNK = "zombie/iso/worldgen/WorldGenChunk";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks";
private static final String MATCHES = "(Ljava/lang/String;)Z";
/**
* {@code WorldGenChunk} with a reduced {@code isProtected} ({@code return tile.matches(null);})
* and, when {@code withCleanChunk}, a reduced {@code cleanChunk}
* ({@code material.matches(filter);}).
*/
private static ClassNode chunk(boolean withCleanChunk)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, WorldGenChunkRulesPerformancePatchTest.CHUNK, null, "java/lang/Object", null);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor isProtected = node.visitMethod(ACC_PUBLIC, "isProtected", "(Ljava/util/List;Ljava/lang/String;)Z", null, null);
isProtected.visitVarInsn(ALOAD, 2);
isProtected.visitInsn(ACONST_NULL);
isProtected.visitTypeInsn(CHECKCAST, "java/lang/String");
isProtected.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", WorldGenChunkRulesPerformancePatchTest.MATCHES, false);
isProtected.visitInsn(IRETURN);
isProtected.visitMaxs(0, 0);
if (withCleanChunk)
{
MethodVisitor cleanChunk = node.visitMethod(ACC_PUBLIC, "cleanChunk", "(Lzombie/iso/IsoChunk;Ljava/lang/String;Ljava/lang/String;)V", null, null);
cleanChunk.visitVarInsn(ALOAD, 2);
cleanChunk.visitVarInsn(ALOAD, 3);
cleanChunk.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", WorldGenChunkRulesPerformancePatchTest.MATCHES, false);
cleanChunk.visitInsn(POP);
cleanChunk.visitInsn(RETURN);
cleanChunk.visitMaxs(0, 0);
}
return node;
}
private static List<MethodInsnNode> calls(ClassNode node, String methodName)
{
MethodNode method = node.methods.stream().filter(m -> m.name.equals(methodName)).findFirst().orElseThrow();
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new WorldGenChunkRulesPerformancePatch().anchor().verify(WorldGenChunkRulesPerformancePatchTest.chunk(true));
}
@Test
void replacesIsProtectedAndTheMatchesCallOfCleanChunk()
{
ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(true);
new WorldGenChunkRulesPerformancePatch().apply(node);
List<MethodInsnNode> isProtected = WorldGenChunkRulesPerformancePatchTest.calls(node, "isProtected");
assertEquals(1, isProtected.size());
assertEquals(INVOKESTATIC, isProtected.getFirst().getOpcode());
assertEquals(WorldGenChunkRulesPerformancePatchTest.HOOKS, isProtected.getFirst().owner);
assertEquals("isProtected", isProtected.getFirst().name);
List<MethodInsnNode> cleanChunk = WorldGenChunkRulesPerformancePatchTest.calls(node, "cleanChunk");
assertEquals(1, cleanChunk.size());
assertEquals(INVOKESTATIC, cleanChunk.getFirst().getOpcode());
assertEquals(WorldGenChunkRulesPerformancePatchTest.HOOKS, cleanChunk.getFirst().owner);
assertEquals("matches", cleanChunk.getFirst().name);
assertEquals("(Ljava/lang/String;Ljava/lang/String;)Z", cleanChunk.getFirst().desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(true);
new WorldGenChunkRulesPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on both changed methods.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutCleanChunk()
{
ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(false);
assertThrows(IllegalStateException.class, () -> new WorldGenChunkRulesPerformancePatch().apply(node));
}
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
@Test
void matchesHookExistsAsPublicStaticMethod() throws IOException
{
ClassNode hooks = PackageScan.read(WorldGenChunkRulesPerformancePatchTest.HOOKS);
assertTrue(hooks.methods.stream().anyMatch(method ->
method.name.equals("matches")
&& method.desc.equals("(Ljava/lang/String;Ljava/lang/String;)Z")
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
));
}
@Test
void appliesOnlyToVerifiedVersions()
{
WorldGenChunkRulesPerformancePatch patch = new WorldGenChunkRulesPerformancePatch();
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")));
}
}
@@ -0,0 +1,134 @@
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.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
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_PUBLIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
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.IRETURN;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class WorldGenUtilsPlacementPerformancePatchTest
{
private static final String UTILS = "zombie/iso/worldgen/WorldGenUtils";
/**
* {@code WorldGenUtils} with a reduced {@code canPlace}:
* {@code return floorName.matches((String) placement.get(0));}, reading {@code this} first
* when {@code usesThis}.
*/
private static ClassNode utils(boolean usesThis)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, WorldGenUtilsPlacementPerformancePatchTest.UTILS, null, "java/lang/Object", null);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor canPlace = node.visitMethod(ACC_PUBLIC, "canPlace", "(Ljava/util/List;Ljava/lang/String;)Z", null, null);
if (usesThis)
{
canPlace.visitVarInsn(ALOAD, 0);
canPlace.visitInsn(POP);
}
canPlace.visitVarInsn(ALOAD, 2);
canPlace.visitVarInsn(ALOAD, 1);
canPlace.visitInsn(ICONST_0);
canPlace.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;", true);
canPlace.visitTypeInsn(CHECKCAST, "java/lang/String");
canPlace.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", "(Ljava/lang/String;)Z", false);
canPlace.visitInsn(IRETURN);
canPlace.visitMaxs(0, 0);
return node;
}
private static List<AbstractInsnNode> instructions(ClassNode node)
{
MethodNode canPlace = node.methods.stream().filter(method -> method.name.equals("canPlace")).findFirst().orElseThrow();
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : canPlace.instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
return instructions;
}
@Test
void anchorMatchesTheTarget()
{
new WorldGenUtilsPlacementPerformancePatch().anchor().verify(WorldGenUtilsPlacementPerformancePatchTest.utils(false));
}
@Test
void replacesTheBodyWithTheHookCall()
{
ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(false);
new WorldGenUtilsPlacementPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = WorldGenUtilsPlacementPerformancePatchTest.instructions(node);
assertEquals(List.of(ALOAD, ALOAD, INVOKESTATIC, IRETURN), instructions.stream().map(AbstractInsnNode::getOpcode).toList());
MethodInsnNode call = (MethodInsnNode) instructions.get(2);
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks", call.owner);
assertEquals("canPlace", call.name);
assertEquals("(Ljava/util/List;Ljava/lang/String;)Z", call.desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(false);
new WorldGenUtilsPlacementPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the new body.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWhenTheBodyUsesThis()
{
ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(true);
assertThrows(IllegalStateException.class, () -> new WorldGenUtilsPlacementPerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
WorldGenUtilsPlacementPerformancePatch patch = new WorldGenUtilsPlacementPerformancePatch();
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")));
}
}
@@ -0,0 +1,157 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
import dev.overlord.zomboidforge.compat.b42.patches.BackupStoragePatch;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
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.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ZipBackupSinglePassPerformancePatchTest
{
private static final String ZIP_BACKUP = "zombie/core/backup/ZipBackup";
private static final String DESC = "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V";
private static final String SCATTER = "org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator";
private static final String STREAM = "org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream";
/** {@code ZipBackup} with a reduced {@code makeBackupFile}: {@code ((ParallelScatterZipCreator) null).writeTo(null);} */
private static ClassNode zipBackup()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, ZipBackupSinglePassPerformancePatchTest.ZIP_BACKUP, null, "java/lang/Object", null);
MethodVisitor make = node.visitMethod(ACC_PRIVATE | ACC_STATIC, "makeBackupFile", ZipBackupSinglePassPerformancePatchTest.DESC, null, null);
make.visitInsn(ACONST_NULL);
make.visitTypeInsn(CHECKCAST, ZipBackupSinglePassPerformancePatchTest.SCATTER);
make.visitInsn(ACONST_NULL);
make.visitTypeInsn(CHECKCAST, ZipBackupSinglePassPerformancePatchTest.STREAM);
make.visitMethodInsn(INVOKEVIRTUAL, ZipBackupSinglePassPerformancePatchTest.SCATTER, "writeTo", "(L" + ZipBackupSinglePassPerformancePatchTest.STREAM + ";)V", false);
make.visitInsn(RETURN);
make.visitMaxs(0, 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<String> calls(MethodNode method)
{
List<String> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new ZipBackupSinglePassPerformancePatch().anchor().verify(ZipBackupSinglePassPerformancePatchTest.zipBackup());
}
@Test
void replacesTheBodyWithTheHookCall()
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
new ZipBackupSinglePassPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : ZipBackupSinglePassPerformancePatchTest.method(node, "makeBackupFile").instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
assertEquals(List.of(ALOAD, ALOAD, INVOKESTATIC, RETURN), instructions.stream().map(AbstractInsnNode::getOpcode).toList());
MethodInsnNode call = (MethodInsnNode) instructions.get(2);
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks", call.owner);
assertEquals("makeBackupFile", call.name);
assertEquals("(Ljava/lang/String;Ljava/lang/Object;)V", call.desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
new ZipBackupSinglePassPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the new body.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
/** As in {@link B42PatchSet}: this patch first, then the storage wrapper around the hook call. */
@Test
void storagePatchWrapsTheReplacedBody()
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
BackupStoragePatch storage = new BackupStoragePatch();
new ZipBackupSinglePassPerformancePatch().apply(node);
storage.anchor().verify(node);
storage.apply(node);
assertEquals(List.of("StorageHooks.backupRunning", "ZipBackup.zomboidForge$makeBackupFile", "StorageHooks.backupRunning", "StorageHooks.backupRunning"),
ZipBackupSinglePassPerformancePatchTest.calls(ZipBackupSinglePassPerformancePatchTest.method(node, "makeBackupFile")));
assertEquals(List.of("BackupHooks.makeBackupFile"),
ZipBackupSinglePassPerformancePatchTest.calls(ZipBackupSinglePassPerformancePatchTest.method(node, "zomboidForge$makeBackupFile")));
}
@Test
void registeredBeforeTheStoragePatch()
{
List<String> names = new B42PatchSet().patches().stream().map(ClassPatch::getClass).map(Class::getSimpleName).toList();
assertTrue(names.indexOf("ZipBackupSinglePassPerformancePatch") >= 0);
assertTrue(names.indexOf("ZipBackupSinglePassPerformancePatch") < names.indexOf("BackupStoragePatch"));
}
/** After the storage patch, {@code makeBackupFile} is the wrapper, which the hook must not replace. */
@Test
void anchorFailsOnTheStorageWrapper()
{
ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
new BackupStoragePatch().apply(node);
assertThrows(IllegalStateException.class, () -> new ZipBackupSinglePassPerformancePatch().anchor().verify(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
ZipBackupSinglePassPerformancePatch patch = new ZipBackupSinglePassPerformancePatch();
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")));
}
}
@@ -0,0 +1,188 @@
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.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
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.DLOAD;
import static org.objectweb.asm.Opcodes.DRETURN;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ZombieVoronoiPerformancePatchTest
{
private static final String VORONOI = "zombie/iso/worldgen/zombie/ZombieVoronoi";
private static final String SELECTION = "zombie/iso/worldgen/zombie/ClosestSelection";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks";
private static final String NOISE = "(DDLjava/util/Random;Ljava/util/List;)D";
/**
* {@code ZombieVoronoi} with its three fields and a reduced {@code evaluateNoise}:
*
* <pre>{@code
* private double evaluateNoise(double x, double y, Random rng, List points)
* {
* long unused = this.seed; // a local beyond the parameters
* return this.closestPoint.getClosest(x, y, points);
* }
* }</pre>
*/
private static ClassNode voronoi(boolean withSeed, int noiseAccess)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, ZombieVoronoiPerformancePatchTest.VORONOI, null, "java/lang/Object", null);
if (withSeed) node.visitField(ACC_PRIVATE | ACC_FINAL, "seed", "J", null, null);
node.visitField(ACC_PRIVATE | ACC_FINAL, "numberPoints", "I", null, null);
node.visitField(ACC_PRIVATE | ACC_FINAL, "closestPoint", "L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";", null, 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);
MethodVisitor noise = node.visitMethod(noiseAccess, "evaluateNoise", ZombieVoronoiPerformancePatchTest.NOISE, null, null);
Label start = new Label();
Label end = new Label();
noise.visitLabel(start);
noise.visitVarInsn(ALOAD, 0);
noise.visitFieldInsn(GETFIELD, ZombieVoronoiPerformancePatchTest.VORONOI, "closestPoint", "L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";");
noise.visitVarInsn(DLOAD, 1);
noise.visitVarInsn(DLOAD, 3);
noise.visitVarInsn(ALOAD, 6);
noise.visitMethodInsn(INVOKEINTERFACE, ZombieVoronoiPerformancePatchTest.SELECTION, "getClosest", "(DDLjava/util/List;)D", true);
noise.visitInsn(DRETURN);
noise.visitLabel(end);
noise.visitLocalVariable("unused", "J", null, start, end, 7);
noise.visitMaxs(0, 0);
return node;
}
private static ClassNode voronoi()
{
return ZombieVoronoiPerformancePatchTest.voronoi(true, ACC_PRIVATE);
}
private static MethodNode evaluateNoise(ClassNode node)
{
return node.methods.stream().filter(method -> method.name.equals("evaluateNoise")).findFirst().orElseThrow();
}
/** The real instructions: no labels, line numbers, or frames. */
private static List<AbstractInsnNode> instructions(MethodNode method)
{
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
return instructions;
}
@Test
void anchorMatchesTheTarget()
{
new ZombieVoronoiPerformancePatch().anchor().verify(ZombieVoronoiPerformancePatchTest.voronoi());
}
@Test
void replacesTheBodyWithTheHookCall()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi();
new ZombieVoronoiPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = ZombieVoronoiPerformancePatchTest.instructions(ZombieVoronoiPerformancePatchTest.evaluateNoise(node));
assertEquals(
List.of(ALOAD, GETFIELD, ALOAD, GETFIELD, ALOAD, GETFIELD, DLOAD, DLOAD, ALOAD, ALOAD, INVOKESTATIC, DRETURN),
instructions.stream().map(AbstractInsnNode::getOpcode).toList()
);
assertEquals(
List.of("closestPoint", "seed", "numberPoints"),
instructions.stream().filter(FieldInsnNode.class::isInstance).map(field -> ((FieldInsnNode) field).name).toList()
);
MethodInsnNode call = (MethodInsnNode) instructions.get(10);
assertEquals(ZombieVoronoiPerformancePatchTest.HOOKS, call.owner);
assertEquals("evaluateNoise", call.name);
assertEquals("(L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";JIDDLjava/util/Random;Ljava/util/List;)D", call.desc);
assertFalse(call.itf);
}
@Test
void dropsTheLocalVariablesOfTheOldBody()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi();
new ZombieVoronoiPerformancePatch().apply(node);
assertNull(ZombieVoronoiPerformancePatchTest.evaluateNoise(node).localVariables);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi();
new ZombieVoronoiPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the new body.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutTheSeedField()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(false, ACC_PRIVATE);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZombieVoronoiPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("'" + ZombieVoronoiPerformancePatchTest.VORONOI + ".seed J'"), e.getMessage());
}
@Test
void failsWhenTheMethodIsStatic()
{
ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(true, ACC_PRIVATE | ACC_STATIC);
assertThrows(IllegalStateException.class, () -> new ZombieVoronoiPerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
ZombieVoronoiPerformancePatch patch = new ZombieVoronoiPerformancePatch();
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")));
}
}
@@ -0,0 +1,197 @@
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.MethodVisitor;
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 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_FINAL;
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.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
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.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ZomboidFileSystemInitPerformancePatchTest
{
private static final String FILE_SYSTEM = "zombie/ZomboidFileSystem";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ZomboidFileSystemHooks";
/**
* {@code ZomboidFileSystem} with a reduced {@code init}:
*
* <pre>{@code
* public void init()
* {
* this.searchFolders((File) null); // when search is true
* this.getRelativeFile((String) null); // when relative is true
* this.searchFolders((File) null); // when searchLast is true
* this.loadList.clear();
* }
* }</pre>
*/
private static ClassNode fileSystem(boolean withSets, boolean search, boolean relative, boolean searchLast)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ACC_FINAL, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, null, "java/lang/Object", null);
node.visitField(ACC_PRIVATE | ACC_FINAL, "loadList", "Ljava/util/List;", null, null);
if (withSets) node.visitField(ACC_PRIVATE | ACC_FINAL, "allAbsolutePaths", "Ljava/util/Set;", null, null);
MethodVisitor constructor = node.visitMethod(ACC_PRIVATE, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "init", "()V", null, null);
if (search) ZomboidFileSystemInitPerformancePatchTest.callSearchFolders(init);
if (relative)
{
init.visitVarInsn(ALOAD, 0);
init.visitInsn(ACONST_NULL);
init.visitTypeInsn(CHECKCAST, "java/lang/String");
init.visitMethodInsn(INVOKEVIRTUAL, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, "getRelativeFile", "(Ljava/lang/String;)Ljava/lang/String;", false);
init.visitInsn(POP);
}
if (searchLast) ZomboidFileSystemInitPerformancePatchTest.callSearchFolders(init);
init.visitVarInsn(ALOAD, 0);
init.visitFieldInsn(GETFIELD, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, "loadList", "Ljava/util/List;");
init.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "clear", "()V", true);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
private static void callSearchFolders(MethodVisitor init)
{
init.visitVarInsn(ALOAD, 0);
init.visitInsn(ACONST_NULL);
init.visitTypeInsn(CHECKCAST, "java/io/File");
init.visitMethodInsn(INVOKEVIRTUAL, ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM, "searchFolders", "(Ljava/io/File;)V", false);
}
private static ClassNode fileSystem()
{
return ZomboidFileSystemInitPerformancePatchTest.fileSystem(true, true, true, false);
}
private static MethodNode init(ClassNode node)
{
return node.methods.stream().filter(method -> method.name.equals("init")).findFirst().orElseThrow();
}
/** The real instructions: no labels, line numbers, or frames. */
private static List<AbstractInsnNode> instructions(MethodNode method)
{
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
return instructions;
}
@Test
void anchorMatchesTheTarget()
{
new ZomboidFileSystemInitPerformancePatch().anchor().verify(ZomboidFileSystemInitPerformancePatchTest.fileSystem());
}
@Test
void replacesTheCallWithTheHookAndPassesBothFields()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem();
new ZomboidFileSystemInitPerformancePatch().apply(node);
List<AbstractInsnNode> instructions = ZomboidFileSystemInitPerformancePatchTest.instructions(ZomboidFileSystemInitPerformancePatchTest.init(node));
assertEquals(
List.of(ALOAD, ACONST_NULL, CHECKCAST, ALOAD, GETFIELD, ALOAD, GETFIELD, INVOKESTATIC),
instructions.subList(0, 8).stream().map(AbstractInsnNode::getOpcode).toList()
);
assertEquals("loadList", ((FieldInsnNode) instructions.get(4)).name);
assertEquals("allAbsolutePaths", ((FieldInsnNode) instructions.get(6)).name);
MethodInsnNode call = (MethodInsnNode) instructions.get(7);
assertEquals(ZomboidFileSystemInitPerformancePatchTest.HOOKS, call.owner);
assertEquals("searchAndIndex", call.name);
assertEquals("(L" + ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM + ";Ljava/io/File;Ljava/util/List;Ljava/util/Set;)V", call.desc);
assertFalse(call.itf);
// The loop after the call stays as it is.
assertTrue(instructions.stream().anyMatch(instruction -> instruction instanceof MethodInsnNode m && m.name.equals("getRelativeFile")));
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem();
new ZomboidFileSystemInitPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the changed method.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutTheLoopAfterTheCall()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem(true, true, false, false);
assertThrows(IllegalStateException.class, () -> new ZomboidFileSystemInitPerformancePatch().apply(node));
}
@Test
void failsWhenTheCallComesAfterTheLoop()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem(true, false, true, true);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZomboidFileSystemInitPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("after 'getRelativeFile'"), e.getMessage());
}
@Test
void failsWithoutTheAbsolutePathsField()
{
ClassNode node = ZomboidFileSystemInitPerformancePatchTest.fileSystem(false, true, true, false);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZomboidFileSystemInitPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("'" + ZomboidFileSystemInitPerformancePatchTest.FILE_SYSTEM + ".allAbsolutePaths Ljava/util/Set;'"), e.getMessage());
}
@Test
void appliesOnlyToVerifiedVersions()
{
ZomboidFileSystemInitPerformancePatch patch = new ZomboidFileSystemInitPerformancePatch();
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")));
}
}
+2
View File
@@ -10,6 +10,8 @@ dependencies {
implementation(project(":api")) implementation(project(":api"))
compileOnly(files(projectZomboid.serverJar)) compileOnly(files(projectZomboid.serverJar))
// ModCommandsTest checks command classes against the game's command framework.
testImplementation(files(projectZomboid.serverJar))
testImplementation(platform(libs.junit.bom)) testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter) testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher) testRuntimeOnly(libs.junit.platform.launcher)
@@ -0,0 +1,15 @@
package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
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(
ModCommands::check, ClientCommandChannel::prepare
);
private ForgeInstance() {}
}
@@ -0,0 +1,55 @@
package dev.overlord.zomboidforge.compat.b42.commands;
import dev.overlord.zomboidforge.api.PlayerRef;
import org.jetbrains.annotations.Nullable;
import se.krka.kahlua.vm.KahluaTable;
import zombie.Lua.LuaManager;
import zombie.characters.IsoPlayer;
import zombie.network.GameServer;
import java.util.Map;
/** Client commands in Build 42: players as {@link PlayerRef}s, and server commands to clients. */
public final class ClientCommandChannel
{
private ClientCommandChannel() {}
public static PlayerRef ref(IsoPlayer player) { return new PlayerRef(player.getOnlineID(), player.getUsername()); }
/**
* Copies {@code args} at once and returns the action that sends the command with
* {@code GameServer.sendServerCommand}, to every connection when {@code player} is
* {@code null}. The action runs on the main thread and sends nothing when the player is no
* longer connected.
*
* @throws IllegalArgumentException naming a key or value that cannot be sent
*/
public static Runnable prepare(@Nullable PlayerRef player, String module, String command, Map<?, ?> args)
{
Map<Object, Object> copy = LuaTables.copy(args);
return () ->
{
KahluaTable table = copy.isEmpty() ? null : LuaTables.toLua(copy, LuaManager.platform::newTable);
if (player == null) {
GameServer.sendServerCommand(module, command, table);
return;
}
IsoPlayer target = ClientCommandChannel.find(player);
if (target != null) GameServer.sendServerCommand(target, module, command, table);
};
}
/** The connected player with the online id and the username of {@code player}, or {@code null}. Main thread. */
private static @Nullable IsoPlayer find(PlayerRef player)
{
Object connected = GameServer.IDToPlayerMap.get((short) player.onlineId());
return connected instanceof IsoPlayer target && player.username().equals(target.getUsername()) ? target : null;
}
}
@@ -0,0 +1,134 @@
package dev.overlord.zomboidforge.compat.b42.commands;
import org.jetbrains.annotations.Nullable;
import se.krka.kahlua.vm.KahluaTable;
import se.krka.kahlua.vm.KahluaTableIterator;
import zombie.inventory.InventoryItem;
import zombie.iso.IsoDirections;
import zombie.iso.objects.IsoDeadBody;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* Conversion between the Kahlua tables of command arguments and the Java maps of the API. The
* types are those {@code TableNetworkUtils} sends: {@code String} and {@code Double} keys;
* {@code String}, {@code Double}, {@code Boolean}, table, {@code InventoryItem},
* {@code IsoDirections}, and {@code IsoDeadBody} values.
*/
public final class LuaTables
{
private LuaTables() {}
/** {@code table} as an unmodifiable map, nested tables as nested maps; empty for {@code null}. */
public static Map<Object, Object> toJava(@Nullable KahluaTable table)
{
if (table == null) return Map.of();
Map<Object, Object> map = new LinkedHashMap<>();
KahluaTableIterator iterator = table.iterator();
while (iterator.advance())
{
Object value = iterator.getValue();
map.put(iterator.getKey(), value instanceof KahluaTable nested ? LuaTables.toJava(nested) : value);
}
return Collections.unmodifiableMap(map);
}
/**
* A deep, unmodifiable copy of {@code args} in Lua's types: number keys and values become
* {@code Double}, lists become maps with the keys {@code 1.0}, {@code 2.0}, ....
*
* @throws IllegalArgumentException naming the first key or value that cannot be sent, or a
* map or list that contains itself
*/
public static Map<Object, Object> copy(Map<?, ?> args) { return LuaTables.copy(args, "args", Collections.newSetFromMap(new IdentityHashMap<>())); }
/** A new table with the entries of {@code args}, a result of {@link #copy}; nested maps become nested tables. */
public static KahluaTable toLua(Map<Object, Object> args, Supplier<KahluaTable> newTable)
{
KahluaTable table = newTable.get();
for (Map.Entry<Object, Object> entry : args.entrySet())
{
Object value = entry.getValue();
@SuppressWarnings("unchecked")
Object luaValue = value instanceof Map<?, ?> nested ? LuaTables.toLua((Map<Object, Object>) nested, newTable) : value;
table.rawset(entry.getKey(), luaValue);
}
return table;
}
private static Map<Object, Object> copy(Map<?, ?> map, String path, Set<Object> open)
{
if (!open.add(map)) throw new IllegalArgumentException("'" + path + "' contains itself.");
Map<Object, Object> copy = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : map.entrySet())
{
Object key = LuaTables.key(entry.getKey(), path);
String here = path + "[" + key + "]";
copy.put(key, LuaTables.value(entry.getValue(), here, open));
}
open.remove(map);
return Collections.unmodifiableMap(copy);
}
private static Map<Object, Object> copy(List<?> list, String path, Set<Object> open)
{
if (!open.add(list)) throw new IllegalArgumentException("'" + path + "' contains itself.");
Map<Object, Object> copy = new LinkedHashMap<>();
for (int i = 0; i < list.size(); i++) copy.put((double) (i + 1), LuaTables.value(list.get(i), path + "[" + (i + 1) + "]", open));
open.remove(list);
return Collections.unmodifiableMap(copy);
}
private static Object key(@Nullable Object key, String path)
{
if (key instanceof String) return key;
if (key instanceof Number number) return number.doubleValue();
throw new IllegalArgumentException("'" + path + "' has the key '" + key + "'" + LuaTables.typeOf(key) + "; keys are strings or numbers.");
}
private static Object value(@Nullable Object value, String path, Set<Object> open)
{
return switch (value)
{
case String string -> string;
case Boolean bool -> bool;
case Number number -> number.doubleValue();
case Map<?, ?> map -> LuaTables.copy(map, path, open);
case List<?> list -> LuaTables.copy(list, path, open);
case InventoryItem item -> item;
case IsoDirections direction -> direction;
case IsoDeadBody body -> body;
case null -> throw new IllegalArgumentException("'" + path + "' is null.");
default -> throw new IllegalArgumentException(
"'" + path + "' is a '" + value.getClass().getName() + "'; values are strings, numbers, booleans, maps, lists, inventory items, directions, or dead bodies."
);
};
}
private static String typeOf(@Nullable Object value) { return value == null ? "" : " ('" + value.getClass().getName() + "')"; }
}
@@ -0,0 +1,111 @@
package dev.overlord.zomboidforge.compat.b42.commands;
import org.jetbrains.annotations.Nullable;
import zombie.characters.Role;
import zombie.commands.CommandBase;
import zombie.commands.CommandName;
import zombie.commands.RequiredCapability;
import zombie.core.raknet.UdpConnection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Command classes of mods in Build 42: subclasses of {@code CommandBase}, which
* {@code GameServer.handleServerCommand} creates through {@code getConstructors()[0]} with
* {@code (username, role, command, connection)}.
*/
public final class ModCommands
{
private static final Class<?>[] CONSTRUCTOR = {String.class, Role.class, String.class, UdpConnection.class};
/**
* Names are inserted into a regular expression by {@code findCommandCls}, so they are limited
* to word characters. With such names, {@code ^name\b} matches the input exactly when its first
* word equals the name, ignoring case.
*/
private static final Pattern NAME = Pattern.compile("\\w+");
private ModCommands() {}
/**
* Fails unless {@code command} is a usable Build 42 command whose names are not taken by
* Project Zomboid's commands or by {@code registered}.
*
* @throws IllegalArgumentException listing every problem
*/
public static void check(Class<?> command, List<Class<?>> registered)
{
List<String> problems = new ArrayList<>();
int modifiers = command.getModifiers();
if (!CommandBase.class.isAssignableFrom(command)) problems.add("it does not extend '" + CommandBase.class.getName() + "'");
if (!Modifier.isPublic(modifiers)) problems.add("it is not public");
if (Modifier.isAbstract(modifiers)) problems.add("it is abstract");
Constructor<?>[] constructors = command.getConstructors();
if (constructors.length != 1 || !Arrays.equals(constructors[0].getParameterTypes(), ModCommands.CONSTRUCTOR))
problems.add("it needs exactly one public constructor '(String, Role, String, UdpConnection)'");
if (command.getAnnotationsByType(RequiredCapability.class).length == 0)
problems.add("it has no @RequiredCapability, and Project Zomboid runs no command without one");
CommandName[] names = command.getAnnotationsByType(CommandName.class);
if (names.length == 0) problems.add("it has no @CommandName");
for (CommandName name : names)
{
if (!ModCommands.NAME.matcher(name.name()).matches()) {
problems.add("the name '" + name.name() + "' contains characters other than letters, digits, and '_'");
continue;
}
Class<?> owner = ModCommands.owner(name.name(), registered);
if (owner != null) problems.add("the name '" + name.name() + "' is taken by '" + owner.getName() + "'");
}
if (!problems.isEmpty()) throw new IllegalArgumentException("'" + command.getName() + "' cannot be a command: " + String.join("; ", problems) + ".");
}
/**
* The first class of {@code commands} that is not disabled and has a name that {@code input}
* starts with, matched like {@code CommandBase.findCommandCls} matches Project Zomboid's
* commands; {@code null} when there is none.
*/
public static @Nullable Class<?> find(List<Class<?>> commands, String input)
{
for (Class<?> command : commands)
{
if (CommandBase.isDisabled(command)) continue;
for (CommandName name : command.getAnnotationsByType(CommandName.class)) {
if (Pattern.compile("^" + name.name() + "\\b", Pattern.CASE_INSENSITIVE).matcher(input).find()) return command;
}
}
return null;
}
/** The class among Project Zomboid's commands and {@code registered} that has {@code name}, ignoring case. */
private static @Nullable Class<?> owner(String name, List<Class<?>> registered)
{
Set<Class<?>> taken = new LinkedHashSet<>(Arrays.<Class<?>>asList(CommandBase.getSubClasses()));
taken.addAll(registered);
for (Class<?> command : taken)
{
for (CommandName existing : command.getAnnotationsByType(CommandName.class)) {
if (existing.name().equalsIgnoreCase(name)) return command;
}
}
return null;
}
}
@@ -0,0 +1,11 @@
/**
* Commands of mods in Build 42: checks for registered admin command classes and the lookup that
* mirrors {@code zombie.commands.CommandBase.findCommandCls}; client commands and the conversion
* of their Lua tables.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.commands;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,114 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.ParallelZip;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import zombie.ZomboidFileSystem;
import zombie.core.backup.ZipBackup;
import zombie.debug.DebugLog;
import zombie.debug.DebugType;
import zombie.debug.LogSeverity;
import zombie.iso.IsoChunk;
import zombie.network.CoopSlave;
/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
@SuppressWarnings("unused")
public final class BackupHooks
{
/** {@code ZipBackup.rotateBackupFile(BackupTypes)}, private, taking the enum as {@code Object}. */
private static final MethodHandle ROTATE;
/** {@code ZipBackup.getBackupReadme(String)}, private. */
private static final MethodHandle README;
/** The files of the cache folder that vanilla adds, each when it exists. */
private static final String[] FILES = {
"options.ini", "popman-options.ini", "latestSave.ini", "debug-options.ini", "sounds.ini", "gamepadBinding.config"
};
/** The folders of the cache folder whose top-level files vanilla adds. */
private static final String[] TOP_LEVEL_FOLDERS = { "mods", "Lua", "db", "Server" };
static
{
try
{
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(ZipBackup.class, MethodHandles.lookup());
Class<?> types = Class.forName("zombie.core.backup.ZipBackup$BackupTypes");
ROTATE = lookup.findStatic(ZipBackup.class, "rotateBackupFile", MethodType.methodType(void.class, types))
.asType(MethodType.methodType(void.class, Object.class));
README = lookup.findStatic(ZipBackup.class, "getBackupReadme", MethodType.methodType(String.class, String.class));
}
catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
}
private BackupHooks() {}
/**
* Replaces the body of {@code ZipBackup.makeBackupFile(String, BackupTypes)}; {@code type} is
* the {@code BackupTypes} constant, a private enum. Writes the same entries into
* {@code backups/<type>/backup_1.zip} as vanilla, after the same rotation: {@code readme.txt},
* the files of {@link #FILES}, the top-level files of {@link #TOP_LEVEL_FOLDERS} (vanilla's
* {@code zipDir(String, String)} skips every subfolder), and the save folder without the
* folders named {@code blam}, read under {@code IsoChunk.WriteLock}. {@link ParallelZip}
* writes them in one pass instead of vanilla's three. As vanilla, the backup logs its
* failures and does not throw.
*/
public static void makeBackupFile(String serverName, Object type)
{
String backupDir = ZomboidFileSystem.instance.getCacheDir() + File.separator + "backups" + File.separator + ((Enum<?>) type).name();
long startTime = System.currentTimeMillis();
DebugType.General.println("Start making backup");
DebugType.DetailedInfo.println("backup dir: " + backupDir);
CoopSlave.status("UI_ServerStatus_CreateBackup");
try
{
//noinspection ResultOfMethodCallIgnored
new File(backupDir).mkdirs();
BackupHooks.ROTATE.invokeExact(type);
Path zipFile = Paths.get(backupDir + File.separator + "backup_1.zip");
try { Files.deleteIfExists(zipFile); }
catch (IOException e) { DebugType.General.printException(e, LogSeverity.Error); }
String readme = (String) BackupHooks.README.invokeExact(serverName);
String saveDir = "Saves" + File.separator + "Multiplayer" + File.separator + serverName;
int threads = Runtime.getRuntime().availableProcessors();
try (ParallelZip zip = new ParallelZip(zipFile, readme, threads, e -> DebugType.General.printException(e, LogSeverity.Error)))
{
zip.addText("readme.txt", readme);
for (String name : BackupHooks.FILES)
{
Path file = Paths.get(ZomboidFileSystem.instance.getCacheDir() + File.separator + name);
if (Files.exists(file)) zip.addFile(name, file);
}
for (String folder : BackupHooks.TOP_LEVEL_FOLDERS) zip.addFolder(folder, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(folder)), subfolder -> false);
synchronized (IsoChunk.WriteLock)
{
zip.addFolder(saveDir, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(saveDir)), subfolder -> !subfolder.endsWith("blam"));
}
zip.finish();
}
}
// As vanilla's catch of Exception: errors pass; invokeExact declares Throwable.
catch (Error e) { throw e; }
catch (Throwable t) { DebugType.General.printException(t, LogSeverity.Error); }
DebugLog.log("Backup made in " + (System.currentTimeMillis() - startTime) + " ms");
}
}
@@ -0,0 +1,54 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.api.ClientCommandEvent;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
import dev.overlord.zomboidforge.compat.b42.commands.LuaTables;
import org.jetbrains.annotations.Nullable;
import se.krka.kahlua.vm.KahluaTable;
import zombie.characters.IsoPlayer;
/**
* Hooks called by patched {@code zombie.network.GameServer.receiveClientCommand} code, on the main
* thread (client commands are queued for the main loop). Exceptions are caught here; the command
* then reaches Lua as in vanilla.
*/
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
public final class ClientCommandHooks
{
private ClientCommandHooks() {}
/**
* Called directly before {@code LuaEventManager.triggerEvent("OnClientCommand", module, command, player, args)},
* after the vanilla checks (the player exists; {@code vehicle.remove} only with permission).
* Posts {@link ClientCommandEvent} when a mod listens for it.
*
* @param args {@code null} when the client sent no arguments
* @return {@code true} when a listener cancelled the event, which skips the Lua event
*/
public static boolean onClientCommand(String module, String command, IsoPlayer player, @Nullable KahluaTable args)
{
try
{
if (!ForgeInstance.FORGE.hasListeners(ClientCommandEvent.class)) return false;
ClientCommandEvent event = new ClientCommandEvent(
ClientCommandChannel.ref(player),
module, command,
LuaTables.toJava(args)
);
ForgeInstance.FORGE.post(event);
return event.isCancelled();
}
catch (Throwable t)
{
t.printStackTrace();
return false;
}
}
}
@@ -0,0 +1,61 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
/**
* Hooks called by patched {@code zombie.commands.CommandBase} code, on the main thread: the
* server console, RCON, and chat commands all run there. Exceptions are caught here, and the
* vanilla value is returned.
*/
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
public final class CommandHooks
{
private CommandHooks() {}
/**
* Replaces the {@code null} that {@code CommandBase.findCommandCls} returns when no command of
* Project Zomboid matches {@code command}: the mods' command class for it, or {@code null}.
*/
public static @Nullable Class<?> findCommand(@Nullable Class<?> vanilla, String command)
{
try
{
return ModCommands.find(ForgeInstance.FORGE.commands(), command);
}
catch (Throwable t)
{
t.printStackTrace();
return vanilla;
}
}
/**
* Replaces the array that {@code CommandBase.getSubClasses} returns: Project Zomboid's
* command classes followed by the mods', in registration order. Without mod commands, the
* vanilla array itself.
*/
public static Class<?>[] listCommands(Class<?>[] vanilla)
{
try
{
List<Class<?>> mods = ForgeInstance.FORGE.commands();
if (mods.isEmpty()) return vanilla;
Class<?>[] all = Arrays.copyOf(vanilla, vanilla.length + mods.size());
for (int i = 0; i < mods.size(); i++) all[vanilla.length + i] = mods.get(i);
return all;
}
catch (Throwable t)
{
t.printStackTrace();
return vanilla;
}
}
}
@@ -0,0 +1,82 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.sql.Connection;
import java.sql.SQLException;
import zombie.network.ServerWorldDatabase;
/**
* Hooks called by patched {@code zombie.characters.Roles} code: {@code Roles.save()} in one
* SQLite transaction.
*
* <p>{@code Roles.save()} writes every role and capability with its own statement, each in its
* own transaction on the autocommitting connection of {@code ServerWorldDatabase}: about 250
* transactions and 1,000 {@code fsync}s at every shutdown. In one transaction the same
* statements write the same rows. The hooks never fail the save: when the connection cannot be
* reached or switched, the save runs in autocommit mode as in vanilla.
*/
@SuppressWarnings("unused")
public final class RolesHooks
{
/** {@code ServerWorldDatabase.conn}, package-private; {@code null} when it cannot be reached. */
private static final @Nullable VarHandle CONNECTION;
static
{
VarHandle connection = null;
try
{
connection = MethodHandles.privateLookupIn(ServerWorldDatabase.class, MethodHandles.lookup())
.findVarHandle(ServerWorldDatabase.class, "conn", Connection.class);
}
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: 'ServerWorldDatabase.conn' not found: " + e); }
CONNECTION = connection;
}
/** The connection of the running save while it is in a transaction of these hooks. */
private static @Nullable Connection transaction;
private RolesHooks() {}
/** Called before {@code Roles.save()}: switches the database connection to one transaction. */
public static void beginSave()
{
if (RolesHooks.CONNECTION == null || ServerWorldDatabase.instance == null) return;
Connection connection = (Connection) RolesHooks.CONNECTION.get(ServerWorldDatabase.instance);
if (connection == null) return;
try
{
if (!connection.getAutoCommit()) return;
connection.setAutoCommit(false);
RolesHooks.transaction = connection;
}
catch (SQLException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: " + e); }
}
/**
* Called after {@code Roles.save()}, also when it threw: commits what it wrote, as autocommit
* would have, and switches autocommit back on.
*/
public static void endSave()
{
Connection connection = RolesHooks.transaction;
RolesHooks.transaction = null;
if (connection == null) return;
try { connection.commit(); }
catch (SQLException e) { System.out.println("[ZomboidForge] Committing the saved roles failed: " + e); }
finally
{
try { connection.setAutoCommit(true); }
catch (SQLException e) { System.out.println("[ZomboidForge] Switching the database back to autocommit failed: " + e); }
}
}
}
@@ -1,17 +1,110 @@
package dev.overlord.zomboidforge.compat.b42.hooks; package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.ZomboidForge; 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;
/** Hooks called by patched {@code zombie.network.GameServer} code. */ 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({"unused", "CallToPrintStackTrace"})
public final class ServerHooks public final class ServerHooks
{ {
private 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 * 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. * RCON is initialized; directly before the main loop starts.
*/ */
public static void onServerStarted() { public static void onServerStarted()
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ")."); {
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,49 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.FrameBudget;
import zombie.network.ServerLOS;
import zombie.network.ServerMap;
/** Hooks called by patched {@code zombie.network.ServerMap} code. */
@SuppressWarnings("unused")
public final class ServerMapHooks
{
/**
* Main-thread time per frame for integrating finished cells (frames target 100 ms). One
* integration takes 70 to 300 ms on new terrain, so in practice a frame integrates one cell,
* or a few small ones.
*/
private static final long BUDGET_NANOS = 40_000_000L;
private static final FrameBudget CELL_INTEGRATION = new FrameBudget(ServerMapHooks.BUDGET_NANOS, System::nanoTime);
private ServerMapHooks() {}
/**
* Replaces {@code ServerLOS.instance.suspend()} in {@code ServerMap.preupdate}, which precedes
* the loop that integrates the finished cells of this frame: suspends, then starts the
* frame's integration budget.
*/
public static void beginIntegration(ServerLOS los)
{
los.suspend();
ServerMapHooks.CELL_INTEGRATION.begin();
}
/**
* Replaces {@code cell.Load2()} in that loop. Vanilla integrates every finished cell in the
* frame it finishes; here a cell beyond the frame's budget is skipped: {@code false} keeps it
* in {@code ServerCell.loaded2}, at the front, and the loop of the next frame integrates it.
* The work per cell is unchanged; a cell becomes active up to a few frames later.
*/
public static boolean integrate(ServerMap.ServerCell cell)
{
if (!ServerMapHooks.CELL_INTEGRATION.allowsAnother()) return false;
boolean integrated = cell.Load2();
if (integrated) ServerMapHooks.CELL_INTEGRATION.count();
return integrated;
}
}
@@ -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({"unused", "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,51 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.WakeableSleep;
/**
* Hooks for the waiting loops of the shutdown and the world save, which poll with
* {@code Thread.sleep(100)} or {@code Thread.sleep(500)}: {@code ServerChunkLoader.quit},
* {@code ZipBackup.waitFinish}, {@code ServerPlayersVehicles.stop},
* {@code ServerPlayerDB.saveFinishWait}, and the round sleep of the
* {@code ServerPlayersVehicles} thread. The loops check the same conditions as in vanilla; the
* hooks only let them notice sooner that the condition holds.
*/
@SuppressWarnings("unused")
public final class WaitHooks
{
/** Longest sleep of a polling loop. */
private static final long POLL_MILLIS = 5L;
/** The round sleep of the {@code ServerPlayersVehicles} thread. */
private static final WakeableSleep VEHICLE_ROUND = new WakeableSleep();
private WaitHooks() {}
/** Replaces {@code Thread.sleep(millis)} in a polling loop: sleeps at most 5 ms. */
public static void pollSleep(long millis) throws InterruptedException
{
Thread.sleep(Math.min(millis, WaitHooks.POLL_MILLIS));
}
/**
* Replaces {@code Thread.sleep(500)} at the end of a round of the {@code ServerPlayersVehicles}
* thread ({@code SPVThread.runInner}): the same sleep, unless {@link #wakeVehiclesAndPoll}
* ends it early.
*/
public static void vehicleRoundSleep(long millis) throws InterruptedException
{
WaitHooks.VEHICLE_ROUND.sleep(millis);
}
/**
* Replaces {@code Thread.sleep(100)} in loops that wait for the {@code ServerPlayersVehicles}
* thread ({@code ServerPlayersVehicles.stop}: until it ended; {@code
* ServerPlayerDB.saveFinishWait}: until it saved the queued players): wakes the thread, so its
* next round starts now, then sleeps at most 5 ms.
*/
public static void wakeVehiclesAndPoll(long millis) throws InterruptedException
{
WaitHooks.VEHICLE_ROUND.wake();
Thread.sleep(Math.min(millis, WaitHooks.POLL_MILLIS));
}
}
Loaded 100 of 230 files, more files were not shown because too many files have changed in this diff. Show more